mutant-cafe 0.1.2 → 0.1.4
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 +106 -6
- package/dist/bin.js +932 -290
- package/dist/bin.js.map +4 -4
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -13,6 +13,7 @@ var RunConfig = Schema.Struct({
|
|
|
13
13
|
exclude: Schema.Array(Schema.String),
|
|
14
14
|
functionFilter: Schema.Array(Schema.String),
|
|
15
15
|
inDiff: Schema.optional(Schema.String),
|
|
16
|
+
exportedOnly: Schema.optional(Schema.Boolean),
|
|
16
17
|
jobs: Schema.Int,
|
|
17
18
|
timeoutMs: Schema.optional(Schema.Int),
|
|
18
19
|
timeoutMultiplier: Schema.Finite,
|
|
@@ -39,6 +40,7 @@ var ProgramLoadError = class extends Schema2.TaggedError()("ProgramLoadError", {
|
|
|
39
40
|
};
|
|
40
41
|
var BaselineFailed = class extends Schema2.TaggedError()("BaselineFailed", {
|
|
41
42
|
exitCode: Schema2.Int,
|
|
43
|
+
command: Schema2.Array(Schema2.String),
|
|
42
44
|
output: Schema2.String
|
|
43
45
|
}) {
|
|
44
46
|
};
|
|
@@ -79,6 +81,7 @@ var Genre = Schema3.Literals([
|
|
|
79
81
|
"StreamOne",
|
|
80
82
|
"StreamFail",
|
|
81
83
|
"LayerFail",
|
|
84
|
+
"LayerDie",
|
|
82
85
|
"SchemaAcceptAnything",
|
|
83
86
|
"BooleanFlip",
|
|
84
87
|
"LiteralCycle",
|
|
@@ -105,7 +108,7 @@ var Mutant = Schema3.Struct({
|
|
|
105
108
|
replacement: Replacement,
|
|
106
109
|
synthetic: Schema3.Boolean
|
|
107
110
|
});
|
|
108
|
-
var Outcome = Schema3.Literals(["caught", "missed", "unviable", "timeout", "untested"]);
|
|
111
|
+
var Outcome = Schema3.Literals(["caught", "missed", "unviable", "timeout", "untested", "unreliable"]);
|
|
109
112
|
var MutantResult = Schema3.Struct({
|
|
110
113
|
mutant: Mutant,
|
|
111
114
|
outcome: Outcome,
|
|
@@ -114,17 +117,45 @@ var MutantResult = Schema3.Struct({
|
|
|
114
117
|
diagnostics: Schema3.Array(Schema3.String),
|
|
115
118
|
output: Schema3.optional(Schema3.String)
|
|
116
119
|
});
|
|
120
|
+
var SelectionIssue = Schema3.Union([
|
|
121
|
+
Schema3.Struct({ kind: Schema3.Literal("runner"), reason: Schema3.String }),
|
|
122
|
+
Schema3.Struct({ kind: Schema3.Literal("warning"), reason: Schema3.String }),
|
|
123
|
+
Schema3.Struct({ kind: Schema3.Literal("target"), file: Schema3.String, reason: Schema3.String }),
|
|
124
|
+
Schema3.Struct({ kind: Schema3.Literal("built"), files: Schema3.optional(Schema3.Array(Schema3.String)), testFiles: Schema3.Array(Schema3.String), reason: Schema3.String })
|
|
125
|
+
]);
|
|
117
126
|
var Baseline = Schema3.Struct({
|
|
118
127
|
durationMs: Schema3.Int,
|
|
119
|
-
testCommand: Schema3.Array(Schema3.String)
|
|
128
|
+
testCommand: Schema3.Array(Schema3.String),
|
|
129
|
+
unreliable: Schema3.optional(Schema3.Array(SelectionIssue))
|
|
130
|
+
});
|
|
131
|
+
var NotMutated = Schema3.Struct({
|
|
132
|
+
file: Schema3.String,
|
|
133
|
+
functionName: Schema3.String,
|
|
134
|
+
reason: Schema3.String
|
|
135
|
+
});
|
|
136
|
+
var SelectionCounts = Schema3.Struct({
|
|
137
|
+
selected: Schema3.Int,
|
|
138
|
+
run: Schema3.Int,
|
|
139
|
+
budgetSkipped: Schema3.Int
|
|
140
|
+
});
|
|
141
|
+
var MutantList = Schema3.Struct({
|
|
142
|
+
schemaVersion: Schema3.Literal(2),
|
|
143
|
+
tool: Schema3.Literal("mutant.cafe"),
|
|
144
|
+
mutants: Schema3.Array(Mutant),
|
|
145
|
+
notMutated: Schema3.Array(NotMutated),
|
|
146
|
+
counts: SelectionCounts
|
|
120
147
|
});
|
|
121
148
|
var RunReport = Schema3.Struct({
|
|
122
|
-
|
|
149
|
+
selected: Schema3.optional(Schema3.Int),
|
|
150
|
+
run: Schema3.optional(Schema3.Int),
|
|
151
|
+
budgetSkipped: Schema3.optional(Schema3.Int),
|
|
152
|
+
schemaVersion: Schema3.Literal(2),
|
|
123
153
|
tool: Schema3.Literal("mutant.cafe"),
|
|
124
154
|
root: Schema3.String,
|
|
125
155
|
baseline: Baseline,
|
|
126
156
|
timeoutMs: Schema3.Int,
|
|
127
|
-
results: Schema3.Array(MutantResult)
|
|
157
|
+
results: Schema3.Array(MutantResult),
|
|
158
|
+
failure: Schema3.optional(Schema3.String)
|
|
128
159
|
});
|
|
129
160
|
|
|
130
161
|
// packages/core/src/Services.ts
|
|
@@ -146,33 +177,33 @@ import * as Schema4 from "effect/Schema";
|
|
|
146
177
|
|
|
147
178
|
// packages/engine/src/Generate.ts
|
|
148
179
|
import { createHash } from "node:crypto";
|
|
149
|
-
function* generateFunction(
|
|
150
|
-
const api =
|
|
180
|
+
function* generateFunction(fn9) {
|
|
181
|
+
const api = fn9.api;
|
|
151
182
|
const candidate = (genre, expression, value = { text: "", synthetic: false }, description = expression) => {
|
|
152
|
-
const pinned = `((): ${
|
|
153
|
-
const text =
|
|
154
|
-
return makeMutant(
|
|
183
|
+
const pinned = `((): ${fn9.returnType} => (${expression}))()`;
|
|
184
|
+
const text = fn9.block ? `{ return ${fn9.generator ? "yield* " : ""}${pinned}; }` : `(${pinned})`;
|
|
185
|
+
return makeMutant(fn9, genre, text, value.synthetic, description);
|
|
155
186
|
};
|
|
156
|
-
const shape =
|
|
187
|
+
const shape = fn9.shape;
|
|
157
188
|
switch (shape.kind) {
|
|
158
189
|
case "Effect": {
|
|
159
|
-
const
|
|
160
|
-
if (
|
|
190
|
+
const succeed4 = api("Effect", "succeed");
|
|
191
|
+
if (succeed4) {
|
|
161
192
|
for (const value of shape.values) {
|
|
162
|
-
if (!
|
|
193
|
+
if (!fn9.equivalentValues.includes(value.text)) yield candidate("EffectSucceed", `${succeed4}(${value.text})`, value);
|
|
163
194
|
}
|
|
164
195
|
}
|
|
165
|
-
const
|
|
166
|
-
const
|
|
167
|
-
for (const
|
|
168
|
-
if (
|
|
196
|
+
const fail3 = api("Effect", "fail");
|
|
197
|
+
const catchTag3 = api("Effect", "catchTag");
|
|
198
|
+
for (const error3 of shape.errors) {
|
|
199
|
+
if (fail3) yield candidate("EffectFail", `${fail3}(${error3.text})`, error3, `${fail3}(${error3.text}) [${error3.synthetic ? "synthetic tag cast" : "constructed error"}]`);
|
|
169
200
|
const value = shape.values[0];
|
|
170
201
|
const die3 = api("Effect", "die");
|
|
171
|
-
const recovery = value &&
|
|
172
|
-
if (
|
|
173
|
-
const
|
|
174
|
-
const original =
|
|
175
|
-
if (original) yield candidate(value ? "SwallowTag" : "TagToDefect", `${original}.pipe(${
|
|
202
|
+
const recovery = value && succeed4 ? `${succeed4}(${value.text})` : die3 ? `${die3}(${JSON.stringify(`mutant.cafe: swallowed ${error3.tag}`)})` : void 0;
|
|
203
|
+
if (catchTag3 && recovery) {
|
|
204
|
+
const gen9 = api("Effect", "gen");
|
|
205
|
+
const original = fn9.generator ? gen9 && `((): ${fn9.returnType} => ${gen9}(function* () ${fn9.original}))()` : fn9.block ? `((): ${fn9.returnType} => ${fn9.original})()` : `((): ${fn9.returnType} => (${fn9.original}))()`;
|
|
206
|
+
if (original) 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`);
|
|
176
207
|
}
|
|
177
208
|
}
|
|
178
209
|
const die2 = api("Effect", "die");
|
|
@@ -190,45 +221,50 @@ function* generateFunction(fn7) {
|
|
|
190
221
|
}
|
|
191
222
|
case "Stream": {
|
|
192
223
|
const empty = api("Stream", "empty");
|
|
193
|
-
const
|
|
194
|
-
const
|
|
224
|
+
const make9 = api("Stream", "make");
|
|
225
|
+
const fail3 = api("Stream", "fail");
|
|
195
226
|
if (empty) yield candidate("StreamEmpty", empty);
|
|
196
|
-
if (
|
|
197
|
-
if (
|
|
227
|
+
if (make9) for (const value of shape.values) yield candidate("StreamOne", `${make9}(${value.text})`, value);
|
|
228
|
+
if (fail3) for (const error3 of shape.errors) yield candidate("StreamFail", `${fail3}(${error3.text})`, error3);
|
|
198
229
|
break;
|
|
199
230
|
}
|
|
200
231
|
case "Layer": {
|
|
201
232
|
const layer2 = api("Layer", "effectContext");
|
|
202
|
-
const
|
|
203
|
-
|
|
204
|
-
|
|
233
|
+
const fail3 = api("Effect", "fail");
|
|
234
|
+
const die2 = api("Effect", "die");
|
|
235
|
+
if (layer2 && die2) yield candidate("LayerDie", `${layer2}(${die2}("mutant.cafe"))`);
|
|
236
|
+
if (layer2 && fail3) {
|
|
237
|
+
for (const error3 of shape.errors) yield candidate("LayerFail", `${layer2}(${fail3}(${error3.text}))`, error3);
|
|
205
238
|
}
|
|
206
239
|
break;
|
|
207
240
|
}
|
|
208
241
|
case "Void":
|
|
209
|
-
yield makeMutant(
|
|
242
|
+
yield makeMutant(fn9, "FnValue", "{}", false, "an empty body");
|
|
210
243
|
break;
|
|
211
244
|
default: {
|
|
212
245
|
const genre = shape.kind === "Boolean" ? "BooleanFlip" : shape.kind === "Literal" ? "LiteralCycle" : "FnValue";
|
|
213
246
|
for (const value of shape.values) {
|
|
214
|
-
if (shape.kind === "Literal" && value.text ===
|
|
247
|
+
if (shape.kind === "Literal" && value.text === fn9.literal) continue;
|
|
215
248
|
yield candidate(genre, value.text, value);
|
|
216
249
|
}
|
|
217
250
|
}
|
|
218
251
|
}
|
|
219
252
|
}
|
|
220
|
-
function makeMutant(
|
|
221
|
-
const
|
|
222
|
-
const
|
|
253
|
+
function makeMutant(fn9, genre, text, synthetic, description) {
|
|
254
|
+
const additions = fn9.extraImports?.filter((item) => text.includes(`${item.namespace}.`)) ?? [];
|
|
255
|
+
const prefix = fn9.sourcePrefix ?? "";
|
|
256
|
+
const insertion = fn9.importInsertionOffset ?? 0;
|
|
257
|
+
const replacement = additions.length && fn9.sourcePrefix !== void 0 ? { startOffset: 0, endOffset: fn9.endOffset, text: prefix.slice(0, insertion) + (insertion ? "\n" : "") + additions.map((item) => item.statement).join("\n") + "\n" + prefix.slice(insertion) + text } : { startOffset: fn9.startOffset, endOffset: fn9.endOffset, text };
|
|
258
|
+
const id = createHash("sha256").update(JSON.stringify([fn9.identityFile ?? fn9.file, fn9.name, fn9.identityOrdinal ?? 0, fn9.logicalSpan, genre, text, additions.map((item) => item.statement)])).digest("hex").slice(0, 24);
|
|
223
259
|
return {
|
|
224
260
|
id,
|
|
225
|
-
file:
|
|
226
|
-
functionName:
|
|
227
|
-
returnType:
|
|
228
|
-
displayReturnType:
|
|
261
|
+
file: fn9.file,
|
|
262
|
+
functionName: fn9.name,
|
|
263
|
+
returnType: fn9.returnType,
|
|
264
|
+
displayReturnType: fn9.displayReturnType,
|
|
229
265
|
genre,
|
|
230
|
-
description: `replace ${
|
|
231
|
-
span:
|
|
266
|
+
description: `replace ${fn9.name} -> ${fn9.returnType} with ${description}`,
|
|
267
|
+
span: fn9.span,
|
|
232
268
|
replacement,
|
|
233
269
|
synthetic
|
|
234
270
|
};
|
|
@@ -294,7 +330,9 @@ function makeTypeScriptOracle() {
|
|
|
294
330
|
const sessions = /* @__PURE__ */ new Map();
|
|
295
331
|
const owners = /* @__PURE__ */ new Map();
|
|
296
332
|
return {
|
|
297
|
-
|
|
333
|
+
discover(config) {
|
|
334
|
+
const notMutated = [];
|
|
335
|
+
const functions = [];
|
|
298
336
|
const configPath = resolve(config.root, config.tsconfig);
|
|
299
337
|
let session = sessions.get(configPath);
|
|
300
338
|
if (!session) {
|
|
@@ -314,9 +352,14 @@ function makeTypeScriptOracle() {
|
|
|
314
352
|
owners.set(file, session);
|
|
315
353
|
const api = imports(source);
|
|
316
354
|
const visit = (node) => {
|
|
317
|
-
if (isFunction(node) && node.body && mutable(node, checker)
|
|
318
|
-
|
|
319
|
-
|
|
355
|
+
if (isFunction(node) && node.body && !mutable(node, checker)) {
|
|
356
|
+
notMutated.push({ file, functionName: functionName(node, checker), reason: "unsupported function position: callback, array element or curried implementation" });
|
|
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)))) {
|
|
320
363
|
const signature = checker.getSignatureFromDeclaration(node);
|
|
321
364
|
if (signature) {
|
|
322
365
|
const wrapped = wrappedEffect(node, checker);
|
|
@@ -327,33 +370,80 @@ function makeTypeScriptOracle() {
|
|
|
327
370
|
const end = body.getEnd();
|
|
328
371
|
const a = source.getLineAndCharacterOfPosition(start);
|
|
329
372
|
const b = source.getLineAndCharacterOfPosition(end);
|
|
330
|
-
const
|
|
373
|
+
const beforePipeables = wrapped && ts.isFunctionExpression(node) ? generatorContract(node, checker) : void 0;
|
|
374
|
+
const shape = beforePipeables?.shape ?? shapeOf(type, checker, node, body);
|
|
331
375
|
const originals = equivalentSuccessValues(body, api);
|
|
332
|
-
|
|
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({
|
|
333
379
|
file,
|
|
334
380
|
name,
|
|
335
|
-
returnType: returnTypeText(type, checker, node),
|
|
381
|
+
returnType: beforePipeables?.text ?? returnTypeText(type, checker, node),
|
|
336
382
|
displayReturnType: node.type?.getText(source) ?? checker.typeToString(type, node),
|
|
383
|
+
skipReason: beforePipeables ? `no synthesizable generator success value: ${beforePipeables.text}` : synthesisReason(type, checker, node),
|
|
337
384
|
equivalentValues: shape.kind === "Effect" ? shape.values.filter((value) => isEquivalentSuccess(value.text, originals)).map((value) => value.text) : [],
|
|
338
385
|
span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
|
|
339
386
|
startOffset: start,
|
|
340
387
|
endOffset: end,
|
|
341
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),
|
|
342
394
|
literal: literalOfBody(body, checker),
|
|
343
395
|
block: ts.isBlock(body),
|
|
344
396
|
generator: generator !== void 0,
|
|
345
397
|
shape,
|
|
346
398
|
api
|
|
347
399
|
});
|
|
400
|
+
} else notMutated.push({ file, functionName: name, reason: "missing callable signature" });
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if ((ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node)) && node.initializer) {
|
|
404
|
+
const type = checker.getTypeAtLocation(node.initializer);
|
|
405
|
+
if (family(type, checker)?.kind === "Layer") {
|
|
406
|
+
const name = valuePath(node);
|
|
407
|
+
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;
|
|
408
|
+
if (reason) notMutated.push({ file, functionName: name, reason });
|
|
409
|
+
else if (!config.functionFilter.length || config.functionFilter.some((filter) => matchesGlob(name, filter))) {
|
|
410
|
+
const body = node.initializer;
|
|
411
|
+
const a = source.getLineAndCharacterOfPosition(body.getStart(source));
|
|
412
|
+
const b = source.getLineAndCharacterOfPosition(body.getEnd());
|
|
413
|
+
found.push({
|
|
414
|
+
file,
|
|
415
|
+
name,
|
|
416
|
+
returnType: returnTypeText(type, checker, node),
|
|
417
|
+
displayReturnType: checker.typeToString(type, node),
|
|
418
|
+
equivalentValues: [],
|
|
419
|
+
span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
|
|
420
|
+
startOffset: body.getStart(source),
|
|
421
|
+
endOffset: body.getEnd(),
|
|
422
|
+
original: body.getText(source),
|
|
423
|
+
literal: void 0,
|
|
424
|
+
identityFile: local,
|
|
425
|
+
logicalSpan: { offset: body.getStart(source) - node.getStart(source), length: body.getWidth(source) },
|
|
426
|
+
sourcePrefix: source.text.slice(0, body.getStart(source)),
|
|
427
|
+
importInsertionOffset: importInsertionOffset(source),
|
|
428
|
+
extraImports: mutationImports(source),
|
|
429
|
+
block: false,
|
|
430
|
+
generator: false,
|
|
431
|
+
shape: shapeOf(type, checker, node, body),
|
|
432
|
+
api
|
|
433
|
+
});
|
|
348
434
|
}
|
|
349
435
|
}
|
|
350
|
-
return;
|
|
351
436
|
}
|
|
352
437
|
ts.forEachChild(node, visit);
|
|
353
438
|
};
|
|
354
439
|
const found = [];
|
|
355
440
|
visit(source);
|
|
356
|
-
|
|
441
|
+
const occurrences = /* @__PURE__ */ new Map();
|
|
442
|
+
for (const fn9 of found) {
|
|
443
|
+
const ordinal = occurrences.get(fn9.name) ?? 0;
|
|
444
|
+
occurrences.set(fn9.name, ordinal + 1);
|
|
445
|
+
functions.push({ ...fn9, identityOrdinal: ordinal });
|
|
446
|
+
}
|
|
357
447
|
}
|
|
358
448
|
const unmatched = config.include.filter((glob) => !matched.has(glob));
|
|
359
449
|
if (unmatched.length) throw new ProgramLoadError({ tsconfig: configPath, reason: "selection", diagnostics: unmatched.map((glob) => {
|
|
@@ -361,6 +451,7 @@ function makeTypeScriptOracle() {
|
|
|
361
451
|
const outside = target === ".." || target.startsWith("../");
|
|
362
452
|
return `No source file matched ${JSON.stringify(glob)}${outside ? " (path is outside the package root)" : ""}`;
|
|
363
453
|
}) });
|
|
454
|
+
return { functions, notMutated };
|
|
364
455
|
},
|
|
365
456
|
checkViable(mutant) {
|
|
366
457
|
const session = owners.get(resolve(mutant.file));
|
|
@@ -372,21 +463,120 @@ function makeTypeScriptOracle() {
|
|
|
372
463
|
function isFunction(node) {
|
|
373
464
|
return ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node);
|
|
374
465
|
}
|
|
375
|
-
function
|
|
376
|
-
|
|
466
|
+
function functionValue(node, checker) {
|
|
467
|
+
const wrapper = wrappedEffect(node, checker);
|
|
468
|
+
return wrapper && checker.getTypeAtLocation(node.parent).getCallSignatures().length ? node.parent : node;
|
|
469
|
+
}
|
|
470
|
+
function returnedBy(node, checker) {
|
|
471
|
+
let value = functionValue(node, checker);
|
|
472
|
+
while (ts.isParenthesizedExpression(value.parent)) value = value.parent;
|
|
473
|
+
const parent = value.parent;
|
|
474
|
+
if (ts.isArrowFunction(parent) && parent.body === value) return parent;
|
|
475
|
+
if (ts.isReturnStatement(parent) && parent.expression === value && ts.isBlock(parent.parent) && isFunction(parent.parent.parent)) return parent.parent.parent;
|
|
476
|
+
return void 0;
|
|
377
477
|
}
|
|
378
478
|
function mutable(node, checker) {
|
|
379
|
-
if (ts.isMethodDeclaration(node)) return true;
|
|
380
|
-
|
|
381
|
-
const wrapper = wrappedEffect(node, checker);
|
|
382
|
-
let current = node;
|
|
383
|
-
if (wrapper) current = node.parent;
|
|
479
|
+
if (ts.isMethodDeclaration(node) || ts.isFunctionDeclaration(node)) return true;
|
|
480
|
+
let current = wrappedEffect(node, checker) ? node.parent : node;
|
|
384
481
|
while (ts.isParenthesizedExpression(current.parent)) current = current.parent;
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
482
|
+
return returnedBy(node, checker) !== void 0 || (ts.isVariableDeclaration(current.parent) || ts.isPropertyAssignment(current.parent) || ts.isPropertyDeclaration(current.parent)) && current.parent.initializer === current;
|
|
483
|
+
}
|
|
484
|
+
function layerBody(boundary, checker) {
|
|
485
|
+
let enclosing = boundary.parent;
|
|
486
|
+
while (!ts.isSourceFile(enclosing) && !isFunction(enclosing)) {
|
|
487
|
+
if (ts.isCallExpression(enclosing) && family(checker.getTypeAtLocation(enclosing), checker)?.kind === "Layer") return true;
|
|
488
|
+
enclosing = enclosing.parent;
|
|
489
|
+
}
|
|
490
|
+
return false;
|
|
491
|
+
}
|
|
492
|
+
function returnsLayer(node, checker) {
|
|
493
|
+
const signature = checker.getSignatureFromDeclaration(node);
|
|
494
|
+
if (!signature) return false;
|
|
495
|
+
const type = checker.getReturnTypeOfSignature(signature);
|
|
496
|
+
return (type.isUnion() ? type.types : [type]).every((member) => family(member, checker)?.kind === "Layer");
|
|
497
|
+
}
|
|
498
|
+
function serviceProperty(node, boundary, checker) {
|
|
499
|
+
if (!(ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) || !ts.isObjectLiteralExpression(node.parent)) return false;
|
|
500
|
+
const object = node.parent;
|
|
501
|
+
const call = object.parent;
|
|
502
|
+
return ts.isCallExpression(call) && call.arguments[0] === object && ts.isPropertyAccessExpression(call.expression) && call.expression.name.text === "of" && ts.isReturnStatement(call.parent) && call.parent.parent === boundary.body && layerBody(boundary, checker);
|
|
503
|
+
}
|
|
504
|
+
function serviceMethod(node, boundary, checker) {
|
|
505
|
+
if (!layerBody(boundary, checker) || !boundary.body) return false;
|
|
506
|
+
const declaration = ts.findAncestor(node, ts.isVariableDeclaration);
|
|
507
|
+
let returned = false;
|
|
508
|
+
const visit = (child) => {
|
|
509
|
+
if (isFunction(child)) return;
|
|
510
|
+
if (ts.isReturnStatement(child) && child.expression && ts.isCallExpression(child.expression)) {
|
|
511
|
+
const call = child.expression;
|
|
512
|
+
const object = call.arguments[0];
|
|
513
|
+
if (ts.isPropertyAccessExpression(call.expression) && call.expression.name.text === "of" && object && ts.isObjectLiteralExpression(object)) {
|
|
514
|
+
returned ||= object.properties.some((prop) => {
|
|
515
|
+
if (ts.isPropertyAssignment(prop) && (prop.initializer === functionValue(node, checker) || declaration && ts.isIdentifier(prop.initializer) && checker.getSymbolAtLocation(prop.initializer)?.valueDeclaration === declaration)) return true;
|
|
516
|
+
if (ts.isShorthandPropertyAssignment(prop)) return checker.getShorthandAssignmentValueSymbol(prop)?.valueDeclaration === declaration;
|
|
517
|
+
return false;
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
ts.forEachChild(child, visit);
|
|
522
|
+
};
|
|
523
|
+
visit(boundary.body);
|
|
524
|
+
return returned;
|
|
525
|
+
}
|
|
526
|
+
function exportedBinding(binding, checker) {
|
|
527
|
+
let declaration = binding;
|
|
528
|
+
let symbol = binding.name ? checker.getSymbolAtLocation(binding.name) : void 0;
|
|
529
|
+
let container = ts.findAncestor(binding, (node) => ts.isSourceFile(node) || ts.isModuleBlock(node));
|
|
530
|
+
while (container) {
|
|
531
|
+
const module = ts.isSourceFile(container) ? checker.getSymbolAtLocation(container) : ts.isModuleBlock(container) && ts.isModuleDeclaration(container.parent) ? checker.getSymbolAtLocation(container.parent.name) : void 0;
|
|
532
|
+
if (!module || !checker.getExportsOfModule(module).some((item) => {
|
|
533
|
+
const target = item.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(item) : item;
|
|
534
|
+
return target === symbol || target.valueDeclaration === declaration;
|
|
535
|
+
})) return false;
|
|
536
|
+
if (ts.isSourceFile(container)) return true;
|
|
537
|
+
if (!ts.isModuleBlock(container) || !ts.isModuleDeclaration(container.parent)) return false;
|
|
538
|
+
declaration = container.parent;
|
|
539
|
+
symbol = module;
|
|
540
|
+
container = ts.findAncestor(container.parent, (node) => ts.isSourceFile(node) || ts.isModuleBlock(node));
|
|
541
|
+
}
|
|
542
|
+
return false;
|
|
543
|
+
}
|
|
544
|
+
function publicOwner(node, checker, seen = /* @__PURE__ */ new Set()) {
|
|
545
|
+
if (seen.has(node)) return false;
|
|
546
|
+
seen.add(node);
|
|
547
|
+
let current = node;
|
|
548
|
+
let binding;
|
|
549
|
+
let value = isFunction(node) ? node : void 0;
|
|
550
|
+
let throughService = false;
|
|
551
|
+
while (!ts.isSourceFile(current)) {
|
|
552
|
+
if (current !== node && isFunction(current)) {
|
|
553
|
+
const method = value ? serviceMethod(value, current, checker) : serviceProperty(node, current, checker);
|
|
554
|
+
if (!(value && returnedBy(value, checker) === current) && !method && !(throughService && returnsLayer(current, checker))) return false;
|
|
555
|
+
throughService ||= method;
|
|
556
|
+
value = current;
|
|
557
|
+
}
|
|
558
|
+
if (ts.isVariableDeclaration(current) || ts.isFunctionDeclaration(current) || ts.isClassDeclaration(current)) binding = current;
|
|
559
|
+
current = current.parent;
|
|
560
|
+
}
|
|
561
|
+
if (!binding) return false;
|
|
562
|
+
if (exportedBinding(binding, checker)) return true;
|
|
563
|
+
let exposed = false;
|
|
564
|
+
const declaration = binding;
|
|
565
|
+
const visit = (child) => {
|
|
566
|
+
if (exposed) return;
|
|
567
|
+
const referenced = ts.isShorthandPropertyAssignment(child) ? checker.getShorthandAssignmentValueSymbol(child) : ts.isPropertyAssignment(child) && ts.isIdentifier(child.initializer) ? checker.getSymbolAtLocation(child.initializer) : ts.isExportAssignment(child) && ts.isIdentifier(child.expression) ? checker.getSymbolAtLocation(child.expression) : void 0;
|
|
568
|
+
if (referenced?.valueDeclaration === declaration) {
|
|
569
|
+
exposed = ts.isExportAssignment(child) || publicOwner(child, checker, seen);
|
|
570
|
+
}
|
|
571
|
+
ts.forEachChild(child, visit);
|
|
572
|
+
};
|
|
573
|
+
visit(current);
|
|
574
|
+
return exposed;
|
|
388
575
|
}
|
|
389
576
|
function skipped(node) {
|
|
577
|
+
return skippedNode(node);
|
|
578
|
+
}
|
|
579
|
+
function skippedNode(node) {
|
|
390
580
|
let current = node;
|
|
391
581
|
while (!ts.isSourceFile(current)) {
|
|
392
582
|
if (ts.getJSDocTags(current).some((tag) => tag.tagName.text === "mutants-skip")) return true;
|
|
@@ -394,24 +584,23 @@ function skipped(node) {
|
|
|
394
584
|
}
|
|
395
585
|
return false;
|
|
396
586
|
}
|
|
397
|
-
function
|
|
398
|
-
|
|
399
|
-
let enclosing = node.parent;
|
|
400
|
-
while (!ts.isSourceFile(enclosing)) {
|
|
401
|
-
if (ts.isVariableDeclaration(enclosing)) return enclosing.name.getText();
|
|
402
|
-
enclosing = enclosing.parent;
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
if (node.name) {
|
|
406
|
-
if (ts.isMethodDeclaration(node) && ts.isClassLike(node.parent) && node.parent.name) return `${node.parent.name.text}.${node.name.getText()}`;
|
|
407
|
-
return node.name.getText();
|
|
408
|
-
}
|
|
587
|
+
function valuePath(node) {
|
|
588
|
+
const parts = [];
|
|
409
589
|
let current = node;
|
|
410
590
|
while (!ts.isSourceFile(current)) {
|
|
411
|
-
if (ts.isVariableDeclaration(current))
|
|
591
|
+
if ((ts.isVariableDeclaration(current) || ts.isPropertyAssignment(current) || ts.isPropertyDeclaration(current) || ts.isMethodDeclaration(current) || ts.isFunctionDeclaration(current) || ts.isClassDeclaration(current) || ts.isModuleDeclaration(current)) && current.name) parts.unshift(current.name.getText());
|
|
412
592
|
current = current.parent;
|
|
413
593
|
}
|
|
414
|
-
return "default";
|
|
594
|
+
return parts.join(".") || "default";
|
|
595
|
+
}
|
|
596
|
+
function functionName(node, checker) {
|
|
597
|
+
let path = valuePath(node);
|
|
598
|
+
let parent = returnedBy(node, checker);
|
|
599
|
+
while (parent) {
|
|
600
|
+
path += ".<inner>";
|
|
601
|
+
parent = returnedBy(parent, checker);
|
|
602
|
+
}
|
|
603
|
+
return path;
|
|
415
604
|
}
|
|
416
605
|
function wrappedEffect(node, checker) {
|
|
417
606
|
if (!ts.isFunctionExpression(node) || !node.asteriskToken || !ts.isCallExpression(node.parent)) return void 0;
|
|
@@ -422,6 +611,39 @@ function wrappedEffect(node, checker) {
|
|
|
422
611
|
const returned = checker.getReturnTypeOfSignature(signature);
|
|
423
612
|
return family(returned, checker)?.kind === "Effect" ? returned : void 0;
|
|
424
613
|
}
|
|
614
|
+
function nameableContract(contract, checker, node) {
|
|
615
|
+
return contract.types.every((type) => !hasUnnameableType(type, checker, node));
|
|
616
|
+
}
|
|
617
|
+
function hasUnnameableType(type, checker, location) {
|
|
618
|
+
const printed = checker.typeToTypeNode(type, location, ts.NodeBuilderFlags.NoTruncation);
|
|
619
|
+
if (!printed) return true;
|
|
620
|
+
let missing = false;
|
|
621
|
+
const visit = (node) => {
|
|
622
|
+
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !checker.resolveName(node.typeName.text, location, ts.SymbolFlags.Type, false)) missing = true;
|
|
623
|
+
ts.forEachChild(node, visit);
|
|
624
|
+
};
|
|
625
|
+
visit(printed);
|
|
626
|
+
return missing;
|
|
627
|
+
}
|
|
628
|
+
function generatorContract(node, checker) {
|
|
629
|
+
const signature = checker.getSignatureFromDeclaration(node);
|
|
630
|
+
if (!signature || !node.body) return void 0;
|
|
631
|
+
const iterator = checker.getReturnTypeOfSignature(signature);
|
|
632
|
+
const args = checker.getTypeArguments(iterator);
|
|
633
|
+
const [yielded, success] = args;
|
|
634
|
+
if (!yielded || !success) return void 0;
|
|
635
|
+
const effects = (yielded.isUnion() ? yielded.types : [yielded]).flatMap((t) => {
|
|
636
|
+
const f = family(t, checker);
|
|
637
|
+
return f?.kind === "Effect" ? [f] : [];
|
|
638
|
+
});
|
|
639
|
+
const print = (t) => returnTypeText(t, checker, node);
|
|
640
|
+
const union = (index) => [...new Set(effects.flatMap((f) => f.args[index] ? [print(f.args[index])] : []))].join(" | ") || "never";
|
|
641
|
+
return {
|
|
642
|
+
types: [success, ...effects.flatMap((effect5) => effect5.args.slice(1))],
|
|
643
|
+
text: `import("effect/Effect").Effect<${print(success)}, ${union(1)}, ${union(2)}>`,
|
|
644
|
+
shape: { kind: "Effect", values: valuesOf(success, checker, node), errors: [...new Map(effects.flatMap((f) => f.args[1] ? taggedValues(f.args[1], checker, node) : []).map((e) => [e.tag, e])).values()] }
|
|
645
|
+
};
|
|
646
|
+
}
|
|
425
647
|
function literalOfBody(body, checker) {
|
|
426
648
|
const first = ts.isBlock(body) && body.statements.length === 1 ? body.statements[0] : void 0;
|
|
427
649
|
const expression = ts.isBlock(body) ? first && ts.isReturnStatement(first) ? first.expression : void 0 : body;
|
|
@@ -460,9 +682,28 @@ function imports(source) {
|
|
|
460
682
|
}
|
|
461
683
|
return (module, member) => {
|
|
462
684
|
const namespace = namespaces.get(module);
|
|
463
|
-
return namespace ? `${namespace}.${member}` : named.get(`${module}.${member}`)
|
|
685
|
+
return namespace ? `${namespace}.${member}` : named.get(`${module}.${member}`) ?? `${mutationNamespace(source, module)}.${member}`;
|
|
464
686
|
};
|
|
465
687
|
}
|
|
688
|
+
function importInsertionOffset(source) {
|
|
689
|
+
let offset = source.text.startsWith("#!") ? source.text.indexOf("\n") + 1 || source.text.length : 0;
|
|
690
|
+
for (const statement of source.statements) {
|
|
691
|
+
if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) break;
|
|
692
|
+
offset = statement.getEnd();
|
|
693
|
+
}
|
|
694
|
+
return offset;
|
|
695
|
+
}
|
|
696
|
+
function mutationNamespace(source, module) {
|
|
697
|
+
let name = `__mutantCafe${module}`;
|
|
698
|
+
while (source.text.includes(name)) name += "_";
|
|
699
|
+
return name;
|
|
700
|
+
}
|
|
701
|
+
function mutationImports(source) {
|
|
702
|
+
return ["Effect", "Option", "Stream", "Layer"].map((module) => {
|
|
703
|
+
const namespace = mutationNamespace(source, module);
|
|
704
|
+
return { namespace, statement: `import * as ${namespace} from "effect/${module}";` };
|
|
705
|
+
});
|
|
706
|
+
}
|
|
466
707
|
function family(type, checker) {
|
|
467
708
|
const symbol = type.aliasSymbol ?? type.getSymbol();
|
|
468
709
|
const name = symbol?.getName();
|
|
@@ -500,40 +741,34 @@ function family(type, checker) {
|
|
|
500
741
|
function shapeOf(type, checker, node, body) {
|
|
501
742
|
if (type.isUnion() && type.types.every((member) => family(member, checker)?.kind === "Effect")) {
|
|
502
743
|
const shapes = type.types.map((member) => shapeOf(member, checker, node, body));
|
|
503
|
-
const
|
|
744
|
+
const values2 = shapes.flatMap((shape) => shape.kind === "Effect" ? shape.values : []);
|
|
504
745
|
const errors = shapes.flatMap((shape) => shape.kind === "Effect" ? shape.errors : []);
|
|
505
746
|
return {
|
|
506
747
|
kind: "Effect",
|
|
507
|
-
values: [...new Map(
|
|
508
|
-
errors: [...new Map(errors.map((
|
|
748
|
+
values: [...new Map(values2.map((value) => [value.text, value])).values()].sort((a, b) => a.text.localeCompare(b.text, "en")),
|
|
749
|
+
errors: [...new Map(errors.map((error3) => [error3.tag, error3])).values()].sort((a, b) => a.tag.localeCompare(b.tag, "en"))
|
|
509
750
|
};
|
|
510
751
|
}
|
|
511
752
|
const detected = family(type, checker);
|
|
512
753
|
if (detected) {
|
|
513
754
|
const [a, e] = detected.args;
|
|
514
|
-
const
|
|
515
|
-
if (detected.kind === "Option") return { kind: "Option", values };
|
|
755
|
+
const values2 = a ? valuesOf(a, checker, node) : [];
|
|
756
|
+
if (detected.kind === "Option") return { kind: "Option", values: values2 };
|
|
516
757
|
const errors = e ? taggedValues(e, checker, node) : [];
|
|
517
|
-
if (detected.kind === "Layer") {
|
|
518
|
-
|
|
519
|
-
const find = (child) => {
|
|
520
|
-
if (!service && ts.isCallExpression(child) && child.arguments[0]) {
|
|
521
|
-
const arg = child.arguments[0];
|
|
522
|
-
const argType = checker.getTypeAtLocation(arg);
|
|
523
|
-
if (argType.getProperty("Identifier") && argType.getProperty("Service")) service = arg.getText();
|
|
524
|
-
}
|
|
525
|
-
ts.forEachChild(child, find);
|
|
526
|
-
};
|
|
527
|
-
find(body);
|
|
528
|
-
return { kind: "Layer", errors, service };
|
|
529
|
-
}
|
|
530
|
-
return { kind: detected.kind, values, errors };
|
|
758
|
+
if (detected.kind === "Layer") return { kind: "Layer", errors };
|
|
759
|
+
return { kind: detected.kind, values: values2, errors };
|
|
531
760
|
}
|
|
532
761
|
if (type.flags & ts.TypeFlags.Void) return { kind: "Void", values: [] };
|
|
533
762
|
const members = type.isUnion() ? type.types : [type];
|
|
534
763
|
const boolean = members.every((t) => (t.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral)) !== 0);
|
|
535
764
|
const literal = members.every((t) => t.isLiteral());
|
|
536
|
-
|
|
765
|
+
const values = valuesOf(type, checker, node);
|
|
766
|
+
if (isFunction(node)) for (const parameter of node.parameters) {
|
|
767
|
+
if (ts.isIdentifier(parameter.name) && !parameter.questionToken && !parameter.dotDotDotToken && checker.getTypeAtLocation(parameter) === type) {
|
|
768
|
+
values.push({ text: parameter.name.text, synthetic: false });
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
return { kind: boolean ? "Boolean" : literal ? "Literal" : "Value", values };
|
|
537
772
|
}
|
|
538
773
|
function taggedValues(type, checker, location) {
|
|
539
774
|
return (type.isUnion() ? type.types : [type]).flatMap((member) => {
|
|
@@ -616,6 +851,17 @@ function isEquivalentSuccess(text, values) {
|
|
|
616
851
|
const value = literalData(statement.expression);
|
|
617
852
|
return value !== void 0 && values.includes(JSON.stringify(value));
|
|
618
853
|
}
|
|
854
|
+
function synthesisReason(type, checker, node) {
|
|
855
|
+
if (type.flags & (ts.TypeFlags.TypeParameter | ts.TypeFlags.IndexedAccess)) return "generic return cannot be synthesized";
|
|
856
|
+
const detected = family(type, checker);
|
|
857
|
+
const valueType = detected?.args[0] ?? type;
|
|
858
|
+
for (const field of valueType.getProperties()) {
|
|
859
|
+
if (!(field.flags & ts.SymbolFlags.Optional) && !valuesOf(checker.getTypeOfSymbolAtLocation(field, node), checker, node).length) {
|
|
860
|
+
return `no synthesizable value for field ${field.name}`;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
return `opaque return: ${checker.typeToString(type, node)}`;
|
|
864
|
+
}
|
|
619
865
|
function valuesOf(type, checker, location, depth = 0) {
|
|
620
866
|
if (depth > 4 || type.flags & ts.TypeFlags.Never) return [];
|
|
621
867
|
const value = (text) => ({ text, synthetic: false });
|
|
@@ -631,6 +877,15 @@ function valuesOf(type, checker, location, depth = 0) {
|
|
|
631
877
|
...wrap ? values.map((v) => ({ text: `${wrap}(${v.text})`, synthetic: v.synthetic })) : []
|
|
632
878
|
];
|
|
633
879
|
}
|
|
880
|
+
if (type.isIntersection()) {
|
|
881
|
+
const primitive = type.types.find((member) => member.flags & (ts.TypeFlags.String | ts.TypeFlags.Number));
|
|
882
|
+
const brand = type.types.some((member) => member.getProperties().some((prop) => prop.name.includes("Brand")));
|
|
883
|
+
if (primitive && brand) return valuesOf(primitive, checker, location, depth + 1).map((v) => ({ ...v, text: `(${v.text} as ${returnTypeText(type, checker, location)})` }));
|
|
884
|
+
}
|
|
885
|
+
const symbol = type.getSymbol();
|
|
886
|
+
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
|
+
return [value(symbol.name.endsWith("Set") ? "new Set()" : "new Map()")];
|
|
888
|
+
}
|
|
634
889
|
if (type.isUnion()) return [...type.types].sort((a, b) => a.isNumberLiteral() && b.isNumberLiteral() ? a.value - b.value : checker.typeToString(a).localeCompare(checker.typeToString(b), "en")).flatMap((member) => valuesOf(member, checker, location, depth + 1));
|
|
635
890
|
if (type.isStringLiteral()) return [value(JSON.stringify(type.value))];
|
|
636
891
|
if (type.isNumberLiteral()) return [value(String(type.value))];
|
|
@@ -656,11 +911,21 @@ function valuesOf(type, checker, location, depth = 0) {
|
|
|
656
911
|
for (const prop of type.getProperties()) {
|
|
657
912
|
if (prop.flags & ts.SymbolFlags.Optional) continue;
|
|
658
913
|
if (!/^[$\w]+$/.test(prop.name)) return [];
|
|
659
|
-
const
|
|
660
|
-
if (!
|
|
661
|
-
fields.push(
|
|
914
|
+
const values = valuesOf(checker.getTypeOfSymbolAtLocation(prop, location), checker, location, depth + 1);
|
|
915
|
+
if (!values.length) return [];
|
|
916
|
+
fields.push({ name: prop.name, values });
|
|
662
917
|
}
|
|
663
|
-
|
|
918
|
+
const literalFields = fields.filter((field) => {
|
|
919
|
+
const prop = type.getProperty(field.name);
|
|
920
|
+
const t = checker.getTypeOfSymbolAtLocation(prop, location);
|
|
921
|
+
return (t.isUnion() ? t.types : [t]).every((member) => member.isLiteral() || !!(member.flags & ts.TypeFlags.BooleanLiteral));
|
|
922
|
+
});
|
|
923
|
+
const render = (changed, replacement) => value(`({ ${fields.map((field) => {
|
|
924
|
+
const v = (field === changed ? replacement : field.values[0]).text;
|
|
925
|
+
return `${JSON.stringify(field.name)}: ${literalFields.includes(field) ? `(${v} as const)` : v}`;
|
|
926
|
+
}).join(", ")} })`);
|
|
927
|
+
const anonymous = !type.aliasSymbol && (!type.getSymbol() || ["__type", "__object"].includes(type.getSymbol().name));
|
|
928
|
+
return [render(), ...anonymous ? literalFields.flatMap((field) => field.values.slice(1).map((v) => render(field, v))) : []];
|
|
664
929
|
}
|
|
665
930
|
return [];
|
|
666
931
|
}
|
|
@@ -671,28 +936,33 @@ var MutantSourceLive = Layer.effect(
|
|
|
671
936
|
Effect.sync(() => makeMutantSource(makeTypeScriptOracle()))
|
|
672
937
|
);
|
|
673
938
|
function makeMutantSource(oracle) {
|
|
939
|
+
const discover = (config) => Effect.try({
|
|
940
|
+
try: () => {
|
|
941
|
+
const discovered = oracle.discover(config);
|
|
942
|
+
const notMutated = [...discovered.notMutated];
|
|
943
|
+
const mutants = [];
|
|
944
|
+
for (const fn9 of discovered.functions) {
|
|
945
|
+
const generated = [...generateFunction(fn9)];
|
|
946
|
+
if (!generated.length) notMutated.push({ file: fn9.file, functionName: fn9.name, reason: fn9.skipReason ?? `opaque return or no synthesizable value: ${fn9.displayReturnType}` });
|
|
947
|
+
mutants.push(...generated);
|
|
948
|
+
}
|
|
949
|
+
return { mutants, notMutated };
|
|
950
|
+
},
|
|
951
|
+
catch: (error3) => loadError(config.tsconfig, error3)
|
|
952
|
+
});
|
|
674
953
|
return {
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
*[Symbol.iterator]() {
|
|
678
|
-
for (const fn7 of oracle.discover(config)) yield* generateFunction(fn7);
|
|
679
|
-
}
|
|
680
|
-
}),
|
|
681
|
-
catch: (error2) => loadError(config.tsconfig, error2)
|
|
682
|
-
})).pipe(
|
|
683
|
-
// Iteration is synchronous compiler work; load it inside the typed error boundary.
|
|
684
|
-
Stream.catchDefect((error2) => Stream.fail(loadError(config.tsconfig, error2)))
|
|
685
|
-
),
|
|
954
|
+
notMutated: (config) => discover(config).pipe(Effect.map((result2) => result2.notMutated)),
|
|
955
|
+
generate: (config) => Stream.unwrap(discover(config).pipe(Effect.map((result2) => Stream.fromIterable(result2.mutants)))),
|
|
686
956
|
checkViable: (mutant) => Effect.try({
|
|
687
957
|
try: () => oracle.checkViable(mutant),
|
|
688
|
-
catch: (
|
|
958
|
+
catch: (error3) => loadError("", error3)
|
|
689
959
|
})
|
|
690
960
|
};
|
|
691
961
|
}
|
|
692
|
-
function loadError(tsconfig,
|
|
693
|
-
return Schema4.is(ProgramLoadError)(
|
|
962
|
+
function loadError(tsconfig, error3) {
|
|
963
|
+
return Schema4.is(ProgramLoadError)(error3) ? error3 : new ProgramLoadError({
|
|
694
964
|
tsconfig,
|
|
695
|
-
diagnostics: [
|
|
965
|
+
diagnostics: [error3 instanceof Error ? error3.message : String(error3)]
|
|
696
966
|
});
|
|
697
967
|
}
|
|
698
968
|
|
|
@@ -704,7 +974,7 @@ import * as Path from "effect/Path";
|
|
|
704
974
|
var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
705
975
|
const fs = yield* FileSystem.FileSystem;
|
|
706
976
|
const path = yield* Path.Path;
|
|
707
|
-
const failure = (operation, location,
|
|
977
|
+
const failure = (operation, location, error3) => new ScratchError({ operation, path: location, message: error3.message });
|
|
708
978
|
return Scratch.of({
|
|
709
979
|
acquire: Effect2.fn("Scratch.acquire")(function* (root) {
|
|
710
980
|
const source = path.resolve(root);
|
|
@@ -721,7 +991,7 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
721
991
|
}
|
|
722
992
|
const temp = yield* Effect2.acquireRelease(
|
|
723
993
|
fs.makeTempDirectory({ prefix: "mutant-cafe-" }).pipe(
|
|
724
|
-
Effect2.mapError((
|
|
994
|
+
Effect2.mapError((error3) => failure("create", source, error3))
|
|
725
995
|
),
|
|
726
996
|
(dir2) => fs.remove(dir2, { recursive: true }).pipe(Effect2.orDie)
|
|
727
997
|
);
|
|
@@ -739,7 +1009,23 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
739
1009
|
const src = path.join(from, entry);
|
|
740
1010
|
const dest = path.join(to, entry);
|
|
741
1011
|
if (entry === "node_modules") {
|
|
742
|
-
|
|
1012
|
+
const linkDependencies = (from2, to2) => Effect2.gen(function* () {
|
|
1013
|
+
yield* fs.makeDirectory(to2, { recursive: true });
|
|
1014
|
+
for (const name of yield* fs.readDirectory(from2)) {
|
|
1015
|
+
if ([".vite", ".vite-temp", ".vitest", ".cache"].includes(name)) continue;
|
|
1016
|
+
const dependency = path.join(from2, name);
|
|
1017
|
+
const destination = path.join(to2, name);
|
|
1018
|
+
if (name.startsWith("@")) {
|
|
1019
|
+
yield* linkDependencies(dependency, destination);
|
|
1020
|
+
continue;
|
|
1021
|
+
}
|
|
1022
|
+
const realDependency = yield* fs.realPath(dependency);
|
|
1023
|
+
const rel = path.relative(copyRoot, realDependency);
|
|
1024
|
+
const inside = rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) && !rel.split(path.sep).includes("node_modules");
|
|
1025
|
+
yield* fs.symlink(inside ? path.join(temp, rel) : realDependency, destination);
|
|
1026
|
+
}
|
|
1027
|
+
});
|
|
1028
|
+
yield* linkDependencies(src, dest);
|
|
743
1029
|
} else {
|
|
744
1030
|
yield* copy(src, dest, [...ancestors, real]);
|
|
745
1031
|
}
|
|
@@ -747,10 +1033,10 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
747
1033
|
} else if (info.type === "File") {
|
|
748
1034
|
yield* fs.copyFile(from, to);
|
|
749
1035
|
}
|
|
750
|
-
}).pipe(Effect2.mapError((
|
|
1036
|
+
}).pipe(Effect2.mapError((error3) => failure("copy", from, error3)));
|
|
751
1037
|
yield* copy(copyRoot, temp, []);
|
|
752
1038
|
const packageRoot = yield* fs.realPath(path.join(temp, path.relative(copyRoot, source))).pipe(
|
|
753
|
-
Effect2.mapError((
|
|
1039
|
+
Effect2.mapError((error3) => failure("resolve", source, error3))
|
|
754
1040
|
);
|
|
755
1041
|
const originals = /* @__PURE__ */ new Map();
|
|
756
1042
|
const target = (mutant) => Effect2.gen(function* () {
|
|
@@ -760,7 +1046,7 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
760
1046
|
if (rel === "" || rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel) || rel.split(path.sep).includes("node_modules")) {
|
|
761
1047
|
return yield* Effect2.fail(new ScratchError({ operation: "resolve", path: mutant.file, message: "Mutant file must be inside the copied source tree" }));
|
|
762
1048
|
}
|
|
763
|
-
const real = yield* fs.realPath(location).pipe(Effect2.mapError((
|
|
1049
|
+
const real = yield* fs.realPath(location).pipe(Effect2.mapError((error3) => failure("resolve", location, error3)));
|
|
764
1050
|
const realRelative = path.relative(packageRoot, real);
|
|
765
1051
|
if (realRelative === ".." || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {
|
|
766
1052
|
return yield* Effect2.fail(new ScratchError({ operation: "resolve", path: mutant.file, message: "Mutant file resolves outside the scratch package" }));
|
|
@@ -779,7 +1065,7 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
779
1065
|
return yield* Effect2.fail(new ScratchError({ operation: "apply", path: location, message: "Replacement offsets are outside the file" }));
|
|
780
1066
|
}
|
|
781
1067
|
yield* fs.writeFileString(location, original.slice(0, startOffset) + text + original.slice(endOffset));
|
|
782
|
-
}, (effect5, mutant) => effect5.pipe(Effect2.mapError((
|
|
1068
|
+
}, (effect5, mutant) => effect5.pipe(Effect2.mapError((error3) => failure("apply", mutant.file, error3)))),
|
|
783
1069
|
revert: Effect2.fn("Scratch.revert")(function* (mutant) {
|
|
784
1070
|
const location = yield* target(mutant);
|
|
785
1071
|
const bytes = originals.get(location);
|
|
@@ -787,39 +1073,213 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
787
1073
|
yield* fs.writeFile(location, bytes);
|
|
788
1074
|
originals.delete(location);
|
|
789
1075
|
}
|
|
790
|
-
}, (effect5, mutant) => effect5.pipe(Effect2.mapError((
|
|
1076
|
+
}, (effect5, mutant) => effect5.pipe(Effect2.mapError((error3) => failure("revert", mutant.file, error3))))
|
|
791
1077
|
};
|
|
792
1078
|
return dir;
|
|
793
|
-
}, (effect5, root) => effect5.pipe(Effect2.mapError((
|
|
1079
|
+
}, (effect5, root) => effect5.pipe(Effect2.mapError((error3) => error3._tag === "ScratchError" ? error3 : failure("acquire", root, error3))))
|
|
794
1080
|
});
|
|
795
1081
|
}));
|
|
796
1082
|
|
|
797
1083
|
// packages/runner/src/TestRunner.ts
|
|
798
1084
|
import * as Clock from "effect/Clock";
|
|
1085
|
+
import * as Console from "effect/Console";
|
|
1086
|
+
|
|
1087
|
+
// packages/runner/src/Preflight.ts
|
|
799
1088
|
import * as Effect3 from "effect/Effect";
|
|
1089
|
+
import * as Schema5 from "effect/Schema";
|
|
1090
|
+
import * as ChildProcess from "effect/process/ChildProcess";
|
|
1091
|
+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
|
|
1092
|
+
var Issues = Schema5.Array(SelectionIssue);
|
|
1093
|
+
var probe = String.raw`
|
|
1094
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
1095
|
+
import { resolve, relative, dirname, isAbsolute, sep } from "node:path";
|
|
1096
|
+
import { createRequire } from "node:module";
|
|
1097
|
+
import { fileURLToPath } from "node:url";
|
|
1098
|
+
const root = process.cwd();
|
|
1099
|
+
const issues = [];
|
|
1100
|
+
const pkg = JSON.parse(await readFile("package.json", "utf8").catch(error => { if (error.code === "ENOENT") return "{}"; throw error; }));
|
|
1101
|
+
const script = pkg.scripts?.test;
|
|
1102
|
+
const vitestScript = !script || /(?:^|[\s/])vitest(?=\s|$|[;&|])/.test(script);
|
|
1103
|
+
const delegated = script && /(?:\bturbo\s+(?:run\s+)?test\b|\bpnpm\s+(?:-r|--recursive|--filter\s+\S+)\s+(?:run\s+)?test\b)/.test(script);
|
|
1104
|
+
const otherRunner = script && /(?:^|&&\s*|;\s*)(?:(?:pnpm\s+exec|npx)\s+)?(?:node\s+(?:\S+\s+)*--test(?=\s|$)|(?:jest|mocha|ava|tap)(?=\s|$)|bun\s+test(?=\s|$))/.test(script);
|
|
1105
|
+
if (otherRunner) {
|
|
1106
|
+
issues.push({ kind: "runner", reason: 'package.json scripts.test = ' + JSON.stringify(script) + '; mutant.cafe only runs Vitest' });
|
|
1107
|
+
} else {
|
|
1108
|
+
if (!vitestScript) issues.push({ kind: "warning", reason: 'package.json scripts.test = ' + JSON.stringify(script) + (delegated ? '; delegated test runner: Vitest selection is unverified' : '; unknown test wrapper: Vitest selection is unverified') });
|
|
1109
|
+
let ctx;
|
|
1110
|
+
try {
|
|
1111
|
+
const { createVitest } = await import("vitest/node");
|
|
1112
|
+
ctx = await createVitest("test", { root, watch: false, cache: false, fsModuleCache: false });
|
|
1113
|
+
const selected = new Set((await ctx.globTestSpecifications()).map(spec => resolve(spec.moduleId)));
|
|
1114
|
+
const sources = new Map();
|
|
1115
|
+
async function walk(dir) {
|
|
1116
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
1117
|
+
if (["node_modules", ".git", ".brain", ".pi", ".agent_sources", "mutants.out", "dist"].includes(entry.name)) continue;
|
|
1118
|
+
const file = resolve(dir, entry.name);
|
|
1119
|
+
if (entry.isDirectory()) await walk(file);
|
|
1120
|
+
else if (/\.[cm]?[jt]sx?$/.test(file)) sources.set(file, await readFile(file, "utf8"));
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
await walk(root);
|
|
1124
|
+
// Read only explicit rootDir/outDir evidence, including JSONC and extends.
|
|
1125
|
+
// Do not depend on a compiler API in the tested package or infer build layout.
|
|
1126
|
+
async function configOptions(file, seen = new Set()) {
|
|
1127
|
+
if (seen.has(file)) throw new Error('cyclic tsconfig extends');
|
|
1128
|
+
const text = await readFile(file, 'utf8');
|
|
1129
|
+
const json = text.replace(/"(?:\\.|[^"\\])*"|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, token => token.startsWith('"') ? token : token.replace(/[^\r\n]/g, ' '))
|
|
1130
|
+
.replace(/("(?:\\.|[^"\\])*")|,\s*(?=[}\]])/g, (token, string) => string ?? '');
|
|
1131
|
+
const config = JSON.parse(json);
|
|
1132
|
+
let options = {};
|
|
1133
|
+
for (const base of Array.isArray(config.extends) ? config.extends : typeof config.extends === 'string' ? [config.extends] : []) {
|
|
1134
|
+
const path = base.startsWith('.') || isAbsolute(base) ? resolve(dirname(file), base) : createRequire(file).resolve(base);
|
|
1135
|
+
const candidate = await readFile(path).then(() => path, () => path + '.json');
|
|
1136
|
+
options = { ...options, ...await configOptions(candidate, new Set([...seen, file])) };
|
|
1137
|
+
}
|
|
1138
|
+
for (const key of ['rootDir', 'outDir']) if (typeof config.compilerOptions?.[key] === 'string') options[key] = resolve(dirname(file), config.compilerOptions[key]);
|
|
1139
|
+
return options;
|
|
1140
|
+
}
|
|
1141
|
+
let options = {};
|
|
1142
|
+
try { options = await configOptions(resolve(root, process.argv[1])); }
|
|
1143
|
+
catch { /* No proven mapping: restrict by importing tests only. */ }
|
|
1144
|
+
function sourceFile(path) {
|
|
1145
|
+
return [path, path.replace(/\.[cm]?js$/, '.ts'), path.replace(/\.[cm]?js$/, '.mts'), path.replace(/\.[cm]?js$/, '.cts'), path + '.ts', path + '.tsx', path + '.mts', path + '.cts', resolve(path, 'index.ts')].find(p => sources.has(p) && !/\.d\.[cm]?ts$/.test(p));
|
|
1146
|
+
}
|
|
1147
|
+
function exportTypes(specifier) {
|
|
1148
|
+
const key = specifier === pkg.name ? '.' : './' + specifier.slice(pkg.name.length + 1);
|
|
1149
|
+
let entry = pkg.exports;
|
|
1150
|
+
let wildcard;
|
|
1151
|
+
if (entry && typeof entry === 'object' && Object.keys(entry).some(key => key.startsWith('.'))) {
|
|
1152
|
+
if (key in entry) entry = entry[key];
|
|
1153
|
+
else {
|
|
1154
|
+
const pattern = Object.keys(entry).find(pattern => pattern.includes('*') && key.startsWith(pattern.split('*')[0]) && key.endsWith(pattern.split('*')[1]));
|
|
1155
|
+
if (!pattern) return;
|
|
1156
|
+
const [before, after] = pattern.split('*');
|
|
1157
|
+
wildcard = key.slice(before.length, after.length ? -after.length : undefined);
|
|
1158
|
+
entry = entry[pattern];
|
|
1159
|
+
}
|
|
1160
|
+
} else if (key !== '.') return;
|
|
1161
|
+
function types(value) {
|
|
1162
|
+
if (!value || typeof value !== 'object') return;
|
|
1163
|
+
if (typeof value.types === 'string') return value.types;
|
|
1164
|
+
return types(value.types) ?? types(value.import) ?? types(value.default);
|
|
1165
|
+
}
|
|
1166
|
+
const path = types(entry) ?? (key === '.' ? pkg.types : undefined);
|
|
1167
|
+
return typeof path === 'string' ? resolve(root, wildcard === undefined ? path : path.replaceAll('*', wildcard)) : undefined;
|
|
1168
|
+
}
|
|
1169
|
+
function mappedSource(entry, types) {
|
|
1170
|
+
for (const path of [types, entry]) {
|
|
1171
|
+
if (!path) continue;
|
|
1172
|
+
if (/\.[cm]?tsx?$/.test(path) && !/\.d\.[cm]?ts$/.test(path)) {
|
|
1173
|
+
const direct = sourceFile(path);
|
|
1174
|
+
if (direct) return direct;
|
|
1175
|
+
}
|
|
1176
|
+
if (!options.rootDir || !options.outDir) continue;
|
|
1177
|
+
const inside = relative(options.outDir, path);
|
|
1178
|
+
if (inside === '..' || inside.startsWith('..' + sep) || isAbsolute(inside)) continue;
|
|
1179
|
+
const stem = inside.replace(/(?:\.d)?\.[cm]?[jt]sx?$/, '');
|
|
1180
|
+
const mapped = sourceFile(resolve(options.rootDir, stem));
|
|
1181
|
+
if (mapped) return mapped;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
const edges = new Map();
|
|
1185
|
+
const built = [];
|
|
1186
|
+
for (const [file, text] of sources) {
|
|
1187
|
+
const dependencies = new Set();
|
|
1188
|
+
edges.set(file, dependencies);
|
|
1189
|
+
for (const match of text.matchAll(/(?:from\s*|import\s*\(?\s*|require\s*\(\s*)["']([^"']+)["']/g)) {
|
|
1190
|
+
let target;
|
|
1191
|
+
let source;
|
|
1192
|
+
const specifier = match[1];
|
|
1193
|
+
if (specifier.startsWith('.')) target = resolve(dirname(file), specifier);
|
|
1194
|
+
else {
|
|
1195
|
+
try {
|
|
1196
|
+
const self = pkg.name && (specifier === pkg.name || specifier.startsWith(pkg.name + '/'));
|
|
1197
|
+
target = self ? fileURLToPath(import.meta.resolve(specifier)) : createRequire(file).resolve(specifier);
|
|
1198
|
+
if (self && (!/\.[cm]?tsx?$/.test(target) || /\.d\.[cm]?ts$/.test(target))) {
|
|
1199
|
+
source = mappedSource(target, exportTypes(specifier));
|
|
1200
|
+
built.push({ importer: file, source, reason: relative(root, file) + ' imports ' + specifier + '; self entry resolves to built output ' + relative(root, target) + ', not mutated TypeScript source' + (source ? '; mapped source ' + relative(root, source) : '; source mapping unavailable') });
|
|
1201
|
+
}
|
|
1202
|
+
} catch { continue; }
|
|
1203
|
+
}
|
|
1204
|
+
const candidate = source ?? sourceFile(target);
|
|
1205
|
+
if (candidate) dependencies.add(candidate);
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
function dependencies(file, seen = new Set()) {
|
|
1209
|
+
if (seen.has(file)) return seen;
|
|
1210
|
+
seen.add(file);
|
|
1211
|
+
for (const dependency of edges.get(file) ?? []) dependencies(dependency, seen);
|
|
1212
|
+
return seen;
|
|
1213
|
+
}
|
|
1214
|
+
const closures = new Map([...selected].map(file => [file, dependencies(file)]));
|
|
1215
|
+
for (const entry of built) {
|
|
1216
|
+
const testFiles = [...selected].filter(file => closures.get(file).has(entry.importer)).map(file => relative(root, file));
|
|
1217
|
+
if (testFiles.length) issues.push({ kind: 'built', ...(entry.source ? { files: [...dependencies(entry.source)].map(file => relative(root, file)) } : {}), testFiles, reason: entry.reason });
|
|
1218
|
+
}
|
|
1219
|
+
const reached = new Set([...closures.values()].flatMap(files => [...files]));
|
|
1220
|
+
for (const [file, text] of sources) {
|
|
1221
|
+
const testFile = /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(file)
|
|
1222
|
+
|| (/["'](?:node:test|vitest|@effect\/vitest)["']/.test(text) && /\b(?:it|test|describe)\s*(?:\.|\()/.test(text));
|
|
1223
|
+
if (reached.has(file) || !testFile) continue;
|
|
1224
|
+
for (const target of dependencies(file)) {
|
|
1225
|
+
if (target !== file) issues.push({ kind: 'target', file: relative(root, target), reason: relative(root, file) + ' imports this target but is absent from Vitest resolved test files' });
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
} catch (error) {
|
|
1229
|
+
issues.push({ kind: 'warning', reason: 'Cannot verify Vitest resolved selection: ' + String(error) });
|
|
1230
|
+
} finally { await ctx?.close(); }
|
|
1231
|
+
}
|
|
1232
|
+
console.log('mutant-cafe-preflight:' + JSON.stringify([...new Map(issues.map(issue => [JSON.stringify(issue), issue])).values()]));
|
|
1233
|
+
`;
|
|
1234
|
+
var preflight = Effect3.fn("TestRunner.preflight")(function* (root, tsconfig = "tsconfig.json") {
|
|
1235
|
+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
|
1236
|
+
const output = yield* spawner.string(ChildProcess.make("node", ["--input-type=module", "--eval", probe, tsconfig], { cwd: root, stdin: "ignore" }));
|
|
1237
|
+
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* Schema5.decodeEffect(Schema5.fromJsonString(Issues))(encoded);
|
|
1239
|
+
return issues;
|
|
1240
|
+
});
|
|
1241
|
+
function unreliableFor(baseline, file, testFiles) {
|
|
1242
|
+
return baseline.unreliable?.filter((issue) => {
|
|
1243
|
+
switch (issue.kind) {
|
|
1244
|
+
case "runner":
|
|
1245
|
+
return true;
|
|
1246
|
+
case "warning":
|
|
1247
|
+
return false;
|
|
1248
|
+
case "target":
|
|
1249
|
+
return issue.file === file;
|
|
1250
|
+
case "built":
|
|
1251
|
+
return (issue.files === void 0 || issue.files.includes(file)) && (testFiles?.some((test) => issue.testFiles.includes(test)) ?? false);
|
|
1252
|
+
}
|
|
1253
|
+
}) ?? [];
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
// packages/runner/src/TestRunner.ts
|
|
1257
|
+
import * as Effect4 from "effect/Effect";
|
|
800
1258
|
import * as Layer3 from "effect/Layer";
|
|
801
1259
|
import * as FileSystem3 from "effect/FileSystem";
|
|
802
1260
|
import * as Path3 from "effect/Path";
|
|
803
1261
|
import * as Stream2 from "effect/Stream";
|
|
804
|
-
import * as
|
|
805
|
-
import * as
|
|
806
|
-
|
|
807
|
-
|
|
1262
|
+
import * as Schema6 from "effect/Schema";
|
|
1263
|
+
import * as ChildProcess2 from "effect/process/ChildProcess";
|
|
1264
|
+
import * as ChildProcessSpawner3 from "effect/process/ChildProcessSpawner";
|
|
1265
|
+
var TestRunnerLive = Layer3.effect(TestRunner, Effect4.gen(function* () {
|
|
1266
|
+
const spawner = yield* ChildProcessSpawner3.ChildProcessSpawner;
|
|
808
1267
|
const fs = yield* FileSystem3.FileSystem;
|
|
809
1268
|
const path = yield* Path3.Path;
|
|
810
|
-
const execute =
|
|
1269
|
+
const execute = Effect4.fn("TestRunner.execute")(function* (dir, args, timeoutMs) {
|
|
811
1270
|
const reporterDir = yield* fs.makeTempDirectoryScoped({ prefix: "mutant-vitest-" }).pipe(
|
|
812
|
-
|
|
1271
|
+
Effect4.mapError((error3) => new TestSpawnError({ command: ["vitest"], message: String(error3) }))
|
|
813
1272
|
);
|
|
814
1273
|
const reporter = path.join(reporterDir, "reporter.mjs");
|
|
815
1274
|
const marker = `mutant-cafe:${path.basename(reporterDir)}:`;
|
|
816
|
-
yield* fs.writeFileString(reporter, `
|
|
1275
|
+
yield* fs.writeFileString(reporter, `import { relative } from "node:path";
|
|
1276
|
+
export default class {
|
|
817
1277
|
files = 0;
|
|
818
|
-
onTestRunStart(specifications) { this.files = specifications.length; }
|
|
1278
|
+
onTestRunStart(specifications) { this.files = specifications.length; console.log(${JSON.stringify(marker + "selected:")} + JSON.stringify(specifications.map(spec => relative(process.cwd(), spec.moduleId)))); }
|
|
819
1279
|
onTestModuleCollected() { console.log(${JSON.stringify(marker + "collected")}); }
|
|
820
1280
|
onTestCaseResult(test) { if (test.result().state === "failed") console.log(${JSON.stringify(marker + "failed")}); }
|
|
821
1281
|
onTestRunEnd() { if (this.files === 0) console.log(${JSON.stringify(marker + "empty")}); }
|
|
822
|
-
}`).pipe(
|
|
1282
|
+
}`).pipe(Effect4.mapError((error3) => new TestSpawnError({ command: ["vitest"], message: String(error3) })));
|
|
823
1283
|
const command = [
|
|
824
1284
|
"npx",
|
|
825
1285
|
"--no",
|
|
@@ -833,11 +1293,12 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect3.gen(function* () {
|
|
|
833
1293
|
"--no-cache",
|
|
834
1294
|
"--no-fsModuleCache"
|
|
835
1295
|
];
|
|
1296
|
+
if (timeoutMs === void 0) yield* Console.error(`Baseline command: ${command.join(" ")} (cwd: ${dir.path})`);
|
|
836
1297
|
const started = yield* Clock.currentTimeMillis;
|
|
837
1298
|
const chunks = [];
|
|
838
1299
|
let exitCode = 1;
|
|
839
|
-
const child =
|
|
840
|
-
const handle = yield* spawner.spawn(
|
|
1300
|
+
const child = Effect4.scoped(Effect4.gen(function* () {
|
|
1301
|
+
const handle = yield* spawner.spawn(ChildProcess2.make(command[0], command.slice(1), {
|
|
841
1302
|
cwd: dir.path,
|
|
842
1303
|
// Node's scoped spawner kills the detached process group, not just pnpm.
|
|
843
1304
|
detached: true,
|
|
@@ -845,44 +1306,57 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect3.gen(function* () {
|
|
|
845
1306
|
forceKillAfter: "100 millis",
|
|
846
1307
|
stdin: "ignore"
|
|
847
1308
|
}));
|
|
848
|
-
const collect = handle.all.pipe(Stream2.decodeText(), Stream2.runForEach((chunk) =>
|
|
1309
|
+
const collect = handle.all.pipe(Stream2.decodeText(), Stream2.runForEach((chunk) => Effect4.sync(() => {
|
|
849
1310
|
chunks.push(chunk);
|
|
850
1311
|
})));
|
|
851
|
-
const [code] = yield*
|
|
1312
|
+
const [code] = yield* Effect4.all([handle.exitCode, collect], { concurrency: "unbounded" });
|
|
852
1313
|
exitCode = code;
|
|
853
1314
|
return code === 0 ? "passed" : "failed";
|
|
854
1315
|
}));
|
|
855
1316
|
const status = yield* (timeoutMs === void 0 ? child : child.pipe(
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
)).pipe(
|
|
1317
|
+
Effect4.timeout(timeoutMs),
|
|
1318
|
+
Effect4.catchTag("TimeoutError", () => Effect4.succeed("timedOut"))
|
|
1319
|
+
)).pipe(Effect4.mapError((error3) => new TestSpawnError({ command, message: error3.message })));
|
|
859
1320
|
const ended = yield* Clock.currentTimeMillis;
|
|
860
1321
|
const output = chunks.join("");
|
|
861
1322
|
const failed = output.includes(marker + "failed");
|
|
1323
|
+
const selection = output.split("\n").find((line) => line.includes(marker + "selected:"))?.split(marker + "selected:")[1];
|
|
1324
|
+
const selected = selection === void 0 ? [] : yield* Schema6.decodeEffect(Schema6.fromJsonString(Schema6.Array(Schema6.String)))(selection).pipe(
|
|
1325
|
+
Effect4.mapError((error3) => new TestSpawnError({ command, message: `Cannot decode Vitest selected files: ${String(error3)}` }))
|
|
1326
|
+
);
|
|
862
1327
|
const run2 = {
|
|
863
1328
|
status: failed ? "failed" : status === "passed" && output.includes(marker + "empty") ? "untested" : status,
|
|
864
1329
|
durationMs: ended - started,
|
|
865
1330
|
command,
|
|
866
1331
|
output,
|
|
867
|
-
testsCollected: output.includes(marker + "collected")
|
|
1332
|
+
testsCollected: output.includes(marker + "collected"),
|
|
1333
|
+
testFiles: selected
|
|
868
1334
|
};
|
|
869
1335
|
return { ...run2, exitCode };
|
|
870
|
-
},
|
|
1336
|
+
}, Effect4.scoped);
|
|
871
1337
|
return TestRunner.of({
|
|
872
|
-
baseline:
|
|
1338
|
+
baseline: Effect4.fn("TestRunner.baseline")(function* (dir, tsconfig) {
|
|
1339
|
+
const unreliable = yield* preflight(dir.path, tsconfig).pipe(Effect4.provideService(ChildProcessSpawner3.ChildProcessSpawner, spawner), Effect4.catch((error3) => Effect4.succeed([{ kind: "warning", reason: `Cannot verify runner selection: ${String(error3)}` }])));
|
|
1340
|
+
for (const issue of unreliable) yield* Console.warn(`Warning (${issue.kind}): ${issue.reason}`);
|
|
1341
|
+
if (unreliable.some((issue) => issue.kind === "runner")) {
|
|
1342
|
+
const command = ["npx", "--no", "vitest", "run", "--passWithNoTests"];
|
|
1343
|
+
yield* Console.warn(`Baseline command (not executed: unsupported runner): ${command.join(" ")}`);
|
|
1344
|
+
return { durationMs: 0, testCommand: command, unreliable };
|
|
1345
|
+
}
|
|
873
1346
|
const run2 = yield* execute(dir, ["run", "--passWithNoTests"]);
|
|
874
1347
|
if (run2.status !== "passed" && run2.status !== "untested") {
|
|
875
|
-
return yield*
|
|
1348
|
+
return yield* Effect4.fail(new BaselineFailed({ exitCode: run2.exitCode, output: run2.output, command: run2.command }));
|
|
876
1349
|
}
|
|
877
|
-
return { durationMs: run2.durationMs, testCommand: run2.command };
|
|
1350
|
+
return { durationMs: run2.durationMs, testCommand: run2.command, unreliable };
|
|
878
1351
|
}),
|
|
879
|
-
runRelated:
|
|
1352
|
+
runRelated: Effect4.fn("TestRunner.runRelated")(function* (dir, file, timeoutMs) {
|
|
880
1353
|
const related = yield* execute(dir, ["related", file, "--run", "--passWithNoTests"], timeoutMs);
|
|
881
1354
|
if (related.status !== "untested") return related;
|
|
882
1355
|
const remaining = Math.max(1, timeoutMs - related.durationMs);
|
|
883
1356
|
const full = yield* execute(dir, ["run", "--passWithNoTests"], remaining);
|
|
884
1357
|
return {
|
|
885
1358
|
...full,
|
|
1359
|
+
status: full.status === "passed" ? "untested" : full.status,
|
|
886
1360
|
durationMs: related.durationMs + full.durationMs,
|
|
887
1361
|
output: related.output + "\nFull-suite fallback:\n" + full.output
|
|
888
1362
|
};
|
|
@@ -893,11 +1367,11 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect3.gen(function* () {
|
|
|
893
1367
|
// packages/runner/src/Run.ts
|
|
894
1368
|
import { createEffectActor, createEffectLogic, join, send, setupEffect } from "@xstate/effect";
|
|
895
1369
|
import { types } from "xstate";
|
|
896
|
-
import * as
|
|
1370
|
+
import * as Effect5 from "effect/Effect";
|
|
897
1371
|
import * as Pool from "effect/Pool";
|
|
898
1372
|
import * as Path5 from "effect/Path";
|
|
899
1373
|
import * as Result from "effect/Result";
|
|
900
|
-
import * as
|
|
1374
|
+
import * as Schema7 from "effect/Schema";
|
|
901
1375
|
import * as Scope from "effect/Scope";
|
|
902
1376
|
import * as Stream3 from "effect/Stream";
|
|
903
1377
|
var ScratchPool = class {
|
|
@@ -906,7 +1380,7 @@ var ScratchPool = class {
|
|
|
906
1380
|
this.value = value;
|
|
907
1381
|
}
|
|
908
1382
|
};
|
|
909
|
-
var runMutants =
|
|
1383
|
+
var runMutants = Effect5.fn("Runner.runMutants")(function* (config, mutants) {
|
|
910
1384
|
const scratch = yield* Scratch;
|
|
911
1385
|
const tests = yield* TestRunner;
|
|
912
1386
|
const source = yield* MutantSource;
|
|
@@ -915,47 +1389,49 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
|
|
|
915
1389
|
const path = yield* Path5.Path;
|
|
916
1390
|
const jobs = Math.max(1, Math.floor(config.jobs));
|
|
917
1391
|
const report = (state2) => ({
|
|
918
|
-
schemaVersion:
|
|
1392
|
+
schemaVersion: 2,
|
|
919
1393
|
tool: "mutant.cafe",
|
|
920
1394
|
root: config.root,
|
|
921
1395
|
baseline: state2.baseline,
|
|
922
1396
|
timeoutMs: state2.timeoutMs,
|
|
923
|
-
results: state2.results
|
|
1397
|
+
results: state2.results,
|
|
1398
|
+
...state2.failure === void 0 ? {} : { failure: state2.failure._tag === "BaselineFailed" ? `${state2.failure._tag}: ${state2.failure.command.join(" ")}
|
|
1399
|
+
${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
|
|
924
1400
|
});
|
|
925
|
-
const capture = (effect5) =>
|
|
926
|
-
const copying = createEffectLogic(() => capture(
|
|
1401
|
+
const capture = (effect5) => Effect5.result(effect5);
|
|
1402
|
+
const copying = createEffectLogic(() => capture(Effect5.gen(function* () {
|
|
927
1403
|
const pool = yield* Pool.make({ acquire: scratch.acquire(config.root), size: jobs }).pipe(
|
|
928
|
-
|
|
1404
|
+
Effect5.provideService(Scope.Scope, scope)
|
|
929
1405
|
);
|
|
930
|
-
yield*
|
|
1406
|
+
yield* Effect5.scoped(Pool.get(pool));
|
|
931
1407
|
return new ScratchPool(pool);
|
|
932
1408
|
})));
|
|
933
|
-
const baselining = createEffectLogic(({ input }) => capture(
|
|
934
|
-
if (input === void 0) return yield*
|
|
935
|
-
const baseline = yield*
|
|
1409
|
+
const baselining = createEffectLogic(({ input }) => capture(Effect5.gen(function* () {
|
|
1410
|
+
if (input === void 0) return yield* Effect5.die("Missing scratch pool");
|
|
1411
|
+
const baseline = yield* Effect5.scoped(Effect5.gen(function* () {
|
|
936
1412
|
const dir = yield* Pool.get(input.value);
|
|
937
|
-
return yield* tests.baseline(dir);
|
|
1413
|
+
return yield* tests.baseline(dir, path.isAbsolute(config.tsconfig) ? path.relative(config.root, config.tsconfig) : config.tsconfig);
|
|
938
1414
|
}));
|
|
939
1415
|
return { baseline, timeoutMs: config.timeoutMs ?? Math.max(config.minimumTimeoutMs, Math.ceil(config.timeoutMultiplier * baseline.durationMs)) };
|
|
940
1416
|
})));
|
|
941
1417
|
const generating = createEffectLogic(() => capture(Stream3.runCollect(mutants ?? source.generate(config))));
|
|
942
|
-
const testing = createEffectLogic(({ input }) => capture(
|
|
1418
|
+
const testing = createEffectLogic(({ input }) => capture(Effect5.gen(function* () {
|
|
943
1419
|
const dirs = input.state.pool?.value;
|
|
944
|
-
if (dirs === void 0) return yield*
|
|
1420
|
+
if (dirs === void 0) return yield* Effect5.die("Missing scratch pool");
|
|
945
1421
|
const neverBudgets = /* @__PURE__ */ new Map();
|
|
946
1422
|
for (const mutant of input.state.pending) {
|
|
947
|
-
if (mutant.genre !== "EffectNever" || neverBudgets.has(mutant.file)) continue;
|
|
948
|
-
const measured = yield*
|
|
1423
|
+
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
|
+
const measured = yield* Effect5.scoped(Effect5.gen(function* () {
|
|
949
1425
|
const dir = yield* Pool.get(dirs);
|
|
950
1426
|
return yield* tests.runRelated(dir, path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file, input.state.timeoutMs);
|
|
951
1427
|
}));
|
|
952
1428
|
if (measured.status === "failed" || measured.status === "timedOut") {
|
|
953
|
-
return yield* new BaselineFailed({ exitCode: 1, output: measured.output });
|
|
1429
|
+
return yield* new BaselineFailed({ exitCode: 1, output: measured.output, command: measured.command });
|
|
954
1430
|
}
|
|
955
1431
|
neverBudgets.set(mutant.file, Math.max(config.neverTimeoutMs, Math.ceil(measured.durationMs * config.timeoutMultiplier)));
|
|
956
1432
|
}
|
|
957
1433
|
yield* Stream3.fromIterable(input.state.pending).pipe(
|
|
958
|
-
Stream3.mapEffect((mutant) =>
|
|
1434
|
+
Stream3.mapEffect((mutant) => Effect5.scoped(Effect5.gen(function* () {
|
|
959
1435
|
const viability = yield* source.checkViable(mutant);
|
|
960
1436
|
if (!viability.viable) {
|
|
961
1437
|
const result3 = { mutant, outcome: "unviable", durationMs: 0, testCommand: [], diagnostics: viability.diagnostics };
|
|
@@ -963,20 +1439,29 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
|
|
|
963
1439
|
yield* reporter.progress(result3);
|
|
964
1440
|
return;
|
|
965
1441
|
}
|
|
1442
|
+
const localFile = path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file;
|
|
1443
|
+
const unreliable = unreliableFor(input.state.baseline, localFile);
|
|
1444
|
+
if (unreliable.length) {
|
|
1445
|
+
const result3 = { mutant, outcome: "unreliable", durationMs: 0, testCommand: input.state.baseline.testCommand, diagnostics: unreliable.map((issue) => issue.reason) };
|
|
1446
|
+
yield* input.record(result3);
|
|
1447
|
+
yield* reporter.progress(result3);
|
|
1448
|
+
return;
|
|
1449
|
+
}
|
|
966
1450
|
const dir = yield* Pool.get(dirs);
|
|
967
|
-
const run2 = yield*
|
|
1451
|
+
const run2 = yield* Effect5.acquireUseRelease(
|
|
968
1452
|
dir.apply(mutant),
|
|
969
1453
|
() => tests.runRelated(dir, path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file, mutant.genre === "EffectNever" ? neverBudgets.get(mutant.file) : input.state.timeoutMs),
|
|
970
1454
|
// A dirty directory must never return to the pool, even on cancel.
|
|
971
|
-
() => dir.revert(mutant).pipe(
|
|
1455
|
+
() => dir.revert(mutant).pipe(Effect5.orDie)
|
|
972
1456
|
);
|
|
1457
|
+
const selectedIssues = unreliableFor(input.state.baseline, localFile, run2.testFiles);
|
|
973
1458
|
const result2 = {
|
|
974
1459
|
mutant,
|
|
975
1460
|
// A kill before collection proves nothing about whether tests noticed.
|
|
976
|
-
outcome: run2.status === "timedOut" ? mutant.genre === "EffectNever" && run2.testsCollected ? "caught" : "timeout" : run2.status === "failed" ? "caught" : run2.status === "untested" ? "untested" : "missed",
|
|
1461
|
+
outcome: selectedIssues.length ? "unreliable" : run2.status === "timedOut" ? mutant.genre === "EffectNever" && run2.testsCollected ? "caught" : "timeout" : run2.status === "failed" ? "caught" : run2.status === "untested" ? "untested" : "missed",
|
|
977
1462
|
durationMs: run2.durationMs,
|
|
978
1463
|
testCommand: run2.command,
|
|
979
|
-
diagnostics:
|
|
1464
|
+
diagnostics: selectedIssues.map((issue) => issue.reason),
|
|
980
1465
|
...run2.output === "" ? {} : { output: run2.output }
|
|
981
1466
|
};
|
|
982
1467
|
yield* input.record(result2);
|
|
@@ -986,12 +1471,12 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
|
|
|
986
1471
|
);
|
|
987
1472
|
})));
|
|
988
1473
|
const reporting = createEffectLogic(({ input }) => capture(
|
|
989
|
-
input.reported ?
|
|
1474
|
+
input.reported ? Effect5.void : reporter.write(report(input))
|
|
990
1475
|
));
|
|
991
1476
|
const machine = setupEffect({
|
|
992
1477
|
schemas: {
|
|
993
1478
|
context: types(),
|
|
994
|
-
events: { CANCEL:
|
|
1479
|
+
events: { CANCEL: Schema7.Struct({}), RESULT: Schema7.Struct({ result: MutantResult }) }
|
|
995
1480
|
},
|
|
996
1481
|
actors: { copying, baselining, generating, testing, reporting }
|
|
997
1482
|
}).createMachine({
|
|
@@ -1015,7 +1500,11 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
|
|
|
1015
1500
|
baseline: { invoke: {
|
|
1016
1501
|
src: "baselining",
|
|
1017
1502
|
input: ({ context }) => context.pool,
|
|
1018
|
-
onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "generating", context: { ...context, ...event.output.success } } : { target:
|
|
1503
|
+
onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "generating", context: { ...context, ...event.output.success } } : { target: "reporting", context: {
|
|
1504
|
+
...context,
|
|
1505
|
+
failure: event.output.failure,
|
|
1506
|
+
baseline: event.output.failure._tag === "BaselineFailed" ? { durationMs: 0, testCommand: event.output.failure.command } : context.baseline
|
|
1507
|
+
} }
|
|
1019
1508
|
} },
|
|
1020
1509
|
generating: { invoke: { src: "generating", onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "testing", context: { ...context, pending: event.output.success } } : { target: "reporting", context: { ...context, failure: event.output.failure } } } },
|
|
1021
1510
|
testing: { invoke: {
|
|
@@ -1049,54 +1538,53 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
|
|
|
1049
1538
|
failure: Result.isFailure(event.output) ? event.output.failure : context.failure
|
|
1050
1539
|
} })
|
|
1051
1540
|
} },
|
|
1052
|
-
baselineFailed: { type: "final" },
|
|
1053
1541
|
failed: { type: "final" },
|
|
1054
1542
|
done: { type: "final" }
|
|
1055
1543
|
}
|
|
1056
1544
|
});
|
|
1057
|
-
const state = yield*
|
|
1545
|
+
const state = yield* Effect5.scoped(Effect5.gen(function* () {
|
|
1058
1546
|
const actor = yield* createEffectActor(machine);
|
|
1059
|
-
return yield* join(actor).pipe(
|
|
1547
|
+
return yield* join(actor).pipe(Effect5.orDie, Effect5.onInterrupt(() => Effect5.gen(function* () {
|
|
1060
1548
|
yield* send(actor, { type: "CANCEL" });
|
|
1061
|
-
yield* join(actor).pipe(
|
|
1549
|
+
yield* join(actor).pipe(Effect5.orDie);
|
|
1062
1550
|
})));
|
|
1063
1551
|
}));
|
|
1064
1552
|
if (state.failure !== void 0) return yield* state.failure;
|
|
1065
1553
|
return report(state);
|
|
1066
|
-
},
|
|
1554
|
+
}, Effect5.scoped);
|
|
1067
1555
|
|
|
1068
1556
|
// packages/cli/src/bin.ts
|
|
1069
|
-
import * as
|
|
1557
|
+
import * as Effect10 from "effect/Effect";
|
|
1070
1558
|
import * as Layer5 from "effect/Layer";
|
|
1071
|
-
import * as
|
|
1559
|
+
import * as Stream7 from "effect/Stream";
|
|
1072
1560
|
|
|
1073
1561
|
// packages/cli/src/Command.ts
|
|
1074
|
-
import * as
|
|
1075
|
-
import * as
|
|
1076
|
-
import * as
|
|
1562
|
+
import * as Console3 from "effect/Console";
|
|
1563
|
+
import * as Effect9 from "effect/Effect";
|
|
1564
|
+
import * as FileSystem11 from "effect/FileSystem";
|
|
1077
1565
|
import * as Option from "effect/Option";
|
|
1078
|
-
import * as
|
|
1566
|
+
import * as Path13 from "effect/Path";
|
|
1079
1567
|
import * as Ref from "effect/Ref";
|
|
1080
|
-
import * as
|
|
1081
|
-
import * as
|
|
1568
|
+
import * as Schema11 from "effect/Schema";
|
|
1569
|
+
import * as Stream6 from "effect/Stream";
|
|
1082
1570
|
import * as Command from "effect/cli/Command";
|
|
1083
1571
|
import * as Flag from "effect/cli/Flag";
|
|
1084
1572
|
|
|
1085
1573
|
// packages/cli/src/Diff.ts
|
|
1086
|
-
import * as
|
|
1574
|
+
import * as Effect6 from "effect/Effect";
|
|
1087
1575
|
import * as FileSystem5 from "effect/FileSystem";
|
|
1088
1576
|
import * as Path7 from "effect/Path";
|
|
1089
|
-
import * as
|
|
1577
|
+
import * as Schema8 from "effect/Schema";
|
|
1090
1578
|
import * as Stream4 from "effect/Stream";
|
|
1091
|
-
import * as
|
|
1092
|
-
var DiffMismatch = class extends
|
|
1093
|
-
path:
|
|
1094
|
-
message:
|
|
1579
|
+
import * as ChildProcess3 from "effect/process/ChildProcess";
|
|
1580
|
+
var DiffMismatch = class extends Schema8.TaggedError()("DiffMismatch", {
|
|
1581
|
+
path: Schema8.String,
|
|
1582
|
+
message: Schema8.String
|
|
1095
1583
|
}) {
|
|
1096
1584
|
};
|
|
1097
|
-
var parseDiff = (text, path) =>
|
|
1585
|
+
var parseDiff = (text, path) => Effect6.try({
|
|
1098
1586
|
try: () => {
|
|
1099
|
-
const
|
|
1587
|
+
const fail3 = (message) => {
|
|
1100
1588
|
throw new DiffParseError({ path, message });
|
|
1101
1589
|
};
|
|
1102
1590
|
if (text === "") return [];
|
|
@@ -1108,12 +1596,12 @@ var parseDiff = (text, path) => Effect5.try({
|
|
|
1108
1596
|
while (i < input.length) {
|
|
1109
1597
|
const line = input[i++];
|
|
1110
1598
|
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;
|
|
1111
|
-
if (!line.startsWith("--- "))
|
|
1599
|
+
if (!line.startsWith("--- ")) fail3("Expected a unified diff file header");
|
|
1112
1600
|
const next = input[i++];
|
|
1113
|
-
if (!next?.startsWith("+++ "))
|
|
1601
|
+
if (!next?.startsWith("+++ ")) fail3("Missing new-side file header");
|
|
1114
1602
|
const raw = next.slice(4).split(" ")[0];
|
|
1115
1603
|
const decoded = raw.startsWith('"') ? JSON.parse(raw) : raw;
|
|
1116
|
-
if (typeof decoded !== "string")
|
|
1604
|
+
if (typeof decoded !== "string") fail3("Invalid file path");
|
|
1117
1605
|
const file = String(decoded).replace(/^b\//, "");
|
|
1118
1606
|
const lines2 = [];
|
|
1119
1607
|
let hunks = 0;
|
|
@@ -1121,22 +1609,22 @@ var parseDiff = (text, path) => Effect5.try({
|
|
|
1121
1609
|
let previousOldEnd = 0;
|
|
1122
1610
|
while (input[i]?.startsWith("@@")) {
|
|
1123
1611
|
const match2 = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:.*)$/.exec(input[i++]);
|
|
1124
|
-
if (!match2)
|
|
1612
|
+
if (!match2) fail3("Invalid hunk header");
|
|
1125
1613
|
let oldRemaining = Number(match2[2] ?? 1);
|
|
1126
1614
|
let newRemaining = Number(match2[4] ?? 1);
|
|
1127
1615
|
let newLine = Number(match2[3]);
|
|
1128
1616
|
const oldStart = Number(match2[1]);
|
|
1129
1617
|
const oldCount = oldRemaining;
|
|
1130
|
-
if (![oldStart, oldRemaining, newLine, newRemaining].every(Number.isSafeInteger))
|
|
1131
|
-
if (oldRemaining > 0 && oldStart === 0 || newRemaining > 0 && newLine === 0)
|
|
1132
|
-
if (newLine < previousEnd || oldStart < previousOldEnd)
|
|
1618
|
+
if (![oldStart, oldRemaining, newLine, newRemaining].every(Number.isSafeInteger)) fail3("Hunk range is not a safe integer");
|
|
1619
|
+
if (oldRemaining > 0 && oldStart === 0 || newRemaining > 0 && newLine === 0) fail3("Nonempty hunk cannot start at zero");
|
|
1620
|
+
if (newLine < previousEnd || oldStart < previousOldEnd) fail3("Overlapping or unordered hunks");
|
|
1133
1621
|
let previousPrefix = "";
|
|
1134
1622
|
const markNoNewline = () => {
|
|
1135
1623
|
if (previousPrefix === "+" || previousPrefix === " ") {
|
|
1136
1624
|
const last = lines2.at(-1);
|
|
1137
|
-
if (last === void 0 || last.noNewline)
|
|
1625
|
+
if (last === void 0 || last.noNewline) fail3("Unexpected no-newline marker");
|
|
1138
1626
|
lines2[lines2.length - 1] = { ...last, noNewline: true };
|
|
1139
|
-
} else if (previousPrefix !== "-")
|
|
1627
|
+
} else if (previousPrefix !== "-") fail3("Unexpected no-newline marker");
|
|
1140
1628
|
previousPrefix = "";
|
|
1141
1629
|
};
|
|
1142
1630
|
hunks++;
|
|
@@ -1146,15 +1634,15 @@ var parseDiff = (text, path) => Effect5.try({
|
|
|
1146
1634
|
markNoNewline();
|
|
1147
1635
|
continue;
|
|
1148
1636
|
}
|
|
1149
|
-
if (body === void 0)
|
|
1637
|
+
if (body === void 0) fail3("Truncated hunk");
|
|
1150
1638
|
const prefix = body[0];
|
|
1151
1639
|
if (prefix === " " || prefix === "-") oldRemaining--;
|
|
1152
1640
|
if (prefix === " " || prefix === "+") {
|
|
1153
1641
|
newRemaining--;
|
|
1154
1642
|
lines2.push({ number: newLine++, text: body.slice(1), added: prefix === "+", noNewline: false });
|
|
1155
|
-
} else if (prefix !== "-")
|
|
1643
|
+
} else if (prefix !== "-") fail3("Invalid hunk line");
|
|
1156
1644
|
previousPrefix = prefix;
|
|
1157
|
-
if (oldRemaining < 0 || newRemaining < 0)
|
|
1645
|
+
if (oldRemaining < 0 || newRemaining < 0) fail3("Hunk count does not match its body");
|
|
1158
1646
|
}
|
|
1159
1647
|
if (input[i] === "\") {
|
|
1160
1648
|
markNoNewline();
|
|
@@ -1163,28 +1651,28 @@ var parseDiff = (text, path) => Effect5.try({
|
|
|
1163
1651
|
previousEnd = newLine;
|
|
1164
1652
|
previousOldEnd = oldStart + oldCount;
|
|
1165
1653
|
}
|
|
1166
|
-
if (hunks === 0)
|
|
1654
|
+
if (hunks === 0) fail3("File has no hunks");
|
|
1167
1655
|
sawFile = true;
|
|
1168
1656
|
if (file !== "/dev/null") patches.push({ file, lines: lines2 });
|
|
1169
1657
|
}
|
|
1170
|
-
if (!sawFile)
|
|
1658
|
+
if (!sawFile) fail3("No unified diff found");
|
|
1171
1659
|
return patches;
|
|
1172
1660
|
},
|
|
1173
|
-
catch: (
|
|
1661
|
+
catch: (error3) => Schema8.is(DiffParseError)(error3) ? error3 : new DiffParseError({ path, message: String(error3) })
|
|
1174
1662
|
});
|
|
1175
|
-
var
|
|
1663
|
+
var selectDiffScope = Effect6.fn("selectDiffScope")(function* (options) {
|
|
1176
1664
|
const fs = yield* FileSystem5.FileSystem;
|
|
1177
1665
|
const path = yield* Path7.Path;
|
|
1178
1666
|
const diffPath = path.resolve(options.root, options.diffPath);
|
|
1179
|
-
const text = yield* fs.readFileString(diffPath).pipe(
|
|
1667
|
+
const text = options.diffText ?? (yield* fs.readFileString(diffPath).pipe(Effect6.mapError((error3) => new DiffParseError({ path: diffPath, message: String(error3) }))));
|
|
1180
1668
|
const patches = yield* parseDiff(text, diffPath);
|
|
1181
|
-
const gitRoot = yield*
|
|
1182
|
-
const handle = yield*
|
|
1183
|
-
const [output, code] = yield*
|
|
1669
|
+
const gitRoot = yield* Effect6.scoped(Effect6.gen(function* () {
|
|
1670
|
+
const handle = yield* ChildProcess3.make("git", ["rev-parse", "--show-toplevel"], { cwd: options.root, stderr: "ignore" });
|
|
1671
|
+
const [output, code] = yield* Effect6.all([Stream4.mkString(Stream4.decodeText(handle.stdout)), handle.exitCode], { concurrency: "unbounded" });
|
|
1184
1672
|
if (Number(code) !== 0 || !output.trim()) return options.root;
|
|
1185
1673
|
const physicalRoot = yield* fs.realPath(options.root);
|
|
1186
1674
|
return path.resolve(options.root, path.relative(physicalRoot, output.trim()));
|
|
1187
|
-
})).pipe(
|
|
1675
|
+
})).pipe(Effect6.catch(() => Effect6.succeed(options.root)));
|
|
1188
1676
|
const changed = /* @__PURE__ */ new Map();
|
|
1189
1677
|
for (const patch of patches) {
|
|
1190
1678
|
const repositoryPath = path.resolve(gitRoot, patch.file);
|
|
@@ -1196,7 +1684,7 @@ var selectInDiff = Effect5.fn("selectInDiff")(function* (options) {
|
|
|
1196
1684
|
return yield* new DiffParseError({ path: diffPath, message: "Diff path escapes repository root" });
|
|
1197
1685
|
}
|
|
1198
1686
|
if (!(yield* fs.exists(candidate))) continue;
|
|
1199
|
-
const current = yield* fs.readFileString(candidate).pipe(
|
|
1687
|
+
const current = yield* fs.readFileString(candidate).pipe(Effect6.mapError((error3) => new DiffMismatch({ path: patch.file, message: String(error3) })));
|
|
1200
1688
|
const lines2 = current.split("\n");
|
|
1201
1689
|
const finalLine = current.endsWith("\n") ? lines2.length - 1 : lines2.length;
|
|
1202
1690
|
if (patch.lines.every((line) => {
|
|
@@ -1212,23 +1700,27 @@ var selectInDiff = Effect5.fn("selectInDiff")(function* (options) {
|
|
|
1212
1700
|
for (const line of patch.lines) if (line.added) added.add(line.number);
|
|
1213
1701
|
changed.set(absolute, added);
|
|
1214
1702
|
}
|
|
1215
|
-
return
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1703
|
+
return {
|
|
1704
|
+
mutants: options.mutants.filter((mutant) => {
|
|
1705
|
+
const added = changed.get(path.resolve(options.root, mutant.file));
|
|
1706
|
+
const end = mutant.span.end.line - (mutant.span.end.column === 1 ? 1 : 0);
|
|
1707
|
+
return added !== void 0 && [...added].some((line) => line >= mutant.span.start.line && line <= end);
|
|
1708
|
+
}),
|
|
1709
|
+
notMutated: options.notMutated.filter((item) => changed.has(path.resolve(options.root, item.file)))
|
|
1710
|
+
};
|
|
1220
1711
|
});
|
|
1221
1712
|
|
|
1222
1713
|
// packages/cli/src/ExitCode.ts
|
|
1223
|
-
var reportExitCode = (report) => report.results.some((result2) => result2.outcome === "missed"
|
|
1224
|
-
var errorExitCode = (
|
|
1225
|
-
switch (
|
|
1714
|
+
var reportExitCode = (report) => report.results.some((result2) => result2.outcome === "missed") ? 2 : report.results.some((result2) => result2.outcome === "unreliable") ? 7 : report.results.some((result2) => result2.outcome === "untested") ? 2 : report.results.some((result2) => result2.outcome === "timeout") ? 3 : 0;
|
|
1715
|
+
var errorExitCode = (error3) => {
|
|
1716
|
+
switch (error3._tag) {
|
|
1226
1717
|
case "BaselineFailed":
|
|
1227
1718
|
return 4;
|
|
1228
1719
|
case "DiffMismatch":
|
|
1229
1720
|
return 5;
|
|
1230
1721
|
case "DiffParseError":
|
|
1231
1722
|
return 6;
|
|
1723
|
+
case "ProgramLoadError":
|
|
1232
1724
|
case "UsageError":
|
|
1233
1725
|
case "ShowHelp":
|
|
1234
1726
|
case "InvalidValue":
|
|
@@ -1242,12 +1734,12 @@ var errorExitCode = (error2) => {
|
|
|
1242
1734
|
|
|
1243
1735
|
// packages/cli/src/Reporter.ts
|
|
1244
1736
|
import * as Clock2 from "effect/Clock";
|
|
1245
|
-
import * as
|
|
1246
|
-
import * as
|
|
1737
|
+
import * as Console2 from "effect/Console";
|
|
1738
|
+
import * as Effect7 from "effect/Effect";
|
|
1247
1739
|
import * as FileSystem7 from "effect/FileSystem";
|
|
1248
1740
|
import * as Layer4 from "effect/Layer";
|
|
1249
1741
|
import * as Path9 from "effect/Path";
|
|
1250
|
-
import * as
|
|
1742
|
+
import * as Schema9 from "effect/Schema";
|
|
1251
1743
|
import * as Semaphore from "effect/Semaphore";
|
|
1252
1744
|
|
|
1253
1745
|
// packages/cli/src/UnifiedDiff.ts
|
|
@@ -1323,7 +1815,8 @@ var unifiedDiff = (original, modified, file) => {
|
|
|
1323
1815
|
if (edit.sign !== "-") next++;
|
|
1324
1816
|
}
|
|
1325
1817
|
const changed = changes.flatMap((edit, index) => edit.sign === " " ? [] : [index]);
|
|
1326
|
-
const
|
|
1818
|
+
const quotePath = (path) => /[\s"\\]/.test(path) ? JSON.stringify(path) : path;
|
|
1819
|
+
const output = [`--- ${quotePath(`a/${file}`)}`, `+++ ${quotePath(`b/${file}`)}`];
|
|
1327
1820
|
for (let i = 0; i < changed.length; i++) {
|
|
1328
1821
|
const start = Math.max(0, changed[i] - 3);
|
|
1329
1822
|
let last = changed[i];
|
|
@@ -1337,19 +1830,42 @@ var unifiedDiff = (original, modified, file) => {
|
|
|
1337
1830
|
return [...output, ""].join("\n");
|
|
1338
1831
|
};
|
|
1339
1832
|
|
|
1833
|
+
// packages/cli/src/Summary.ts
|
|
1834
|
+
var outcomeNames = ["caught", "missed", "timeout", "unviable", "untested", "unreliable"];
|
|
1835
|
+
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((result2) => result2.outcome === outcome).length} ${outcome}`).join(", ") + `; ${notMutated} not mutated`;
|
|
1836
|
+
var cell = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\\", "\\\\").replaceAll("|", "\\|").replaceAll("`", "`").replace(/[\r\n]+/g, " ");
|
|
1837
|
+
var markdownSummary = (options) => {
|
|
1838
|
+
const { report, path } = options;
|
|
1839
|
+
const rows = report.results.filter((result2) => result2.outcome === "missed" || result2.outcome === "timeout" || result2.outcome === "untested" || result2.outcome === "unreliable");
|
|
1840
|
+
const exit = report.failure?.startsWith("BaselineFailed") ? 4 : reportExitCode(report);
|
|
1841
|
+
return [
|
|
1842
|
+
options.marker,
|
|
1843
|
+
countsLine(report, options.notMutated),
|
|
1844
|
+
"",
|
|
1845
|
+
...report.failure === void 0 ? [] : [`Failure: ${cell(report.failure)}`, ""],
|
|
1846
|
+
options.advisory ? `Advisory: would exit ${exit} without --advisory.` : `Exit code: ${exit}.`,
|
|
1847
|
+
"",
|
|
1848
|
+
"| File:line | Function | Description | Outcome |",
|
|
1849
|
+
"| --- | --- | --- | --- |",
|
|
1850
|
+
...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
|
+
...rows.length > 50 ? ["", `and ${rows.length - 50} more`] : [],
|
|
1852
|
+
""
|
|
1853
|
+
].join("\n");
|
|
1854
|
+
};
|
|
1855
|
+
|
|
1340
1856
|
// packages/cli/src/Reporter.ts
|
|
1341
1857
|
var mutantLine = (mutant, root, path) => `${path.relative(root, path.resolve(root, mutant.file))}:${mutant.span.start.line}:${mutant.span.start.column}: ${mutant.description.replace(mutant.returnType, shortType(mutant.displayReturnType ?? mutant.returnType))} [${mutant.id}]`;
|
|
1342
1858
|
var shortType = (text) => {
|
|
1343
1859
|
const line = text.replace(/\s+/g, " ");
|
|
1344
1860
|
return line.length > 80 ? line.slice(0, 79) + "\u2026" : line;
|
|
1345
1861
|
};
|
|
1346
|
-
var outcomes = ["caught", "missed", "timeout", "unviable", "untested"];
|
|
1347
|
-
var jsonReport =
|
|
1862
|
+
var outcomes = ["caught", "missed", "timeout", "unviable", "untested", "unreliable"];
|
|
1863
|
+
var jsonReport = Schema9.encodeEffect(Schema9.fromJsonString(RunReport));
|
|
1348
1864
|
var logText = (result2) => [
|
|
1349
1865
|
..."output" in result2 && typeof result2.output === "string" ? [result2.output] : [],
|
|
1350
1866
|
...result2.diagnostics
|
|
1351
1867
|
].join("\n");
|
|
1352
|
-
var makeReporter =
|
|
1868
|
+
var makeReporter = Effect7.fn("makeReporter")(function* (options) {
|
|
1353
1869
|
const fs = yield* FileSystem7.FileSystem;
|
|
1354
1870
|
const path = yield* Path9.Path;
|
|
1355
1871
|
const dir = path.resolve(options.root, options.outDir);
|
|
@@ -1358,13 +1874,13 @@ var makeReporter = Effect6.fn("makeReporter")(function* (options) {
|
|
|
1358
1874
|
const results = [];
|
|
1359
1875
|
let pendingError;
|
|
1360
1876
|
let summarized = false;
|
|
1361
|
-
const writeError = (
|
|
1877
|
+
const writeError = (error3) => new ReportWriteError({ path: dir, message: String(error3) });
|
|
1362
1878
|
const ids = /* @__PURE__ */ new Set();
|
|
1363
1879
|
for (const mutant of options.mutants) {
|
|
1364
1880
|
if (!/^[A-Za-z0-9_-]+$/.test(mutant.id) || ids.has(mutant.id)) return yield* writeError("Mutant ids must be unique safe filenames");
|
|
1365
1881
|
ids.add(mutant.id);
|
|
1366
1882
|
}
|
|
1367
|
-
yield*
|
|
1883
|
+
yield* Effect7.gen(function* () {
|
|
1368
1884
|
const relative2 = path.relative(dir, path.resolve(options.root));
|
|
1369
1885
|
if (relative2 === "" || relative2 !== ".." && !relative2.startsWith(`..${path.sep}`) && !path.isAbsolute(relative2)) {
|
|
1370
1886
|
return yield* new ReportWriteError({ path: dir, message: "Output cannot be the project root or an ancestor" });
|
|
@@ -1379,81 +1895,147 @@ var makeReporter = Effect6.fn("makeReporter")(function* (options) {
|
|
|
1379
1895
|
}
|
|
1380
1896
|
yield* fs.makeDirectory(path.join(dir, "diff"), { recursive: true });
|
|
1381
1897
|
yield* fs.makeDirectory(path.join(dir, "logs"), { recursive: true });
|
|
1382
|
-
}).pipe(
|
|
1383
|
-
const encodedMutants = yield*
|
|
1384
|
-
yield* fs.writeFileString(path.join(dir, "mutants.json"), encodedMutants).pipe(
|
|
1385
|
-
yield*
|
|
1898
|
+
}).pipe(Effect7.mapError(writeError));
|
|
1899
|
+
const encodedMutants = yield* Schema9.encodeEffect(Schema9.fromJsonString(Schema9.Array(Mutant)))(options.mutants).pipe(Effect7.mapError(writeError));
|
|
1900
|
+
yield* fs.writeFileString(path.join(dir, "mutants.json"), encodedMutants).pipe(Effect7.mapError(writeError));
|
|
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(Effect7.mapError(writeError));
|
|
1903
|
+
yield* Effect7.forEach(outcomes, (outcome) => fs.writeFileString(path.join(dir, `${outcome}.txt`), ""), { discard: true }).pipe(Effect7.mapError(writeError));
|
|
1386
1904
|
for (const mutant of options.mutants) {
|
|
1387
|
-
const original = yield* fs.readFileString(path.resolve(options.root, mutant.file)).pipe(
|
|
1388
|
-
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(
|
|
1905
|
+
const original = yield* fs.readFileString(path.resolve(options.root, mutant.file)).pipe(Effect7.mapError(writeError));
|
|
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(Effect7.mapError(writeError));
|
|
1389
1907
|
}
|
|
1390
|
-
const writeLists = (items) =>
|
|
1908
|
+
const writeLists = (items) => Effect7.forEach(outcomes, (outcome) => {
|
|
1391
1909
|
const lines2 = items.filter((result2) => result2.outcome === outcome).map((result2) => mutantLine(result2.mutant, options.root, path));
|
|
1392
1910
|
return fs.writeFileString(path.join(dir, `${outcome}.txt`), lines2.length === 0 ? "" : lines2.join("\n") + "\n");
|
|
1393
1911
|
}, { discard: true });
|
|
1394
1912
|
const service = Reporter.of({
|
|
1395
|
-
progress: (result2) => semaphore.withPermit(
|
|
1913
|
+
progress: (result2) => semaphore.withPermit(Effect7.gen(function* () {
|
|
1396
1914
|
results.push(result2);
|
|
1397
|
-
yield*
|
|
1398
|
-
yield*
|
|
1915
|
+
if (!options.markdown?.stdout) yield* Console2.log(`${result2.outcome} ${mutantLine(result2.mutant, options.root, path)} (${result2.durationMs}ms)`);
|
|
1916
|
+
yield* Effect7.gen(function* () {
|
|
1399
1917
|
if (!ids.has(result2.mutant.id)) return yield* writeError("Progress result does not belong to this report");
|
|
1400
1918
|
yield* writeLists(results);
|
|
1401
1919
|
yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2));
|
|
1402
|
-
}).pipe(
|
|
1920
|
+
}).pipe(Effect7.catch((error3) => Effect7.gen(function* () {
|
|
1403
1921
|
if (pendingError === void 0) {
|
|
1404
|
-
pendingError = writeError(
|
|
1405
|
-
yield*
|
|
1922
|
+
pendingError = writeError(error3);
|
|
1923
|
+
yield* Console2.warn(`Report write failed: ${pendingError.message}`);
|
|
1406
1924
|
}
|
|
1407
1925
|
})));
|
|
1408
1926
|
})),
|
|
1409
|
-
write: (report) => semaphore.withPermit(
|
|
1927
|
+
write: (report) => semaphore.withPermit(Effect7.gen(function* () {
|
|
1410
1928
|
if (pendingError !== void 0) return yield* pendingError;
|
|
1411
|
-
const
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1929
|
+
const counted = {
|
|
1930
|
+
...report,
|
|
1931
|
+
selected: options.selected ?? options.mutants.length,
|
|
1932
|
+
run: report.results.length,
|
|
1933
|
+
budgetSkipped: options.budgetSkipped ?? 0
|
|
1934
|
+
};
|
|
1935
|
+
const encoded = yield* jsonReport(counted).pipe(Effect7.mapError(writeError));
|
|
1936
|
+
yield* fs.writeFileString(path.join(dir, "outcomes.json.tmp"), encoded).pipe(Effect7.mapError(writeError));
|
|
1937
|
+
yield* fs.rename(path.join(dir, "outcomes.json.tmp"), path.join(dir, "outcomes.json")).pipe(Effect7.mapError(writeError));
|
|
1938
|
+
yield* writeLists(report.results).pipe(Effect7.mapError(writeError));
|
|
1415
1939
|
for (const result2 of report.results) {
|
|
1416
1940
|
if (!ids.has(result2.mutant.id)) return yield* writeError("Final result does not belong to this report");
|
|
1417
|
-
yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2)).pipe(
|
|
1941
|
+
yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2)).pipe(Effect7.mapError(writeError));
|
|
1942
|
+
}
|
|
1943
|
+
if (options.markdown !== void 0) {
|
|
1944
|
+
const markdown = markdownSummary({ ...options.markdown, root: options.root, path, report: counted, notMutated: options.notMutated?.length ?? 0 });
|
|
1945
|
+
for (const file of new Set(options.markdown.files)) {
|
|
1946
|
+
yield* fs.writeFileString(file, markdown).pipe(Effect7.mapError((error3) => new ReportWriteError({ path: file, message: String(error3) })));
|
|
1947
|
+
}
|
|
1948
|
+
if (!summarized && options.markdown.stdout) yield* Console2.log(markdown);
|
|
1418
1949
|
}
|
|
1419
1950
|
if (summarized) return;
|
|
1420
1951
|
summarized = true;
|
|
1952
|
+
if (report.results.some((result2) => result2.outcome === "unreliable")) yield* Console2.warn("Unreliable: the configured Vitest run cannot see all tests. See unreliable.txt and per-mutant diagnostics; these are not missed mutants.");
|
|
1421
1953
|
const elapsed = (yield* Clock2.currentTimeMillis) - started;
|
|
1422
|
-
|
|
1954
|
+
if (!options.markdown?.stdout) yield* Console2.log(countsLine(counted, options.notMutated?.length ?? 0) + `; ${(elapsed / 1e3).toFixed(2)}s`);
|
|
1955
|
+
if (options.markdown === void 0 && report.failure !== void 0) yield* Console2.warn(report.failure);
|
|
1423
1956
|
}))
|
|
1424
1957
|
});
|
|
1425
1958
|
return service;
|
|
1426
1959
|
});
|
|
1427
1960
|
|
|
1428
|
-
// packages/cli/src/
|
|
1429
|
-
|
|
1961
|
+
// packages/cli/src/Git.ts
|
|
1962
|
+
import * as Effect8 from "effect/Effect";
|
|
1963
|
+
import * as FileSystem9 from "effect/FileSystem";
|
|
1964
|
+
import * as Path11 from "effect/Path";
|
|
1965
|
+
import * as Schema10 from "effect/Schema";
|
|
1966
|
+
import * as Stream5 from "effect/Stream";
|
|
1967
|
+
import * as ChildProcess4 from "effect/process/ChildProcess";
|
|
1968
|
+
var UsageError = class extends Schema10.TaggedError()("UsageError", { message: Schema10.String }) {
|
|
1430
1969
|
};
|
|
1970
|
+
var git = Effect8.fn("git")(function* (root, args) {
|
|
1971
|
+
const command = `git ${args.join(" ")}`;
|
|
1972
|
+
return yield* Effect8.scoped(Effect8.gen(function* () {
|
|
1973
|
+
const handle = yield* ChildProcess4.make("git", args, { cwd: root });
|
|
1974
|
+
const [stdout, stderr, code] = yield* Effect8.all([
|
|
1975
|
+
Stream5.mkString(Stream5.decodeText(handle.stdout)),
|
|
1976
|
+
Stream5.mkString(Stream5.decodeText(handle.stderr)),
|
|
1977
|
+
handle.exitCode
|
|
1978
|
+
], { concurrency: "unbounded" });
|
|
1979
|
+
if (Number(code) !== 0) return yield* new UsageError({ message: `${command}:
|
|
1980
|
+
${stderr}` });
|
|
1981
|
+
return stdout;
|
|
1982
|
+
})).pipe(Effect8.mapError((error3) => error3._tag === "UsageError" ? error3 : new UsageError({ message: `${command}: ${String(error3)}` })));
|
|
1983
|
+
});
|
|
1984
|
+
var repositoryRoot = Effect8.fn("repositoryRoot")(function* (root) {
|
|
1985
|
+
const path = yield* Path11.Path;
|
|
1986
|
+
const fs = yield* FileSystem9.FileSystem;
|
|
1987
|
+
const top = (yield* git(root, ["rev-parse", "--show-toplevel"])).trim();
|
|
1988
|
+
const physical = yield* fs.realPath(root).pipe(Effect8.mapError((error3) => new UsageError({ message: String(error3) })));
|
|
1989
|
+
return path.resolve(root, path.relative(physical, top));
|
|
1990
|
+
});
|
|
1991
|
+
|
|
1992
|
+
// packages/cli/src/Command.ts
|
|
1431
1993
|
var flags = {
|
|
1432
|
-
list: Flag.Boolean("list").pipe(Flag.withDefault(false)),
|
|
1433
|
-
inDiff: Flag.String("in-diff").pipe(Flag.optional),
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1994
|
+
list: Flag.Boolean("list").pipe(Flag.withDefault(false), Flag.withDescription("List mutants and skipped function count without running tests")),
|
|
1995
|
+
inDiff: Flag.String("in-diff").pipe(Flag.optional, Flag.withDescription("Only mutate bodies overlapping this unified diff")),
|
|
1996
|
+
inDiffRange: Flag.String("in-diff-range").pipe(Flag.optional, Flag.withDescription("Only mutate bodies overlapping git diff A...B or A..B; exclusive with --in-diff")),
|
|
1997
|
+
maxMutants: Flag.Int("max-mutants").pipe(Flag.optional, Flag.withDescription("Keep first N selected mutants ordered by repository path, line, column, id; N >= 0")),
|
|
1998
|
+
format: Flag.String("format").pipe(Flag.withDefault("text"), Flag.withDescription("Output format: text (default), json (--list only), or github (Markdown and GITHUB_STEP_SUMMARY)")),
|
|
1999
|
+
summaryMd: Flag.String("summary-md").pipe(Flag.optional, Flag.withDescription("Write Markdown summary to this file")),
|
|
2000
|
+
summaryMarker: Flag.String("summary-marker").pipe(Flag.withDefault("<!-- mutant.cafe -->"), Flag.withDescription("Override the first-line sticky-comment marker")),
|
|
2001
|
+
advisory: Flag.Boolean("advisory").pipe(Flag.withDefault(false), Flag.withDescription("Exit 0 for outcomes and baseline failure; keep usage/internal errors")),
|
|
2002
|
+
include: Flag.String("file").pipe(Flag.atLeast(0), Flag.withDescription("Include source glob relative to package root; repeatable")),
|
|
2003
|
+
exclude: Flag.String("exclude").pipe(Flag.atLeast(0), Flag.withDescription("Exclude source glob; repeatable")),
|
|
2004
|
+
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")),
|
|
2005
|
+
jobs: Flag.Int("jobs").pipe(Flag.optional, Flag.withDescription("Concurrent scratch/test workers; default 1")),
|
|
1437
2006
|
timeout: Flag.Finite("timeout").pipe(Flag.optional, Flag.withDescription("Absolute test timeout in seconds")),
|
|
1438
|
-
timeoutMultiplier: Flag.Finite("timeout-multiplier").pipe(Flag.optional),
|
|
2007
|
+
timeoutMultiplier: Flag.Finite("timeout-multiplier").pipe(Flag.optional, Flag.withDescription("Baseline duration multiplier; default 5")),
|
|
1439
2008
|
minimumTimeout: Flag.Finite("minimum-test-timeout").pipe(Flag.optional, Flag.withDescription("Minimum test timeout in seconds")),
|
|
1440
|
-
output: Flag.String("output").pipe(Flag.withDefault("mutants.out")),
|
|
1441
|
-
tsconfig: Flag.String("tsconfig").pipe(Flag.withDefault("tsconfig.json"))
|
|
2009
|
+
output: Flag.String("output").pipe(Flag.withDefault("mutants.out"), Flag.withDescription("Report directory; default mutants.out")),
|
|
2010
|
+
tsconfig: Flag.String("tsconfig").pipe(Flag.withDefault("tsconfig.json"), Flag.withDescription("TypeScript project path; default tsconfig.json"))
|
|
1442
2011
|
};
|
|
1443
|
-
var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) =>
|
|
1444
|
-
const fs = yield*
|
|
1445
|
-
const path = yield*
|
|
2012
|
+
var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Effect9.gen(function* () {
|
|
2013
|
+
const fs = yield* FileSystem11.FileSystem;
|
|
2014
|
+
const path = yield* Path13.Path;
|
|
1446
2015
|
const root = path.resolve(options.root);
|
|
2016
|
+
const range = Option.getOrUndefined(input.inDiffRange);
|
|
2017
|
+
const inDiff = Option.getOrUndefined(input.inDiff);
|
|
2018
|
+
const maxMutants = Option.getOrUndefined(input.maxMutants);
|
|
2019
|
+
const summaryMd = Option.getOrUndefined(input.summaryMd);
|
|
2020
|
+
if (range !== void 0 && inDiff !== void 0) return yield* new UsageError({ message: "--in-diff-range and --in-diff are mutually exclusive" });
|
|
2021
|
+
if (range !== void 0 && (!/^[^\s.][^\s]*\.{2,3}[^\s.][^\s]*$/.test(range) || range.startsWith("-") || range.includes("...."))) {
|
|
2022
|
+
return yield* new UsageError({ message: "--in-diff-range expects A...B or A..B" });
|
|
2023
|
+
}
|
|
2024
|
+
if (maxMutants !== void 0 && (!Number.isSafeInteger(maxMutants) || maxMutants < 0)) return yield* new UsageError({ message: "--max-mutants must be a nonnegative safe integer" });
|
|
2025
|
+
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
|
+
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(Effect9.catch(() => Effect9.succeed(root)));
|
|
2028
|
+
const diffText = range === void 0 ? void 0 : yield* git(gitRoot, ["diff", "--no-ext-diff", "--no-color", range, "--"]);
|
|
1447
2029
|
const configPath = path.join(root, "mutants.config.json");
|
|
1448
2030
|
const fileConfig = (yield* fs.exists(configPath)) ? yield* fs.readFileString(configPath).pipe(
|
|
1449
|
-
|
|
1450
|
-
|
|
2031
|
+
Effect9.flatMap(Schema11.decodeEffect(Schema11.fromJsonString(ConfigFile))),
|
|
2032
|
+
Effect9.mapError((error3) => new UsageError({ message: `Invalid mutants.config.json: ${String(error3)}` }))
|
|
1451
2033
|
) : {};
|
|
1452
2034
|
const timeoutMs = Option.map(input.timeout, (seconds) => Math.ceil(seconds * 1e3));
|
|
1453
|
-
const
|
|
1454
|
-
const config = yield* Schema8.decodeEffect(RunConfig)({
|
|
2035
|
+
const config = yield* Schema11.decodeEffect(RunConfig)({
|
|
1455
2036
|
root,
|
|
1456
2037
|
tsconfig: input.tsconfig,
|
|
2038
|
+
exportedOnly: input.exportedOnly,
|
|
1457
2039
|
include: input.include.length > 0 ? input.include : fileConfig.include ?? ["**/*.{ts,tsx}"],
|
|
1458
2040
|
exclude: input.exclude.length > 0 ? input.exclude : fileConfig.exclude ?? [],
|
|
1459
2041
|
functionFilter: fileConfig.functionFilter ?? [],
|
|
@@ -1464,42 +2046,102 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
1464
2046
|
minimumTimeoutMs: Option.match(input.minimumTimeout, { onNone: () => fileConfig.minimumTimeoutMs ?? 2e4, onSome: (seconds) => Math.ceil(seconds * 1e3) }),
|
|
1465
2047
|
neverTimeoutMs: 1e3,
|
|
1466
2048
|
outDir: input.output
|
|
1467
|
-
}).pipe(
|
|
2049
|
+
}).pipe(Effect9.mapError((error3) => new UsageError({ message: String(error3) })));
|
|
1468
2050
|
if (config.jobs < 1 || config.timeoutMultiplier <= 0 || config.minimumTimeoutMs <= 0 || config.timeoutMs !== void 0 && config.timeoutMs <= 0) {
|
|
1469
2051
|
return yield* new UsageError({ message: "Jobs and timeout values must be positive" });
|
|
1470
2052
|
}
|
|
1471
2053
|
const source = yield* MutantSource;
|
|
1472
|
-
const generated = yield*
|
|
1473
|
-
|
|
2054
|
+
const generated = yield* Stream6.runCollect(source.generate(config)).pipe(
|
|
2055
|
+
Effect9.mapError((error3) => error3.reason === "selection" ? new UsageError({ message: error3.diagnostics.join("\n") }) : error3)
|
|
1474
2056
|
);
|
|
1475
|
-
const
|
|
2057
|
+
const skipped2 = yield* source.notMutated(config);
|
|
2058
|
+
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 });
|
|
2059
|
+
const relative2 = (mutant) => path.relative(gitRoot, path.resolve(root, mutant.file)).replaceAll("\\", "/");
|
|
2060
|
+
const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
2061
|
+
const ordered = [...selected.mutants].sort((a, b) => compare(relative2(a), relative2(b)) || a.span.start.line - b.span.start.line || a.span.start.column - b.span.start.column || compare(a.id, b.id));
|
|
2062
|
+
const mutants = ordered.slice(0, maxMutants);
|
|
2063
|
+
const notMutated = selected.notMutated;
|
|
2064
|
+
const counts = { selected: ordered.length, run: 0, budgetSkipped: ordered.length - mutants.length };
|
|
2065
|
+
const markdown = input.format === "github" || summaryMd !== void 0 ? {
|
|
2066
|
+
gitRoot,
|
|
2067
|
+
marker: input.summaryMarker,
|
|
2068
|
+
advisory: input.advisory,
|
|
2069
|
+
stdout: input.format === "github",
|
|
2070
|
+
files: [
|
|
2071
|
+
...summaryMd === void 0 ? [] : [path.resolve(root, summaryMd)],
|
|
2072
|
+
...input.format === "github" && process.env.GITHUB_STEP_SUMMARY ? [process.env.GITHUB_STEP_SUMMARY] : []
|
|
2073
|
+
]
|
|
2074
|
+
} : void 0;
|
|
2075
|
+
if (input.list && markdown !== void 0) {
|
|
2076
|
+
const text = markdownSummary({
|
|
2077
|
+
...markdown,
|
|
2078
|
+
root,
|
|
2079
|
+
path,
|
|
2080
|
+
notMutated: notMutated.length,
|
|
2081
|
+
report: { schemaVersion: 2, tool: "mutant.cafe", root, baseline: { durationMs: 0, testCommand: [] }, timeoutMs: 0, results: [], ...counts }
|
|
2082
|
+
});
|
|
2083
|
+
for (const file of new Set(markdown.files)) yield* fs.writeFileString(file, text).pipe(
|
|
2084
|
+
Effect9.mapError((error3) => new ReportWriteError({ path: file, message: String(error3) }))
|
|
2085
|
+
);
|
|
2086
|
+
if (markdown.stdout) {
|
|
2087
|
+
yield* Console3.log(text);
|
|
2088
|
+
if (options.onExit !== void 0) yield* options.onExit(0);
|
|
2089
|
+
return;
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
if (input.list && input.format === "json") {
|
|
2093
|
+
yield* Console3.log(yield* Schema11.encodeEffect(Schema11.fromJsonString(MutantList))({ schemaVersion: 2, tool: "mutant.cafe", mutants, notMutated, counts }));
|
|
2094
|
+
if (options.onExit !== void 0) yield* options.onExit(0);
|
|
2095
|
+
return;
|
|
2096
|
+
}
|
|
1476
2097
|
if (input.list) {
|
|
1477
|
-
for (const mutant of mutants) yield*
|
|
1478
|
-
const
|
|
2098
|
+
for (const mutant of mutants) yield* Console3.log(mutantLine(mutant, config.root, path));
|
|
2099
|
+
const perFile = /* @__PURE__ */ new Map();
|
|
1479
2100
|
for (const mutant of mutants) {
|
|
1480
2101
|
const file = path.relative(root, path.resolve(root, mutant.file));
|
|
1481
|
-
|
|
2102
|
+
perFile.set(file, (perFile.get(file) ?? 0) + 1);
|
|
1482
2103
|
}
|
|
1483
|
-
for (const [file, count] of [...
|
|
1484
|
-
yield*
|
|
2104
|
+
for (const [file, count] of [...perFile].sort(([a], [b]) => a.localeCompare(b))) yield* Console3.log(`${file}: ${count} mutants`);
|
|
2105
|
+
yield* Console3.log(`${mutants.length} mutants total; ${notMutated.length} not mutated; ${counts.selected} selected, 0 run, ${counts.budgetSkipped} budget-skipped`);
|
|
1485
2106
|
if (options.onExit !== void 0) yield* options.onExit(0);
|
|
1486
2107
|
return;
|
|
1487
2108
|
}
|
|
1488
|
-
const reporter = yield* makeReporter({ root, outDir: config.outDir, mutants });
|
|
1489
|
-
const report = yield* options.run(config, mutants).pipe(
|
|
2109
|
+
const reporter = yield* makeReporter({ root, outDir: config.outDir, mutants, notMutated, selected: counts.selected, budgetSkipped: counts.budgetSkipped, ...markdown === void 0 ? {} : { markdown } });
|
|
2110
|
+
const report = yield* options.run(config, mutants).pipe(
|
|
2111
|
+
Effect9.provideService(Reporter, reporter),
|
|
2112
|
+
Effect9.catchTag("BaselineFailed", (error3) => Effect9.gen(function* () {
|
|
2113
|
+
const failed = {
|
|
2114
|
+
schemaVersion: 2,
|
|
2115
|
+
tool: "mutant.cafe",
|
|
2116
|
+
root,
|
|
2117
|
+
baseline: { durationMs: 0, testCommand: error3.command },
|
|
2118
|
+
timeoutMs: config.timeoutMs ?? config.minimumTimeoutMs,
|
|
2119
|
+
results: [],
|
|
2120
|
+
failure: `BaselineFailed: ${error3.command.join(" ")}
|
|
2121
|
+
${error3.output.slice(-8e3)}`
|
|
2122
|
+
};
|
|
2123
|
+
yield* reporter.write(failed);
|
|
2124
|
+
if (!input.advisory) return yield* error3;
|
|
2125
|
+
if (markdown === void 0) yield* Console3.log("Advisory: baseline failed; would exit 4 without --advisory.");
|
|
2126
|
+
return failed;
|
|
2127
|
+
}))
|
|
2128
|
+
);
|
|
2129
|
+
if (input.advisory && reportExitCode(report) !== 0 && markdown === void 0) yield* Console3.log(`Advisory: would exit ${reportExitCode(report)} without --advisory.`);
|
|
1490
2130
|
yield* reporter.write(report);
|
|
1491
|
-
if (options.onExit !== void 0) yield* options.onExit(reportExitCode(report));
|
|
2131
|
+
if (options.onExit !== void 0) yield* options.onExit(input.advisory ? 0 : reportExitCode(report));
|
|
1492
2132
|
}));
|
|
1493
|
-
var runCli =
|
|
2133
|
+
var runCli = Effect9.fn("runCli")(function* (options) {
|
|
1494
2134
|
const code = yield* Ref.make(0);
|
|
1495
2135
|
const command = makeCommand({ ...options, onExit: (value) => Ref.set(code, value) });
|
|
1496
|
-
yield* Command.runWith(command, { version: "0.1.
|
|
1497
|
-
|
|
1498
|
-
yield*
|
|
1499
|
-
|
|
2136
|
+
yield* Command.runWith(command, { version: "0.1.4" })(options.args).pipe(
|
|
2137
|
+
Effect9.catch((error3) => Effect9.gen(function* () {
|
|
2138
|
+
yield* Console3.error(error3._tag === "ProgramLoadError" ? `${error3.tsconfig}:
|
|
2139
|
+
${error3.diagnostics.join("\n")}` : error3._tag === "BaselineFailed" ? `Baseline failed (${error3.exitCode}): ${error3.command.join(" ")}
|
|
2140
|
+
${error3.output.slice(-8e3)}` : String(error3));
|
|
2141
|
+
yield* Ref.set(code, errorExitCode(error3));
|
|
1500
2142
|
})),
|
|
1501
|
-
|
|
1502
|
-
yield*
|
|
2143
|
+
Effect9.catchDefect((defect) => Effect9.gen(function* () {
|
|
2144
|
+
yield* Console3.error(`Internal error: ${String(defect)}`);
|
|
1503
2145
|
yield* Ref.set(code, 70);
|
|
1504
2146
|
}))
|
|
1505
2147
|
);
|
|
@@ -1507,15 +2149,15 @@ var runCli = Effect7.fn("runCli")(function* (options) {
|
|
|
1507
2149
|
});
|
|
1508
2150
|
|
|
1509
2151
|
// packages/cli/src/bin.ts
|
|
1510
|
-
var run = (config, mutants) => runMutants(config,
|
|
2152
|
+
var run = (config, mutants) => runMutants(config, Stream7.fromIterable(mutants));
|
|
1511
2153
|
var live = Layer5.mergeAll(MutantSourceLive, ScratchLive, TestRunnerLive).pipe(
|
|
1512
2154
|
Layer5.provideMerge(NodeServices.layer)
|
|
1513
2155
|
);
|
|
1514
|
-
var main =
|
|
2156
|
+
var main = Effect10.gen(function* () {
|
|
1515
2157
|
const code = yield* runCli({ root: process.cwd(), args: process.argv.slice(2), run });
|
|
1516
|
-
yield*
|
|
2158
|
+
yield* Effect10.sync(() => {
|
|
1517
2159
|
process.exitCode = code;
|
|
1518
2160
|
});
|
|
1519
|
-
}).pipe(
|
|
2161
|
+
}).pipe(Effect10.provide(live));
|
|
1520
2162
|
NodeRuntime.runMain(main);
|
|
1521
2163
|
//# sourceMappingURL=bin.js.map
|