mutant-cafe 0.1.1 → 0.1.3
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 +50 -9
- package/dist/bin.js +1027 -291
- 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,
|
|
@@ -33,11 +34,13 @@ var ConfigFile = Schema.Struct({
|
|
|
33
34
|
import * as Schema2 from "effect/Schema";
|
|
34
35
|
var ProgramLoadError = class extends Schema2.TaggedError()("ProgramLoadError", {
|
|
35
36
|
tsconfig: Schema2.String,
|
|
37
|
+
reason: Schema2.optional(Schema2.Literal("selection")),
|
|
36
38
|
diagnostics: Schema2.Array(Schema2.String)
|
|
37
39
|
}) {
|
|
38
40
|
};
|
|
39
41
|
var BaselineFailed = class extends Schema2.TaggedError()("BaselineFailed", {
|
|
40
42
|
exitCode: Schema2.Int,
|
|
43
|
+
command: Schema2.Array(Schema2.String),
|
|
41
44
|
output: Schema2.String
|
|
42
45
|
}) {
|
|
43
46
|
};
|
|
@@ -69,6 +72,7 @@ var Genre = Schema3.Literals([
|
|
|
69
72
|
"EffectSucceed",
|
|
70
73
|
"EffectFail",
|
|
71
74
|
"SwallowTag",
|
|
75
|
+
"TagToDefect",
|
|
72
76
|
"EffectDie",
|
|
73
77
|
"EffectNever",
|
|
74
78
|
"OptionNone",
|
|
@@ -77,6 +81,7 @@ var Genre = Schema3.Literals([
|
|
|
77
81
|
"StreamOne",
|
|
78
82
|
"StreamFail",
|
|
79
83
|
"LayerFail",
|
|
84
|
+
"LayerDie",
|
|
80
85
|
"SchemaAcceptAnything",
|
|
81
86
|
"BooleanFlip",
|
|
82
87
|
"LiteralCycle",
|
|
@@ -96,13 +101,14 @@ var Mutant = Schema3.Struct({
|
|
|
96
101
|
file: Schema3.String,
|
|
97
102
|
functionName: Schema3.String,
|
|
98
103
|
returnType: Schema3.String,
|
|
104
|
+
displayReturnType: Schema3.optional(Schema3.String),
|
|
99
105
|
genre: Genre,
|
|
100
106
|
description: Schema3.String,
|
|
101
107
|
span: Span,
|
|
102
108
|
replacement: Replacement,
|
|
103
109
|
synthetic: Schema3.Boolean
|
|
104
110
|
});
|
|
105
|
-
var Outcome = Schema3.Literals(["caught", "missed", "unviable", "timeout"]);
|
|
111
|
+
var Outcome = Schema3.Literals(["caught", "missed", "unviable", "timeout", "untested", "unreliable"]);
|
|
106
112
|
var MutantResult = Schema3.Struct({
|
|
107
113
|
mutant: Mutant,
|
|
108
114
|
outcome: Outcome,
|
|
@@ -111,17 +117,30 @@ var MutantResult = Schema3.Struct({
|
|
|
111
117
|
diagnostics: Schema3.Array(Schema3.String),
|
|
112
118
|
output: Schema3.optional(Schema3.String)
|
|
113
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
|
+
]);
|
|
114
126
|
var Baseline = Schema3.Struct({
|
|
115
127
|
durationMs: Schema3.Int,
|
|
116
|
-
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
|
|
117
135
|
});
|
|
118
136
|
var RunReport = Schema3.Struct({
|
|
119
|
-
schemaVersion: Schema3.Literal(
|
|
137
|
+
schemaVersion: Schema3.Literal(2),
|
|
120
138
|
tool: Schema3.Literal("mutant.cafe"),
|
|
121
139
|
root: Schema3.String,
|
|
122
140
|
baseline: Baseline,
|
|
123
141
|
timeoutMs: Schema3.Int,
|
|
124
|
-
results: Schema3.Array(MutantResult)
|
|
142
|
+
results: Schema3.Array(MutantResult),
|
|
143
|
+
failure: Schema3.optional(Schema3.String)
|
|
125
144
|
});
|
|
126
145
|
|
|
127
146
|
// packages/core/src/Services.ts
|
|
@@ -143,30 +162,33 @@ import * as Schema4 from "effect/Schema";
|
|
|
143
162
|
|
|
144
163
|
// packages/engine/src/Generate.ts
|
|
145
164
|
import { createHash } from "node:crypto";
|
|
146
|
-
function* generateFunction(
|
|
147
|
-
const api =
|
|
165
|
+
function* generateFunction(fn8) {
|
|
166
|
+
const api = fn8.api;
|
|
148
167
|
const candidate = (genre, expression, value = { text: "", synthetic: false }, description = expression) => {
|
|
149
|
-
const
|
|
150
|
-
|
|
168
|
+
const pinned = `((): ${fn8.returnType} => (${expression}))()`;
|
|
169
|
+
const text = fn8.block ? `{ return ${fn8.generator ? "yield* " : ""}${pinned}; }` : `(${pinned})`;
|
|
170
|
+
return makeMutant(fn8, genre, text, value.synthetic, description);
|
|
151
171
|
};
|
|
152
|
-
const shape =
|
|
172
|
+
const shape = fn8.shape;
|
|
153
173
|
switch (shape.kind) {
|
|
154
174
|
case "Effect": {
|
|
155
|
-
const
|
|
156
|
-
if (
|
|
157
|
-
for (const value of shape.values)
|
|
175
|
+
const succeed3 = api("Effect", "succeed");
|
|
176
|
+
if (succeed3) {
|
|
177
|
+
for (const value of shape.values) {
|
|
178
|
+
if (!fn8.equivalentValues.includes(value.text)) yield candidate("EffectSucceed", `${succeed3}(${value.text})`, value);
|
|
179
|
+
}
|
|
158
180
|
}
|
|
159
|
-
const
|
|
181
|
+
const fail3 = api("Effect", "fail");
|
|
160
182
|
const catchTag2 = api("Effect", "catchTag");
|
|
161
183
|
for (const error2 of shape.errors) {
|
|
162
|
-
if (
|
|
184
|
+
if (fail3) yield candidate("EffectFail", `${fail3}(${error2.text})`, error2, `${fail3}(${error2.text}) [${error2.synthetic ? "synthetic tag cast" : "constructed error"}]`);
|
|
163
185
|
const value = shape.values[0];
|
|
164
186
|
const die3 = api("Effect", "die");
|
|
165
|
-
const recovery = value &&
|
|
187
|
+
const recovery = value && succeed3 ? `${succeed3}(${value.text})` : die3 ? `${die3}(${JSON.stringify(`mutant.cafe: swallowed ${error2.tag}`)})` : void 0;
|
|
166
188
|
if (catchTag2 && recovery) {
|
|
167
|
-
const
|
|
168
|
-
const original =
|
|
169
|
-
if (original) yield candidate("SwallowTag", `${original}.pipe(${catchTag2}(${JSON.stringify(error2.tag)}, () => ${recovery}))`, value, `body.pipe(${catchTag2}(${JSON.stringify(error2.tag)}, () => ${recovery}))`);
|
|
189
|
+
const gen8 = api("Effect", "gen");
|
|
190
|
+
const original = fn8.generator ? gen8 && `((): ${fn8.returnType} => ${gen8}(function* () ${fn8.original}))()` : fn8.block ? `((): ${fn8.returnType} => ${fn8.original})()` : `((): ${fn8.returnType} => (${fn8.original}))()`;
|
|
191
|
+
if (original) yield candidate(value ? "SwallowTag" : "TagToDefect", `${original}.pipe(${catchTag2}(${JSON.stringify(error2.tag)}, () => ${recovery}))`, value, value ? `body.pipe(${catchTag2}(${JSON.stringify(error2.tag)}, () => ${recovery}))` : `turn ${error2.tag} into a defect`);
|
|
170
192
|
}
|
|
171
193
|
}
|
|
172
194
|
const die2 = api("Effect", "die");
|
|
@@ -184,44 +206,50 @@ function* generateFunction(fn7) {
|
|
|
184
206
|
}
|
|
185
207
|
case "Stream": {
|
|
186
208
|
const empty = api("Stream", "empty");
|
|
187
|
-
const
|
|
188
|
-
const
|
|
209
|
+
const make8 = api("Stream", "make");
|
|
210
|
+
const fail3 = api("Stream", "fail");
|
|
189
211
|
if (empty) yield candidate("StreamEmpty", empty);
|
|
190
|
-
if (
|
|
191
|
-
if (
|
|
212
|
+
if (make8) for (const value of shape.values) yield candidate("StreamOne", `${make8}(${value.text})`, value);
|
|
213
|
+
if (fail3) for (const error2 of shape.errors) yield candidate("StreamFail", `${fail3}(${error2.text})`, error2);
|
|
192
214
|
break;
|
|
193
215
|
}
|
|
194
216
|
case "Layer": {
|
|
195
|
-
const layer2 = api("Layer", "
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
|
|
217
|
+
const layer2 = api("Layer", "effectContext");
|
|
218
|
+
const fail3 = api("Effect", "fail");
|
|
219
|
+
const die2 = api("Effect", "die");
|
|
220
|
+
if (layer2 && die2) yield candidate("LayerDie", `${layer2}(${die2}("mutant.cafe"))`);
|
|
221
|
+
if (layer2 && fail3) {
|
|
222
|
+
for (const error2 of shape.errors) yield candidate("LayerFail", `${layer2}(${fail3}(${error2.text}))`, error2);
|
|
199
223
|
}
|
|
200
224
|
break;
|
|
201
225
|
}
|
|
202
226
|
case "Void":
|
|
203
|
-
yield makeMutant(
|
|
227
|
+
yield makeMutant(fn8, "FnValue", "{}", false, "an empty body");
|
|
204
228
|
break;
|
|
205
229
|
default: {
|
|
206
230
|
const genre = shape.kind === "Boolean" ? "BooleanFlip" : shape.kind === "Literal" ? "LiteralCycle" : "FnValue";
|
|
207
231
|
for (const value of shape.values) {
|
|
208
|
-
if (shape.kind === "Literal" && value.text ===
|
|
232
|
+
if (shape.kind === "Literal" && value.text === fn8.literal) continue;
|
|
209
233
|
yield candidate(genre, value.text, value);
|
|
210
234
|
}
|
|
211
235
|
}
|
|
212
236
|
}
|
|
213
237
|
}
|
|
214
|
-
function makeMutant(
|
|
215
|
-
const
|
|
216
|
-
const
|
|
238
|
+
function makeMutant(fn8, genre, text, synthetic, description) {
|
|
239
|
+
const additions = fn8.extraImports?.filter((item) => text.includes(`${item.namespace}.`)) ?? [];
|
|
240
|
+
const prefix = fn8.sourcePrefix ?? "";
|
|
241
|
+
const insertion = fn8.importInsertionOffset ?? 0;
|
|
242
|
+
const replacement = additions.length && fn8.sourcePrefix !== void 0 ? { startOffset: 0, endOffset: fn8.endOffset, text: prefix.slice(0, insertion) + (insertion ? "\n" : "") + additions.map((item) => item.statement).join("\n") + "\n" + prefix.slice(insertion) + text } : { startOffset: fn8.startOffset, endOffset: fn8.endOffset, text };
|
|
243
|
+
const id = createHash("sha256").update(JSON.stringify([fn8.identityFile ?? fn8.file, fn8.name, fn8.identityOrdinal ?? 0, fn8.logicalSpan, genre, text, additions.map((item) => item.statement)])).digest("hex").slice(0, 24);
|
|
217
244
|
return {
|
|
218
245
|
id,
|
|
219
|
-
file:
|
|
220
|
-
functionName:
|
|
221
|
-
returnType:
|
|
246
|
+
file: fn8.file,
|
|
247
|
+
functionName: fn8.name,
|
|
248
|
+
returnType: fn8.returnType,
|
|
249
|
+
displayReturnType: fn8.displayReturnType,
|
|
222
250
|
genre,
|
|
223
|
-
description: `replace ${
|
|
224
|
-
span:
|
|
251
|
+
description: `replace ${fn8.name} -> ${fn8.returnType} with ${description}`,
|
|
252
|
+
span: fn8.span,
|
|
225
253
|
replacement,
|
|
226
254
|
synthetic
|
|
227
255
|
};
|
|
@@ -287,7 +315,9 @@ function makeTypeScriptOracle() {
|
|
|
287
315
|
const sessions = /* @__PURE__ */ new Map();
|
|
288
316
|
const owners = /* @__PURE__ */ new Map();
|
|
289
317
|
return {
|
|
290
|
-
|
|
318
|
+
discover(config) {
|
|
319
|
+
const notMutated = [];
|
|
320
|
+
const functions = [];
|
|
291
321
|
const configPath = resolve(config.root, config.tsconfig);
|
|
292
322
|
let session = sessions.get(configPath);
|
|
293
323
|
if (!session) {
|
|
@@ -295,19 +325,26 @@ function makeTypeScriptOracle() {
|
|
|
295
325
|
sessions.set(configPath, session);
|
|
296
326
|
}
|
|
297
327
|
const checker = session.program.getTypeChecker();
|
|
328
|
+
const matched = /* @__PURE__ */ new Set();
|
|
298
329
|
for (const source of session.program.getSourceFiles()) {
|
|
299
330
|
const file = resolve(source.fileName);
|
|
300
331
|
const local = relative(config.root, file).replaceAll("\\", "/");
|
|
301
332
|
const project = relative(dirname(configPath), file).replaceAll("\\", "/");
|
|
302
333
|
if (source.isDeclarationFile || local.startsWith("../") || /(?:^|\/)(?:node_modules|__tests__|__mocks__|tests?)\//.test(project) || /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(local)) continue;
|
|
334
|
+
for (const glob of config.include) if (matchesGlob(local, glob)) matched.add(glob);
|
|
303
335
|
if (config.include.length && !config.include.some((glob) => matchesGlob(local, glob))) continue;
|
|
304
336
|
if (config.exclude.some((glob) => matchesGlob(local, glob))) continue;
|
|
305
337
|
owners.set(file, session);
|
|
306
338
|
const api = imports(source);
|
|
307
339
|
const visit = (node) => {
|
|
308
|
-
if (isFunction(node) && node.body && mutable(node, checker)
|
|
309
|
-
|
|
310
|
-
|
|
340
|
+
if (isFunction(node) && node.body && !mutable(node, checker)) {
|
|
341
|
+
notMutated.push({ file, functionName: functionName(node, checker), reason: "unsupported function position: callback, array element or curried implementation" });
|
|
342
|
+
}
|
|
343
|
+
if (isFunction(node) && node.body && mutable(node, checker)) {
|
|
344
|
+
const name = functionName(node, checker);
|
|
345
|
+
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;
|
|
346
|
+
if (reason) notMutated.push({ file, functionName: name, reason });
|
|
347
|
+
if (!reason && (!config.functionFilter.length || config.functionFilter.some((filter) => matchesGlob(name, filter)))) {
|
|
311
348
|
const signature = checker.getSignatureFromDeclaration(node);
|
|
312
349
|
if (signature) {
|
|
313
350
|
const wrapped = wrappedEffect(node, checker);
|
|
@@ -318,30 +355,88 @@ function makeTypeScriptOracle() {
|
|
|
318
355
|
const end = body.getEnd();
|
|
319
356
|
const a = source.getLineAndCharacterOfPosition(start);
|
|
320
357
|
const b = source.getLineAndCharacterOfPosition(end);
|
|
321
|
-
|
|
358
|
+
const beforePipeables = wrapped && ts.isFunctionExpression(node) ? generatorContract(node, checker) : void 0;
|
|
359
|
+
const shape = beforePipeables?.shape ?? shapeOf(type, checker, node, body);
|
|
360
|
+
const originals = equivalentSuccessValues(body, api);
|
|
361
|
+
if (!beforePipeables && type.flags & ts.TypeFlags.TypeParameter && !("values" in shape && shape.values.length) || (beforePipeables ? !nameableContract(beforePipeables, checker, node) : hasUnnameableType(type, checker, node))) {
|
|
362
|
+
notMutated.push({ file, functionName: name, reason: "generic: naked or context-only type-parameter return" });
|
|
363
|
+
} else found.push({
|
|
322
364
|
file,
|
|
323
365
|
name,
|
|
324
|
-
returnType:
|
|
366
|
+
returnType: beforePipeables?.text ?? returnTypeText(type, checker, node),
|
|
367
|
+
displayReturnType: node.type?.getText(source) ?? checker.typeToString(type, node),
|
|
368
|
+
skipReason: beforePipeables ? `no synthesizable generator success value: ${beforePipeables.text}` : synthesisReason(type, checker, node),
|
|
369
|
+
equivalentValues: shape.kind === "Effect" ? shape.values.filter((value) => isEquivalentSuccess(value.text, originals)).map((value) => value.text) : [],
|
|
325
370
|
span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
|
|
326
371
|
startOffset: start,
|
|
327
372
|
endOffset: end,
|
|
328
373
|
original: body.getText(source),
|
|
374
|
+
identityFile: local,
|
|
375
|
+
logicalSpan: { offset: start - node.getStart(source), length: end - start },
|
|
376
|
+
sourcePrefix: source.text.slice(0, start),
|
|
377
|
+
importInsertionOffset: importInsertionOffset(source),
|
|
378
|
+
extraImports: mutationImports(source),
|
|
329
379
|
literal: literalOfBody(body, checker),
|
|
330
380
|
block: ts.isBlock(body),
|
|
331
381
|
generator: generator !== void 0,
|
|
382
|
+
shape,
|
|
383
|
+
api
|
|
384
|
+
});
|
|
385
|
+
} else notMutated.push({ file, functionName: name, reason: "missing callable signature" });
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
if ((ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node)) && node.initializer) {
|
|
389
|
+
const type = checker.getTypeAtLocation(node.initializer);
|
|
390
|
+
if (family(type, checker)?.kind === "Layer") {
|
|
391
|
+
const name = valuePath(node);
|
|
392
|
+
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;
|
|
393
|
+
if (reason) notMutated.push({ file, functionName: name, reason });
|
|
394
|
+
else if (!config.functionFilter.length || config.functionFilter.some((filter) => matchesGlob(name, filter))) {
|
|
395
|
+
const body = node.initializer;
|
|
396
|
+
const a = source.getLineAndCharacterOfPosition(body.getStart(source));
|
|
397
|
+
const b = source.getLineAndCharacterOfPosition(body.getEnd());
|
|
398
|
+
found.push({
|
|
399
|
+
file,
|
|
400
|
+
name,
|
|
401
|
+
returnType: returnTypeText(type, checker, node),
|
|
402
|
+
displayReturnType: checker.typeToString(type, node),
|
|
403
|
+
equivalentValues: [],
|
|
404
|
+
span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
|
|
405
|
+
startOffset: body.getStart(source),
|
|
406
|
+
endOffset: body.getEnd(),
|
|
407
|
+
original: body.getText(source),
|
|
408
|
+
literal: void 0,
|
|
409
|
+
identityFile: local,
|
|
410
|
+
logicalSpan: { offset: body.getStart(source) - node.getStart(source), length: body.getWidth(source) },
|
|
411
|
+
sourcePrefix: source.text.slice(0, body.getStart(source)),
|
|
412
|
+
importInsertionOffset: importInsertionOffset(source),
|
|
413
|
+
extraImports: mutationImports(source),
|
|
414
|
+
block: false,
|
|
415
|
+
generator: false,
|
|
332
416
|
shape: shapeOf(type, checker, node, body),
|
|
333
417
|
api
|
|
334
418
|
});
|
|
335
419
|
}
|
|
336
420
|
}
|
|
337
|
-
return;
|
|
338
421
|
}
|
|
339
422
|
ts.forEachChild(node, visit);
|
|
340
423
|
};
|
|
341
424
|
const found = [];
|
|
342
425
|
visit(source);
|
|
343
|
-
|
|
426
|
+
const occurrences = /* @__PURE__ */ new Map();
|
|
427
|
+
for (const fn8 of found) {
|
|
428
|
+
const ordinal = occurrences.get(fn8.name) ?? 0;
|
|
429
|
+
occurrences.set(fn8.name, ordinal + 1);
|
|
430
|
+
functions.push({ ...fn8, identityOrdinal: ordinal });
|
|
431
|
+
}
|
|
344
432
|
}
|
|
433
|
+
const unmatched = config.include.filter((glob) => !matched.has(glob));
|
|
434
|
+
if (unmatched.length) throw new ProgramLoadError({ tsconfig: configPath, reason: "selection", diagnostics: unmatched.map((glob) => {
|
|
435
|
+
const target = relative(config.root, resolve(config.root, glob));
|
|
436
|
+
const outside = target === ".." || target.startsWith("../");
|
|
437
|
+
return `No source file matched ${JSON.stringify(glob)}${outside ? " (path is outside the package root)" : ""}`;
|
|
438
|
+
}) });
|
|
439
|
+
return { functions, notMutated };
|
|
345
440
|
},
|
|
346
441
|
checkViable(mutant) {
|
|
347
442
|
const session = owners.get(resolve(mutant.file));
|
|
@@ -353,21 +448,120 @@ function makeTypeScriptOracle() {
|
|
|
353
448
|
function isFunction(node) {
|
|
354
449
|
return ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node);
|
|
355
450
|
}
|
|
356
|
-
function
|
|
357
|
-
|
|
451
|
+
function functionValue(node, checker) {
|
|
452
|
+
const wrapper = wrappedEffect(node, checker);
|
|
453
|
+
return wrapper && checker.getTypeAtLocation(node.parent).getCallSignatures().length ? node.parent : node;
|
|
454
|
+
}
|
|
455
|
+
function returnedBy(node, checker) {
|
|
456
|
+
let value = functionValue(node, checker);
|
|
457
|
+
while (ts.isParenthesizedExpression(value.parent)) value = value.parent;
|
|
458
|
+
const parent = value.parent;
|
|
459
|
+
if (ts.isArrowFunction(parent) && parent.body === value) return parent;
|
|
460
|
+
if (ts.isReturnStatement(parent) && parent.expression === value && ts.isBlock(parent.parent) && isFunction(parent.parent.parent)) return parent.parent.parent;
|
|
461
|
+
return void 0;
|
|
358
462
|
}
|
|
359
463
|
function mutable(node, checker) {
|
|
360
|
-
if (ts.isMethodDeclaration(node)) return true;
|
|
361
|
-
|
|
362
|
-
const wrapper = wrappedEffect(node, checker);
|
|
363
|
-
let current = node;
|
|
364
|
-
if (wrapper) current = node.parent;
|
|
464
|
+
if (ts.isMethodDeclaration(node) || ts.isFunctionDeclaration(node)) return true;
|
|
465
|
+
let current = wrappedEffect(node, checker) ? node.parent : node;
|
|
365
466
|
while (ts.isParenthesizedExpression(current.parent)) current = current.parent;
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
467
|
+
return returnedBy(node, checker) !== void 0 || (ts.isVariableDeclaration(current.parent) || ts.isPropertyAssignment(current.parent) || ts.isPropertyDeclaration(current.parent)) && current.parent.initializer === current;
|
|
468
|
+
}
|
|
469
|
+
function layerBody(boundary, checker) {
|
|
470
|
+
let enclosing = boundary.parent;
|
|
471
|
+
while (!ts.isSourceFile(enclosing) && !isFunction(enclosing)) {
|
|
472
|
+
if (ts.isCallExpression(enclosing) && family(checker.getTypeAtLocation(enclosing), checker)?.kind === "Layer") return true;
|
|
473
|
+
enclosing = enclosing.parent;
|
|
474
|
+
}
|
|
475
|
+
return false;
|
|
476
|
+
}
|
|
477
|
+
function returnsLayer(node, checker) {
|
|
478
|
+
const signature = checker.getSignatureFromDeclaration(node);
|
|
479
|
+
if (!signature) return false;
|
|
480
|
+
const type = checker.getReturnTypeOfSignature(signature);
|
|
481
|
+
return (type.isUnion() ? type.types : [type]).every((member) => family(member, checker)?.kind === "Layer");
|
|
482
|
+
}
|
|
483
|
+
function serviceProperty(node, boundary, checker) {
|
|
484
|
+
if (!(ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) || !ts.isObjectLiteralExpression(node.parent)) return false;
|
|
485
|
+
const object = node.parent;
|
|
486
|
+
const call = object.parent;
|
|
487
|
+
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);
|
|
488
|
+
}
|
|
489
|
+
function serviceMethod(node, boundary, checker) {
|
|
490
|
+
if (!layerBody(boundary, checker) || !boundary.body) return false;
|
|
491
|
+
const declaration = ts.findAncestor(node, ts.isVariableDeclaration);
|
|
492
|
+
let returned = false;
|
|
493
|
+
const visit = (child) => {
|
|
494
|
+
if (isFunction(child)) return;
|
|
495
|
+
if (ts.isReturnStatement(child) && child.expression && ts.isCallExpression(child.expression)) {
|
|
496
|
+
const call = child.expression;
|
|
497
|
+
const object = call.arguments[0];
|
|
498
|
+
if (ts.isPropertyAccessExpression(call.expression) && call.expression.name.text === "of" && object && ts.isObjectLiteralExpression(object)) {
|
|
499
|
+
returned ||= object.properties.some((prop) => {
|
|
500
|
+
if (ts.isPropertyAssignment(prop) && (prop.initializer === functionValue(node, checker) || declaration && ts.isIdentifier(prop.initializer) && checker.getSymbolAtLocation(prop.initializer)?.valueDeclaration === declaration)) return true;
|
|
501
|
+
if (ts.isShorthandPropertyAssignment(prop)) return checker.getShorthandAssignmentValueSymbol(prop)?.valueDeclaration === declaration;
|
|
502
|
+
return false;
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
ts.forEachChild(child, visit);
|
|
507
|
+
};
|
|
508
|
+
visit(boundary.body);
|
|
509
|
+
return returned;
|
|
510
|
+
}
|
|
511
|
+
function exportedBinding(binding, checker) {
|
|
512
|
+
let declaration = binding;
|
|
513
|
+
let symbol = binding.name ? checker.getSymbolAtLocation(binding.name) : void 0;
|
|
514
|
+
let container = ts.findAncestor(binding, (node) => ts.isSourceFile(node) || ts.isModuleBlock(node));
|
|
515
|
+
while (container) {
|
|
516
|
+
const module = ts.isSourceFile(container) ? checker.getSymbolAtLocation(container) : ts.isModuleBlock(container) && ts.isModuleDeclaration(container.parent) ? checker.getSymbolAtLocation(container.parent.name) : void 0;
|
|
517
|
+
if (!module || !checker.getExportsOfModule(module).some((item) => {
|
|
518
|
+
const target = item.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(item) : item;
|
|
519
|
+
return target === symbol || target.valueDeclaration === declaration;
|
|
520
|
+
})) return false;
|
|
521
|
+
if (ts.isSourceFile(container)) return true;
|
|
522
|
+
if (!ts.isModuleBlock(container) || !ts.isModuleDeclaration(container.parent)) return false;
|
|
523
|
+
declaration = container.parent;
|
|
524
|
+
symbol = module;
|
|
525
|
+
container = ts.findAncestor(container.parent, (node) => ts.isSourceFile(node) || ts.isModuleBlock(node));
|
|
526
|
+
}
|
|
527
|
+
return false;
|
|
528
|
+
}
|
|
529
|
+
function publicOwner(node, checker, seen = /* @__PURE__ */ new Set()) {
|
|
530
|
+
if (seen.has(node)) return false;
|
|
531
|
+
seen.add(node);
|
|
532
|
+
let current = node;
|
|
533
|
+
let binding;
|
|
534
|
+
let value = isFunction(node) ? node : void 0;
|
|
535
|
+
let throughService = false;
|
|
536
|
+
while (!ts.isSourceFile(current)) {
|
|
537
|
+
if (current !== node && isFunction(current)) {
|
|
538
|
+
const method = value ? serviceMethod(value, current, checker) : serviceProperty(node, current, checker);
|
|
539
|
+
if (!(value && returnedBy(value, checker) === current) && !method && !(throughService && returnsLayer(current, checker))) return false;
|
|
540
|
+
throughService ||= method;
|
|
541
|
+
value = current;
|
|
542
|
+
}
|
|
543
|
+
if (ts.isVariableDeclaration(current) || ts.isFunctionDeclaration(current) || ts.isClassDeclaration(current)) binding = current;
|
|
544
|
+
current = current.parent;
|
|
545
|
+
}
|
|
546
|
+
if (!binding) return false;
|
|
547
|
+
if (exportedBinding(binding, checker)) return true;
|
|
548
|
+
let exposed = false;
|
|
549
|
+
const declaration = binding;
|
|
550
|
+
const visit = (child) => {
|
|
551
|
+
if (exposed) return;
|
|
552
|
+
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;
|
|
553
|
+
if (referenced?.valueDeclaration === declaration) {
|
|
554
|
+
exposed = ts.isExportAssignment(child) || publicOwner(child, checker, seen);
|
|
555
|
+
}
|
|
556
|
+
ts.forEachChild(child, visit);
|
|
557
|
+
};
|
|
558
|
+
visit(current);
|
|
559
|
+
return exposed;
|
|
369
560
|
}
|
|
370
561
|
function skipped(node) {
|
|
562
|
+
return skippedNode(node);
|
|
563
|
+
}
|
|
564
|
+
function skippedNode(node) {
|
|
371
565
|
let current = node;
|
|
372
566
|
while (!ts.isSourceFile(current)) {
|
|
373
567
|
if (ts.getJSDocTags(current).some((tag) => tag.tagName.text === "mutants-skip")) return true;
|
|
@@ -375,17 +569,23 @@ function skipped(node) {
|
|
|
375
569
|
}
|
|
376
570
|
return false;
|
|
377
571
|
}
|
|
378
|
-
function
|
|
379
|
-
|
|
380
|
-
if (ts.isMethodDeclaration(node) && ts.isClassLike(node.parent) && node.parent.name) return `${node.parent.name.text}.${node.name.getText()}`;
|
|
381
|
-
return node.name.getText();
|
|
382
|
-
}
|
|
572
|
+
function valuePath(node) {
|
|
573
|
+
const parts = [];
|
|
383
574
|
let current = node;
|
|
384
575
|
while (!ts.isSourceFile(current)) {
|
|
385
|
-
if (ts.isVariableDeclaration(current))
|
|
576
|
+
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());
|
|
386
577
|
current = current.parent;
|
|
387
578
|
}
|
|
388
|
-
return "default";
|
|
579
|
+
return parts.join(".") || "default";
|
|
580
|
+
}
|
|
581
|
+
function functionName(node, checker) {
|
|
582
|
+
let path = valuePath(node);
|
|
583
|
+
let parent = returnedBy(node, checker);
|
|
584
|
+
while (parent) {
|
|
585
|
+
path += ".<inner>";
|
|
586
|
+
parent = returnedBy(parent, checker);
|
|
587
|
+
}
|
|
588
|
+
return path;
|
|
389
589
|
}
|
|
390
590
|
function wrappedEffect(node, checker) {
|
|
391
591
|
if (!ts.isFunctionExpression(node) || !node.asteriskToken || !ts.isCallExpression(node.parent)) return void 0;
|
|
@@ -396,6 +596,39 @@ function wrappedEffect(node, checker) {
|
|
|
396
596
|
const returned = checker.getReturnTypeOfSignature(signature);
|
|
397
597
|
return family(returned, checker)?.kind === "Effect" ? returned : void 0;
|
|
398
598
|
}
|
|
599
|
+
function nameableContract(contract, checker, node) {
|
|
600
|
+
return contract.types.every((type) => !hasUnnameableType(type, checker, node));
|
|
601
|
+
}
|
|
602
|
+
function hasUnnameableType(type, checker, location) {
|
|
603
|
+
const printed = checker.typeToTypeNode(type, location, ts.NodeBuilderFlags.NoTruncation);
|
|
604
|
+
if (!printed) return true;
|
|
605
|
+
let missing = false;
|
|
606
|
+
const visit = (node) => {
|
|
607
|
+
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !checker.resolveName(node.typeName.text, location, ts.SymbolFlags.Type, false)) missing = true;
|
|
608
|
+
ts.forEachChild(node, visit);
|
|
609
|
+
};
|
|
610
|
+
visit(printed);
|
|
611
|
+
return missing;
|
|
612
|
+
}
|
|
613
|
+
function generatorContract(node, checker) {
|
|
614
|
+
const signature = checker.getSignatureFromDeclaration(node);
|
|
615
|
+
if (!signature || !node.body) return void 0;
|
|
616
|
+
const iterator = checker.getReturnTypeOfSignature(signature);
|
|
617
|
+
const args = checker.getTypeArguments(iterator);
|
|
618
|
+
const [yielded, success] = args;
|
|
619
|
+
if (!yielded || !success) return void 0;
|
|
620
|
+
const effects = (yielded.isUnion() ? yielded.types : [yielded]).flatMap((t) => {
|
|
621
|
+
const f = family(t, checker);
|
|
622
|
+
return f?.kind === "Effect" ? [f] : [];
|
|
623
|
+
});
|
|
624
|
+
const print = (t) => returnTypeText(t, checker, node);
|
|
625
|
+
const union = (index) => [...new Set(effects.flatMap((f) => f.args[index] ? [print(f.args[index])] : []))].join(" | ") || "never";
|
|
626
|
+
return {
|
|
627
|
+
types: [success, ...effects.flatMap((effect5) => effect5.args.slice(1))],
|
|
628
|
+
text: `import("effect/Effect").Effect<${print(success)}, ${union(1)}, ${union(2)}>`,
|
|
629
|
+
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()] }
|
|
630
|
+
};
|
|
631
|
+
}
|
|
399
632
|
function literalOfBody(body, checker) {
|
|
400
633
|
const first = ts.isBlock(body) && body.statements.length === 1 ? body.statements[0] : void 0;
|
|
401
634
|
const expression = ts.isBlock(body) ? first && ts.isReturnStatement(first) ? first.expression : void 0 : body;
|
|
@@ -434,9 +667,28 @@ function imports(source) {
|
|
|
434
667
|
}
|
|
435
668
|
return (module, member) => {
|
|
436
669
|
const namespace = namespaces.get(module);
|
|
437
|
-
return namespace ? `${namespace}.${member}` : named.get(`${module}.${member}`)
|
|
670
|
+
return namespace ? `${namespace}.${member}` : named.get(`${module}.${member}`) ?? `${mutationNamespace(source, module)}.${member}`;
|
|
438
671
|
};
|
|
439
672
|
}
|
|
673
|
+
function importInsertionOffset(source) {
|
|
674
|
+
let offset = source.text.startsWith("#!") ? source.text.indexOf("\n") + 1 || source.text.length : 0;
|
|
675
|
+
for (const statement of source.statements) {
|
|
676
|
+
if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) break;
|
|
677
|
+
offset = statement.getEnd();
|
|
678
|
+
}
|
|
679
|
+
return offset;
|
|
680
|
+
}
|
|
681
|
+
function mutationNamespace(source, module) {
|
|
682
|
+
let name = `__mutantCafe${module}`;
|
|
683
|
+
while (source.text.includes(name)) name += "_";
|
|
684
|
+
return name;
|
|
685
|
+
}
|
|
686
|
+
function mutationImports(source) {
|
|
687
|
+
return ["Effect", "Option", "Stream", "Layer"].map((module) => {
|
|
688
|
+
const namespace = mutationNamespace(source, module);
|
|
689
|
+
return { namespace, statement: `import * as ${namespace} from "effect/${module}";` };
|
|
690
|
+
});
|
|
691
|
+
}
|
|
440
692
|
function family(type, checker) {
|
|
441
693
|
const symbol = type.aliasSymbol ?? type.getSymbol();
|
|
442
694
|
const name = symbol?.getName();
|
|
@@ -472,32 +724,36 @@ function family(type, checker) {
|
|
|
472
724
|
return void 0;
|
|
473
725
|
}
|
|
474
726
|
function shapeOf(type, checker, node, body) {
|
|
727
|
+
if (type.isUnion() && type.types.every((member) => family(member, checker)?.kind === "Effect")) {
|
|
728
|
+
const shapes = type.types.map((member) => shapeOf(member, checker, node, body));
|
|
729
|
+
const values2 = shapes.flatMap((shape) => shape.kind === "Effect" ? shape.values : []);
|
|
730
|
+
const errors = shapes.flatMap((shape) => shape.kind === "Effect" ? shape.errors : []);
|
|
731
|
+
return {
|
|
732
|
+
kind: "Effect",
|
|
733
|
+
values: [...new Map(values2.map((value) => [value.text, value])).values()].sort((a, b) => a.text.localeCompare(b.text, "en")),
|
|
734
|
+
errors: [...new Map(errors.map((error2) => [error2.tag, error2])).values()].sort((a, b) => a.tag.localeCompare(b.tag, "en"))
|
|
735
|
+
};
|
|
736
|
+
}
|
|
475
737
|
const detected = family(type, checker);
|
|
476
738
|
if (detected) {
|
|
477
739
|
const [a, e] = detected.args;
|
|
478
|
-
const
|
|
479
|
-
if (detected.kind === "Option") return { kind: "Option", values };
|
|
740
|
+
const values2 = a ? valuesOf(a, checker, node) : [];
|
|
741
|
+
if (detected.kind === "Option") return { kind: "Option", values: values2 };
|
|
480
742
|
const errors = e ? taggedValues(e, checker, node) : [];
|
|
481
|
-
if (detected.kind === "Layer") {
|
|
482
|
-
|
|
483
|
-
const find = (child) => {
|
|
484
|
-
if (!service && ts.isCallExpression(child) && child.arguments[0]) {
|
|
485
|
-
const arg = child.arguments[0];
|
|
486
|
-
const argType = checker.getTypeAtLocation(arg);
|
|
487
|
-
if (argType.getProperty("Identifier") && argType.getProperty("Service")) service = arg.getText();
|
|
488
|
-
}
|
|
489
|
-
ts.forEachChild(child, find);
|
|
490
|
-
};
|
|
491
|
-
find(body);
|
|
492
|
-
return { kind: "Layer", errors, service };
|
|
493
|
-
}
|
|
494
|
-
return { kind: detected.kind, values, errors };
|
|
743
|
+
if (detected.kind === "Layer") return { kind: "Layer", errors };
|
|
744
|
+
return { kind: detected.kind, values: values2, errors };
|
|
495
745
|
}
|
|
496
746
|
if (type.flags & ts.TypeFlags.Void) return { kind: "Void", values: [] };
|
|
497
747
|
const members = type.isUnion() ? type.types : [type];
|
|
498
748
|
const boolean = members.every((t) => (t.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral)) !== 0);
|
|
499
749
|
const literal = members.every((t) => t.isLiteral());
|
|
500
|
-
|
|
750
|
+
const values = valuesOf(type, checker, node);
|
|
751
|
+
if (isFunction(node)) for (const parameter of node.parameters) {
|
|
752
|
+
if (ts.isIdentifier(parameter.name) && !parameter.questionToken && !parameter.dotDotDotToken && checker.getTypeAtLocation(parameter) === type) {
|
|
753
|
+
values.push({ text: parameter.name.text, synthetic: false });
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
return { kind: boolean ? "Boolean" : literal ? "Literal" : "Value", values };
|
|
501
757
|
}
|
|
502
758
|
function taggedValues(type, checker, location) {
|
|
503
759
|
return (type.isUnion() ? type.types : [type]).flatMap((member) => {
|
|
@@ -512,9 +768,10 @@ function taggedValues(type, checker, location) {
|
|
|
512
768
|
function constructError(type, checker, location, tag) {
|
|
513
769
|
const symbol = type.getSymbol();
|
|
514
770
|
if (symbol) {
|
|
515
|
-
const visible = checker.getSymbolsInScope(location, ts.SymbolFlags.Value).find((candidate) => {
|
|
771
|
+
const visible = checker.getSymbolsInScope(location, ts.SymbolFlags.Value | ts.SymbolFlags.Alias).find((candidate) => {
|
|
772
|
+
if (candidate.declarations?.some((declaration) => ts.isImportSpecifier(declaration) && (declaration.isTypeOnly || declaration.parent.parent.isTypeOnly))) return false;
|
|
516
773
|
const target = candidate.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(candidate) : candidate;
|
|
517
|
-
return target === symbol;
|
|
774
|
+
return target === symbol || (symbol.declarations?.some((declaration) => target.declarations?.includes(declaration)) ?? false);
|
|
518
775
|
});
|
|
519
776
|
if (visible) {
|
|
520
777
|
const constructor = checker.getTypeOfSymbolAtLocation(visible, location).getConstructSignatures()[0];
|
|
@@ -522,12 +779,73 @@ function constructError(type, checker, location, tag) {
|
|
|
522
779
|
const param = constructor.parameters[0];
|
|
523
780
|
if (!param) return { text: `new ${visible.name}()`, synthetic: false };
|
|
524
781
|
const fields = checker.getTypeOfSymbolAtLocation(param, location);
|
|
782
|
+
if (fields.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined)) return { text: `new ${visible.name}()`, synthetic: false };
|
|
525
783
|
const value = valuesOf(fields, checker, location)[0];
|
|
526
|
-
if (value && !value.synthetic)
|
|
784
|
+
if (value && !value.synthetic) {
|
|
785
|
+
const rest = param.valueDeclaration && ts.isParameter(param.valueDeclaration) && param.valueDeclaration.dotDotDotToken;
|
|
786
|
+
return { text: `new ${visible.name}(${rest ? "..." : ""}${value.text})`, synthetic: false };
|
|
787
|
+
}
|
|
527
788
|
}
|
|
528
789
|
}
|
|
529
790
|
}
|
|
530
|
-
return { text: `({ _tag: ${JSON.stringify(tag)} } as unknown as ${checker.typeToString(type, location, ts.TypeFormatFlags.
|
|
791
|
+
return { text: `({ _tag: ${JSON.stringify(tag)} } as unknown as ${checker.typeToString(type, location, ts.TypeFormatFlags.NoTruncation)})`, synthetic: true };
|
|
792
|
+
}
|
|
793
|
+
function returnTypeText(type, checker, node) {
|
|
794
|
+
const print = (t) => checker.typeToString(t, node, ts.TypeFormatFlags.NoTruncation);
|
|
795
|
+
if (type.isUnion()) {
|
|
796
|
+
const members = type.types.map((member) => family(member, checker));
|
|
797
|
+
if (members.every((member) => member?.kind === "Effect")) {
|
|
798
|
+
const args = [0, 1, 2].map((index) => [...new Set(members.flatMap((member) => member?.args[index] ? [print(member.args[index])] : []))].sort().join(" | ") || "never");
|
|
799
|
+
return `import("effect/Effect").Effect<${args.join(", ")}>`;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
return print(type);
|
|
803
|
+
}
|
|
804
|
+
function literalData(node) {
|
|
805
|
+
if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) return literalData(node.expression);
|
|
806
|
+
if (ts.isStringLiteral(node) || ts.isNumericLiteral(node)) return [node.kind, node.text];
|
|
807
|
+
if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword || node.kind === ts.SyntaxKind.NullKeyword) return [node.kind];
|
|
808
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
809
|
+
const fields = [];
|
|
810
|
+
for (const field of node.properties) {
|
|
811
|
+
if (!ts.isPropertyAssignment(field) || !field.name || ts.isComputedPropertyName(field.name)) return void 0;
|
|
812
|
+
const value = literalData(field.initializer);
|
|
813
|
+
if (value === void 0) return void 0;
|
|
814
|
+
fields.push([field.name.getText().replace(/^["']|["']$/g, ""), value]);
|
|
815
|
+
}
|
|
816
|
+
return fields.sort(([a], [b]) => a.localeCompare(b, "en"));
|
|
817
|
+
}
|
|
818
|
+
return void 0;
|
|
819
|
+
}
|
|
820
|
+
function equivalentSuccessValues(body, api) {
|
|
821
|
+
const values = [];
|
|
822
|
+
const visit = (node) => {
|
|
823
|
+
if (ts.isCallExpression(node) && node.expression.getText() === api("Effect", "succeed") && node.arguments[0]) {
|
|
824
|
+
const value = literalData(node.arguments[0]);
|
|
825
|
+
if (value !== void 0) values.push(JSON.stringify(value));
|
|
826
|
+
}
|
|
827
|
+
ts.forEachChild(node, visit);
|
|
828
|
+
};
|
|
829
|
+
visit(body);
|
|
830
|
+
return values;
|
|
831
|
+
}
|
|
832
|
+
function isEquivalentSuccess(text, values) {
|
|
833
|
+
const source = ts.createSourceFile("literal.ts", `(${text})`, ts.ScriptTarget.Latest, true);
|
|
834
|
+
const statement = source.statements[0];
|
|
835
|
+
if (!statement || !ts.isExpressionStatement(statement)) return false;
|
|
836
|
+
const value = literalData(statement.expression);
|
|
837
|
+
return value !== void 0 && values.includes(JSON.stringify(value));
|
|
838
|
+
}
|
|
839
|
+
function synthesisReason(type, checker, node) {
|
|
840
|
+
if (type.flags & (ts.TypeFlags.TypeParameter | ts.TypeFlags.IndexedAccess)) return "generic return cannot be synthesized";
|
|
841
|
+
const detected = family(type, checker);
|
|
842
|
+
const valueType = detected?.args[0] ?? type;
|
|
843
|
+
for (const field of valueType.getProperties()) {
|
|
844
|
+
if (!(field.flags & ts.SymbolFlags.Optional) && !valuesOf(checker.getTypeOfSymbolAtLocation(field, node), checker, node).length) {
|
|
845
|
+
return `no synthesizable value for field ${field.name}`;
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
return `opaque return: ${checker.typeToString(type, node)}`;
|
|
531
849
|
}
|
|
532
850
|
function valuesOf(type, checker, location, depth = 0) {
|
|
533
851
|
if (depth > 4 || type.flags & ts.TypeFlags.Never) return [];
|
|
@@ -544,7 +862,16 @@ function valuesOf(type, checker, location, depth = 0) {
|
|
|
544
862
|
...wrap ? values.map((v) => ({ text: `${wrap}(${v.text})`, synthetic: v.synthetic })) : []
|
|
545
863
|
];
|
|
546
864
|
}
|
|
547
|
-
if (type.
|
|
865
|
+
if (type.isIntersection()) {
|
|
866
|
+
const primitive = type.types.find((member) => member.flags & (ts.TypeFlags.String | ts.TypeFlags.Number));
|
|
867
|
+
const brand = type.types.some((member) => member.getProperties().some((prop) => prop.name.includes("Brand")));
|
|
868
|
+
if (primitive && brand) return valuesOf(primitive, checker, location, depth + 1).map((v) => ({ ...v, text: `(${v.text} as ${returnTypeText(type, checker, location)})` }));
|
|
869
|
+
}
|
|
870
|
+
const symbol = type.getSymbol();
|
|
871
|
+
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))) {
|
|
872
|
+
return [value(symbol.name.endsWith("Set") ? "new Set()" : "new Map()")];
|
|
873
|
+
}
|
|
874
|
+
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));
|
|
548
875
|
if (type.isStringLiteral()) return [value(JSON.stringify(type.value))];
|
|
549
876
|
if (type.isNumberLiteral()) return [value(String(type.value))];
|
|
550
877
|
if (type.flags & ts.TypeFlags.BooleanLiteral) return [value(checker.typeToString(type))];
|
|
@@ -569,11 +896,21 @@ function valuesOf(type, checker, location, depth = 0) {
|
|
|
569
896
|
for (const prop of type.getProperties()) {
|
|
570
897
|
if (prop.flags & ts.SymbolFlags.Optional) continue;
|
|
571
898
|
if (!/^[$\w]+$/.test(prop.name)) return [];
|
|
572
|
-
const
|
|
573
|
-
if (!
|
|
574
|
-
fields.push(
|
|
899
|
+
const values = valuesOf(checker.getTypeOfSymbolAtLocation(prop, location), checker, location, depth + 1);
|
|
900
|
+
if (!values.length) return [];
|
|
901
|
+
fields.push({ name: prop.name, values });
|
|
575
902
|
}
|
|
576
|
-
|
|
903
|
+
const literalFields = fields.filter((field) => {
|
|
904
|
+
const prop = type.getProperty(field.name);
|
|
905
|
+
const t = checker.getTypeOfSymbolAtLocation(prop, location);
|
|
906
|
+
return (t.isUnion() ? t.types : [t]).every((member) => member.isLiteral() || !!(member.flags & ts.TypeFlags.BooleanLiteral));
|
|
907
|
+
});
|
|
908
|
+
const render = (changed, replacement) => value(`({ ${fields.map((field) => {
|
|
909
|
+
const v = (field === changed ? replacement : field.values[0]).text;
|
|
910
|
+
return `${JSON.stringify(field.name)}: ${literalFields.includes(field) ? `(${v} as const)` : v}`;
|
|
911
|
+
}).join(", ")} })`);
|
|
912
|
+
const anonymous = !type.aliasSymbol && (!type.getSymbol() || ["__type", "__object"].includes(type.getSymbol().name));
|
|
913
|
+
return [render(), ...anonymous ? literalFields.flatMap((field) => field.values.slice(1).map((v) => render(field, v))) : []];
|
|
577
914
|
}
|
|
578
915
|
return [];
|
|
579
916
|
}
|
|
@@ -584,18 +921,23 @@ var MutantSourceLive = Layer.effect(
|
|
|
584
921
|
Effect.sync(() => makeMutantSource(makeTypeScriptOracle()))
|
|
585
922
|
);
|
|
586
923
|
function makeMutantSource(oracle) {
|
|
924
|
+
const discover = (config) => Effect.try({
|
|
925
|
+
try: () => {
|
|
926
|
+
const discovered = oracle.discover(config);
|
|
927
|
+
const notMutated = [...discovered.notMutated];
|
|
928
|
+
const mutants = [];
|
|
929
|
+
for (const fn8 of discovered.functions) {
|
|
930
|
+
const generated = [...generateFunction(fn8)];
|
|
931
|
+
if (!generated.length) notMutated.push({ file: fn8.file, functionName: fn8.name, reason: fn8.skipReason ?? `opaque return or no synthesizable value: ${fn8.displayReturnType}` });
|
|
932
|
+
mutants.push(...generated);
|
|
933
|
+
}
|
|
934
|
+
return { mutants, notMutated };
|
|
935
|
+
},
|
|
936
|
+
catch: (error2) => loadError(config.tsconfig, error2)
|
|
937
|
+
});
|
|
587
938
|
return {
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
*[Symbol.iterator]() {
|
|
591
|
-
for (const fn7 of oracle.discover(config)) yield* generateFunction(fn7);
|
|
592
|
-
}
|
|
593
|
-
}),
|
|
594
|
-
catch: (error2) => loadError(config.tsconfig, error2)
|
|
595
|
-
})).pipe(
|
|
596
|
-
// Iteration is synchronous compiler work; load it inside the typed error boundary.
|
|
597
|
-
Stream.catchDefect((error2) => Stream.fail(loadError(config.tsconfig, error2)))
|
|
598
|
-
),
|
|
939
|
+
notMutated: (config) => discover(config).pipe(Effect.map((result2) => result2.notMutated)),
|
|
940
|
+
generate: (config) => Stream.unwrap(discover(config).pipe(Effect.map((result2) => Stream.fromIterable(result2.mutants)))),
|
|
599
941
|
checkViable: (mutant) => Effect.try({
|
|
600
942
|
try: () => oracle.checkViable(mutant),
|
|
601
943
|
catch: (error2) => loadError("", error2)
|
|
@@ -652,7 +994,23 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
652
994
|
const src = path.join(from, entry);
|
|
653
995
|
const dest = path.join(to, entry);
|
|
654
996
|
if (entry === "node_modules") {
|
|
655
|
-
|
|
997
|
+
const linkDependencies = (from2, to2) => Effect2.gen(function* () {
|
|
998
|
+
yield* fs.makeDirectory(to2, { recursive: true });
|
|
999
|
+
for (const name of yield* fs.readDirectory(from2)) {
|
|
1000
|
+
if ([".vite", ".vite-temp", ".vitest", ".cache"].includes(name)) continue;
|
|
1001
|
+
const dependency = path.join(from2, name);
|
|
1002
|
+
const destination = path.join(to2, name);
|
|
1003
|
+
if (name.startsWith("@")) {
|
|
1004
|
+
yield* linkDependencies(dependency, destination);
|
|
1005
|
+
continue;
|
|
1006
|
+
}
|
|
1007
|
+
const realDependency = yield* fs.realPath(dependency);
|
|
1008
|
+
const rel = path.relative(copyRoot, realDependency);
|
|
1009
|
+
const inside = rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) && !rel.split(path.sep).includes("node_modules");
|
|
1010
|
+
yield* fs.symlink(inside ? path.join(temp, rel) : realDependency, destination);
|
|
1011
|
+
}
|
|
1012
|
+
});
|
|
1013
|
+
yield* linkDependencies(src, dest);
|
|
656
1014
|
} else {
|
|
657
1015
|
yield* copy(src, dest, [...ancestors, real]);
|
|
658
1016
|
}
|
|
@@ -709,20 +1067,223 @@ var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
|
709
1067
|
|
|
710
1068
|
// packages/runner/src/TestRunner.ts
|
|
711
1069
|
import * as Clock from "effect/Clock";
|
|
1070
|
+
import * as Console from "effect/Console";
|
|
1071
|
+
|
|
1072
|
+
// packages/runner/src/Preflight.ts
|
|
712
1073
|
import * as Effect3 from "effect/Effect";
|
|
713
|
-
import * as
|
|
714
|
-
import * as Stream2 from "effect/Stream";
|
|
1074
|
+
import * as Schema5 from "effect/Schema";
|
|
715
1075
|
import * as ChildProcess from "effect/process/ChildProcess";
|
|
716
1076
|
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
|
|
717
|
-
var
|
|
1077
|
+
var Issues = Schema5.Array(SelectionIssue);
|
|
1078
|
+
var probe = String.raw`
|
|
1079
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
1080
|
+
import { resolve, relative, dirname, isAbsolute, sep } from "node:path";
|
|
1081
|
+
import { createRequire } from "node:module";
|
|
1082
|
+
import { fileURLToPath } from "node:url";
|
|
1083
|
+
const root = process.cwd();
|
|
1084
|
+
const issues = [];
|
|
1085
|
+
const pkg = JSON.parse(await readFile("package.json", "utf8").catch(error => { if (error.code === "ENOENT") return "{}"; throw error; }));
|
|
1086
|
+
const script = pkg.scripts?.test;
|
|
1087
|
+
const vitestScript = !script || /(?:^|[\s/])vitest(?=\s|$|[;&|])/.test(script);
|
|
1088
|
+
const delegated = script && /(?:\bturbo\s+(?:run\s+)?test\b|\bpnpm\s+(?:-r|--recursive|--filter\s+\S+)\s+(?:run\s+)?test\b)/.test(script);
|
|
1089
|
+
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);
|
|
1090
|
+
if (otherRunner) {
|
|
1091
|
+
issues.push({ kind: "runner", reason: 'package.json scripts.test = ' + JSON.stringify(script) + '; mutant.cafe only runs Vitest' });
|
|
1092
|
+
} else {
|
|
1093
|
+
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') });
|
|
1094
|
+
let ctx;
|
|
1095
|
+
try {
|
|
1096
|
+
const { createVitest } = await import("vitest/node");
|
|
1097
|
+
ctx = await createVitest("test", { root, watch: false, cache: false, fsModuleCache: false });
|
|
1098
|
+
const selected = new Set((await ctx.globTestSpecifications()).map(spec => resolve(spec.moduleId)));
|
|
1099
|
+
const sources = new Map();
|
|
1100
|
+
async function walk(dir) {
|
|
1101
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
1102
|
+
if (["node_modules", ".git", ".brain", ".pi", ".agent_sources", "mutants.out", "dist"].includes(entry.name)) continue;
|
|
1103
|
+
const file = resolve(dir, entry.name);
|
|
1104
|
+
if (entry.isDirectory()) await walk(file);
|
|
1105
|
+
else if (/\.[cm]?[jt]sx?$/.test(file)) sources.set(file, await readFile(file, "utf8"));
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
await walk(root);
|
|
1109
|
+
// Read only explicit rootDir/outDir evidence, including JSONC and extends.
|
|
1110
|
+
// Do not depend on a compiler API in the tested package or infer build layout.
|
|
1111
|
+
async function configOptions(file, seen = new Set()) {
|
|
1112
|
+
if (seen.has(file)) throw new Error('cyclic tsconfig extends');
|
|
1113
|
+
const text = await readFile(file, 'utf8');
|
|
1114
|
+
const json = text.replace(/"(?:\\.|[^"\\])*"|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, token => token.startsWith('"') ? token : token.replace(/[^\r\n]/g, ' '))
|
|
1115
|
+
.replace(/("(?:\\.|[^"\\])*")|,\s*(?=[}\]])/g, (token, string) => string ?? '');
|
|
1116
|
+
const config = JSON.parse(json);
|
|
1117
|
+
let options = {};
|
|
1118
|
+
for (const base of Array.isArray(config.extends) ? config.extends : typeof config.extends === 'string' ? [config.extends] : []) {
|
|
1119
|
+
const path = base.startsWith('.') || isAbsolute(base) ? resolve(dirname(file), base) : createRequire(file).resolve(base);
|
|
1120
|
+
const candidate = await readFile(path).then(() => path, () => path + '.json');
|
|
1121
|
+
options = { ...options, ...await configOptions(candidate, new Set([...seen, file])) };
|
|
1122
|
+
}
|
|
1123
|
+
for (const key of ['rootDir', 'outDir']) if (typeof config.compilerOptions?.[key] === 'string') options[key] = resolve(dirname(file), config.compilerOptions[key]);
|
|
1124
|
+
return options;
|
|
1125
|
+
}
|
|
1126
|
+
let options = {};
|
|
1127
|
+
try { options = await configOptions(resolve(root, process.argv[1])); }
|
|
1128
|
+
catch { /* No proven mapping: restrict by importing tests only. */ }
|
|
1129
|
+
function sourceFile(path) {
|
|
1130
|
+
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));
|
|
1131
|
+
}
|
|
1132
|
+
function exportTypes(specifier) {
|
|
1133
|
+
const key = specifier === pkg.name ? '.' : './' + specifier.slice(pkg.name.length + 1);
|
|
1134
|
+
let entry = pkg.exports;
|
|
1135
|
+
let wildcard;
|
|
1136
|
+
if (entry && typeof entry === 'object' && Object.keys(entry).some(key => key.startsWith('.'))) {
|
|
1137
|
+
if (key in entry) entry = entry[key];
|
|
1138
|
+
else {
|
|
1139
|
+
const pattern = Object.keys(entry).find(pattern => pattern.includes('*') && key.startsWith(pattern.split('*')[0]) && key.endsWith(pattern.split('*')[1]));
|
|
1140
|
+
if (!pattern) return;
|
|
1141
|
+
const [before, after] = pattern.split('*');
|
|
1142
|
+
wildcard = key.slice(before.length, after.length ? -after.length : undefined);
|
|
1143
|
+
entry = entry[pattern];
|
|
1144
|
+
}
|
|
1145
|
+
} else if (key !== '.') return;
|
|
1146
|
+
function types(value) {
|
|
1147
|
+
if (!value || typeof value !== 'object') return;
|
|
1148
|
+
if (typeof value.types === 'string') return value.types;
|
|
1149
|
+
return types(value.types) ?? types(value.import) ?? types(value.default);
|
|
1150
|
+
}
|
|
1151
|
+
const path = types(entry) ?? (key === '.' ? pkg.types : undefined);
|
|
1152
|
+
return typeof path === 'string' ? resolve(root, wildcard === undefined ? path : path.replaceAll('*', wildcard)) : undefined;
|
|
1153
|
+
}
|
|
1154
|
+
function mappedSource(entry, types) {
|
|
1155
|
+
for (const path of [types, entry]) {
|
|
1156
|
+
if (!path) continue;
|
|
1157
|
+
if (/\.[cm]?tsx?$/.test(path) && !/\.d\.[cm]?ts$/.test(path)) {
|
|
1158
|
+
const direct = sourceFile(path);
|
|
1159
|
+
if (direct) return direct;
|
|
1160
|
+
}
|
|
1161
|
+
if (!options.rootDir || !options.outDir) continue;
|
|
1162
|
+
const inside = relative(options.outDir, path);
|
|
1163
|
+
if (inside === '..' || inside.startsWith('..' + sep) || isAbsolute(inside)) continue;
|
|
1164
|
+
const stem = inside.replace(/(?:\.d)?\.[cm]?[jt]sx?$/, '');
|
|
1165
|
+
const mapped = sourceFile(resolve(options.rootDir, stem));
|
|
1166
|
+
if (mapped) return mapped;
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
const edges = new Map();
|
|
1170
|
+
const built = [];
|
|
1171
|
+
for (const [file, text] of sources) {
|
|
1172
|
+
const dependencies = new Set();
|
|
1173
|
+
edges.set(file, dependencies);
|
|
1174
|
+
for (const match of text.matchAll(/(?:from\s*|import\s*\(?\s*|require\s*\(\s*)["']([^"']+)["']/g)) {
|
|
1175
|
+
let target;
|
|
1176
|
+
let source;
|
|
1177
|
+
const specifier = match[1];
|
|
1178
|
+
if (specifier.startsWith('.')) target = resolve(dirname(file), specifier);
|
|
1179
|
+
else {
|
|
1180
|
+
try {
|
|
1181
|
+
const self = pkg.name && (specifier === pkg.name || specifier.startsWith(pkg.name + '/'));
|
|
1182
|
+
target = self ? fileURLToPath(import.meta.resolve(specifier)) : createRequire(file).resolve(specifier);
|
|
1183
|
+
if (self && (!/\.[cm]?tsx?$/.test(target) || /\.d\.[cm]?ts$/.test(target))) {
|
|
1184
|
+
source = mappedSource(target, exportTypes(specifier));
|
|
1185
|
+
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') });
|
|
1186
|
+
}
|
|
1187
|
+
} catch { continue; }
|
|
1188
|
+
}
|
|
1189
|
+
const candidate = source ?? sourceFile(target);
|
|
1190
|
+
if (candidate) dependencies.add(candidate);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
function dependencies(file, seen = new Set()) {
|
|
1194
|
+
if (seen.has(file)) return seen;
|
|
1195
|
+
seen.add(file);
|
|
1196
|
+
for (const dependency of edges.get(file) ?? []) dependencies(dependency, seen);
|
|
1197
|
+
return seen;
|
|
1198
|
+
}
|
|
1199
|
+
const closures = new Map([...selected].map(file => [file, dependencies(file)]));
|
|
1200
|
+
for (const entry of built) {
|
|
1201
|
+
const testFiles = [...selected].filter(file => closures.get(file).has(entry.importer)).map(file => relative(root, file));
|
|
1202
|
+
if (testFiles.length) issues.push({ kind: 'built', ...(entry.source ? { files: [...dependencies(entry.source)].map(file => relative(root, file)) } : {}), testFiles, reason: entry.reason });
|
|
1203
|
+
}
|
|
1204
|
+
const reached = new Set([...closures.values()].flatMap(files => [...files]));
|
|
1205
|
+
for (const [file, text] of sources) {
|
|
1206
|
+
const testFile = /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(file)
|
|
1207
|
+
|| (/["'](?:node:test|vitest|@effect\/vitest)["']/.test(text) && /\b(?:it|test|describe)\s*(?:\.|\()/.test(text));
|
|
1208
|
+
if (reached.has(file) || !testFile) continue;
|
|
1209
|
+
for (const target of dependencies(file)) {
|
|
1210
|
+
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' });
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
} catch (error) {
|
|
1214
|
+
issues.push({ kind: 'warning', reason: 'Cannot verify Vitest resolved selection: ' + String(error) });
|
|
1215
|
+
} finally { await ctx?.close(); }
|
|
1216
|
+
}
|
|
1217
|
+
console.log('mutant-cafe-preflight:' + JSON.stringify([...new Map(issues.map(issue => [JSON.stringify(issue), issue])).values()]));
|
|
1218
|
+
`;
|
|
1219
|
+
var preflight = Effect3.fn("TestRunner.preflight")(function* (root, tsconfig = "tsconfig.json") {
|
|
718
1220
|
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
|
719
|
-
const
|
|
720
|
-
|
|
1221
|
+
const output = yield* spawner.string(ChildProcess.make("node", ["--input-type=module", "--eval", probe, tsconfig], { cwd: root, stdin: "ignore" }));
|
|
1222
|
+
const encoded = output.split("\n").find((line) => line.startsWith("mutant-cafe-preflight:"))?.slice("mutant-cafe-preflight:".length);
|
|
1223
|
+
const issues = encoded === void 0 ? [{ kind: "warning", reason: "Vitest selection probe returned no evidence" }] : yield* Schema5.decodeEffect(Schema5.fromJsonString(Issues))(encoded);
|
|
1224
|
+
return issues;
|
|
1225
|
+
});
|
|
1226
|
+
function unreliableFor(baseline, file, testFiles) {
|
|
1227
|
+
return baseline.unreliable?.filter((issue) => {
|
|
1228
|
+
switch (issue.kind) {
|
|
1229
|
+
case "runner":
|
|
1230
|
+
return true;
|
|
1231
|
+
case "warning":
|
|
1232
|
+
return false;
|
|
1233
|
+
case "target":
|
|
1234
|
+
return issue.file === file;
|
|
1235
|
+
case "built":
|
|
1236
|
+
return (issue.files === void 0 || issue.files.includes(file)) && (testFiles?.some((test) => issue.testFiles.includes(test)) ?? false);
|
|
1237
|
+
}
|
|
1238
|
+
}) ?? [];
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// packages/runner/src/TestRunner.ts
|
|
1242
|
+
import * as Effect4 from "effect/Effect";
|
|
1243
|
+
import * as Layer3 from "effect/Layer";
|
|
1244
|
+
import * as FileSystem3 from "effect/FileSystem";
|
|
1245
|
+
import * as Path3 from "effect/Path";
|
|
1246
|
+
import * as Stream2 from "effect/Stream";
|
|
1247
|
+
import * as Schema6 from "effect/Schema";
|
|
1248
|
+
import * as ChildProcess2 from "effect/process/ChildProcess";
|
|
1249
|
+
import * as ChildProcessSpawner3 from "effect/process/ChildProcessSpawner";
|
|
1250
|
+
var TestRunnerLive = Layer3.effect(TestRunner, Effect4.gen(function* () {
|
|
1251
|
+
const spawner = yield* ChildProcessSpawner3.ChildProcessSpawner;
|
|
1252
|
+
const fs = yield* FileSystem3.FileSystem;
|
|
1253
|
+
const path = yield* Path3.Path;
|
|
1254
|
+
const execute = Effect4.fn("TestRunner.execute")(function* (dir, args, timeoutMs) {
|
|
1255
|
+
const reporterDir = yield* fs.makeTempDirectoryScoped({ prefix: "mutant-vitest-" }).pipe(
|
|
1256
|
+
Effect4.mapError((error2) => new TestSpawnError({ command: ["vitest"], message: String(error2) }))
|
|
1257
|
+
);
|
|
1258
|
+
const reporter = path.join(reporterDir, "reporter.mjs");
|
|
1259
|
+
const marker = `mutant-cafe:${path.basename(reporterDir)}:`;
|
|
1260
|
+
yield* fs.writeFileString(reporter, `import { relative } from "node:path";
|
|
1261
|
+
export default class {
|
|
1262
|
+
files = 0;
|
|
1263
|
+
onTestRunStart(specifications) { this.files = specifications.length; console.log(${JSON.stringify(marker + "selected:")} + JSON.stringify(specifications.map(spec => relative(process.cwd(), spec.moduleId)))); }
|
|
1264
|
+
onTestModuleCollected() { console.log(${JSON.stringify(marker + "collected")}); }
|
|
1265
|
+
onTestCaseResult(test) { if (test.result().state === "failed") console.log(${JSON.stringify(marker + "failed")}); }
|
|
1266
|
+
onTestRunEnd() { if (this.files === 0) console.log(${JSON.stringify(marker + "empty")}); }
|
|
1267
|
+
}`).pipe(Effect4.mapError((error2) => new TestSpawnError({ command: ["vitest"], message: String(error2) })));
|
|
1268
|
+
const command = [
|
|
1269
|
+
"npx",
|
|
1270
|
+
"--no",
|
|
1271
|
+
"vitest",
|
|
1272
|
+
...args,
|
|
1273
|
+
"--reporter=default",
|
|
1274
|
+
`--reporter=${reporter}`,
|
|
1275
|
+
"--bail",
|
|
1276
|
+
"1",
|
|
1277
|
+
...timeoutMs === void 0 ? [] : ["--testTimeout", String(Math.max(1, Math.floor(timeoutMs / 2)))],
|
|
1278
|
+
"--no-cache",
|
|
1279
|
+
"--no-fsModuleCache"
|
|
1280
|
+
];
|
|
1281
|
+
if (timeoutMs === void 0) yield* Console.log(`Baseline command: ${command.join(" ")} (cwd: ${dir.path})`);
|
|
721
1282
|
const started = yield* Clock.currentTimeMillis;
|
|
722
1283
|
const chunks = [];
|
|
723
1284
|
let exitCode = 1;
|
|
724
|
-
const child =
|
|
725
|
-
const handle = yield* spawner.spawn(
|
|
1285
|
+
const child = Effect4.scoped(Effect4.gen(function* () {
|
|
1286
|
+
const handle = yield* spawner.spawn(ChildProcess2.make(command[0], command.slice(1), {
|
|
726
1287
|
cwd: dir.path,
|
|
727
1288
|
// Node's scoped spawner kills the detached process group, not just pnpm.
|
|
728
1289
|
detached: true,
|
|
@@ -730,41 +1291,72 @@ var TestRunnerLive = Layer3.effect(TestRunner, Effect3.gen(function* () {
|
|
|
730
1291
|
forceKillAfter: "100 millis",
|
|
731
1292
|
stdin: "ignore"
|
|
732
1293
|
}));
|
|
733
|
-
const collect = handle.all.pipe(Stream2.decodeText(), Stream2.runForEach((chunk) =>
|
|
1294
|
+
const collect = handle.all.pipe(Stream2.decodeText(), Stream2.runForEach((chunk) => Effect4.sync(() => {
|
|
734
1295
|
chunks.push(chunk);
|
|
735
1296
|
})));
|
|
736
|
-
const [code] = yield*
|
|
1297
|
+
const [code] = yield* Effect4.all([handle.exitCode, collect], { concurrency: "unbounded" });
|
|
737
1298
|
exitCode = code;
|
|
738
1299
|
return code === 0 ? "passed" : "failed";
|
|
739
1300
|
}));
|
|
740
1301
|
const status = yield* (timeoutMs === void 0 ? child : child.pipe(
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
)).pipe(
|
|
1302
|
+
Effect4.timeout(timeoutMs),
|
|
1303
|
+
Effect4.catchTag("TimeoutError", () => Effect4.succeed("timedOut"))
|
|
1304
|
+
)).pipe(Effect4.mapError((error2) => new TestSpawnError({ command, message: error2.message })));
|
|
744
1305
|
const ended = yield* Clock.currentTimeMillis;
|
|
745
|
-
const
|
|
1306
|
+
const output = chunks.join("");
|
|
1307
|
+
const failed = output.includes(marker + "failed");
|
|
1308
|
+
const selection = output.split("\n").find((line) => line.includes(marker + "selected:"))?.split(marker + "selected:")[1];
|
|
1309
|
+
const selected = selection === void 0 ? [] : yield* Schema6.decodeEffect(Schema6.fromJsonString(Schema6.Array(Schema6.String)))(selection).pipe(
|
|
1310
|
+
Effect4.mapError((error2) => new TestSpawnError({ command, message: `Cannot decode Vitest selected files: ${String(error2)}` }))
|
|
1311
|
+
);
|
|
1312
|
+
const run2 = {
|
|
1313
|
+
status: failed ? "failed" : status === "passed" && output.includes(marker + "empty") ? "untested" : status,
|
|
1314
|
+
durationMs: ended - started,
|
|
1315
|
+
command,
|
|
1316
|
+
output,
|
|
1317
|
+
testsCollected: output.includes(marker + "collected"),
|
|
1318
|
+
testFiles: selected
|
|
1319
|
+
};
|
|
746
1320
|
return { ...run2, exitCode };
|
|
747
|
-
});
|
|
1321
|
+
}, Effect4.scoped);
|
|
748
1322
|
return TestRunner.of({
|
|
749
|
-
baseline:
|
|
750
|
-
const
|
|
751
|
-
|
|
752
|
-
|
|
1323
|
+
baseline: Effect4.fn("TestRunner.baseline")(function* (dir, tsconfig) {
|
|
1324
|
+
const unreliable = yield* preflight(dir.path, tsconfig).pipe(Effect4.provideService(ChildProcessSpawner3.ChildProcessSpawner, spawner), Effect4.catch((error2) => Effect4.succeed([{ kind: "warning", reason: `Cannot verify runner selection: ${String(error2)}` }])));
|
|
1325
|
+
for (const issue of unreliable) yield* Console.warn(`Warning (${issue.kind}): ${issue.reason}`);
|
|
1326
|
+
if (unreliable.some((issue) => issue.kind === "runner")) {
|
|
1327
|
+
const command = ["npx", "--no", "vitest", "run", "--passWithNoTests"];
|
|
1328
|
+
yield* Console.warn(`Baseline command (not executed: unsupported runner): ${command.join(" ")}`);
|
|
1329
|
+
return { durationMs: 0, testCommand: command, unreliable };
|
|
1330
|
+
}
|
|
1331
|
+
const run2 = yield* execute(dir, ["run", "--passWithNoTests"]);
|
|
1332
|
+
if (run2.status !== "passed" && run2.status !== "untested") {
|
|
1333
|
+
return yield* Effect4.fail(new BaselineFailed({ exitCode: run2.exitCode, output: run2.output, command: run2.command }));
|
|
753
1334
|
}
|
|
754
|
-
return { durationMs: run2.durationMs, testCommand: run2.command };
|
|
1335
|
+
return { durationMs: run2.durationMs, testCommand: run2.command, unreliable };
|
|
755
1336
|
}),
|
|
756
|
-
runRelated:
|
|
1337
|
+
runRelated: Effect4.fn("TestRunner.runRelated")(function* (dir, file, timeoutMs) {
|
|
1338
|
+
const related = yield* execute(dir, ["related", file, "--run", "--passWithNoTests"], timeoutMs);
|
|
1339
|
+
if (related.status !== "untested") return related;
|
|
1340
|
+
const remaining = Math.max(1, timeoutMs - related.durationMs);
|
|
1341
|
+
const full = yield* execute(dir, ["run", "--passWithNoTests"], remaining);
|
|
1342
|
+
return {
|
|
1343
|
+
...full,
|
|
1344
|
+
status: full.status === "passed" ? "untested" : full.status,
|
|
1345
|
+
durationMs: related.durationMs + full.durationMs,
|
|
1346
|
+
output: related.output + "\nFull-suite fallback:\n" + full.output
|
|
1347
|
+
};
|
|
1348
|
+
})
|
|
757
1349
|
});
|
|
758
1350
|
}));
|
|
759
1351
|
|
|
760
1352
|
// packages/runner/src/Run.ts
|
|
761
1353
|
import { createEffectActor, createEffectLogic, join, send, setupEffect } from "@xstate/effect";
|
|
762
1354
|
import { types } from "xstate";
|
|
763
|
-
import * as
|
|
1355
|
+
import * as Effect5 from "effect/Effect";
|
|
764
1356
|
import * as Pool from "effect/Pool";
|
|
765
|
-
import * as
|
|
1357
|
+
import * as Path5 from "effect/Path";
|
|
766
1358
|
import * as Result from "effect/Result";
|
|
767
|
-
import * as
|
|
1359
|
+
import * as Schema7 from "effect/Schema";
|
|
768
1360
|
import * as Scope from "effect/Scope";
|
|
769
1361
|
import * as Stream3 from "effect/Stream";
|
|
770
1362
|
var ScratchPool = class {
|
|
@@ -773,44 +1365,58 @@ var ScratchPool = class {
|
|
|
773
1365
|
this.value = value;
|
|
774
1366
|
}
|
|
775
1367
|
};
|
|
776
|
-
var runMutants =
|
|
1368
|
+
var runMutants = Effect5.fn("Runner.runMutants")(function* (config, mutants) {
|
|
777
1369
|
const scratch = yield* Scratch;
|
|
778
1370
|
const tests = yield* TestRunner;
|
|
779
1371
|
const source = yield* MutantSource;
|
|
780
1372
|
const reporter = yield* Reporter;
|
|
781
1373
|
const scope = yield* Scope.Scope;
|
|
782
|
-
const path = yield*
|
|
1374
|
+
const path = yield* Path5.Path;
|
|
783
1375
|
const jobs = Math.max(1, Math.floor(config.jobs));
|
|
784
1376
|
const report = (state2) => ({
|
|
785
|
-
schemaVersion:
|
|
1377
|
+
schemaVersion: 2,
|
|
786
1378
|
tool: "mutant.cafe",
|
|
787
1379
|
root: config.root,
|
|
788
1380
|
baseline: state2.baseline,
|
|
789
1381
|
timeoutMs: state2.timeoutMs,
|
|
790
|
-
results: state2.results
|
|
1382
|
+
results: state2.results,
|
|
1383
|
+
...state2.failure === void 0 ? {} : { failure: state2.failure._tag === "BaselineFailed" ? `${state2.failure._tag}: ${state2.failure.command.join(" ")}
|
|
1384
|
+
${state2.failure.output.slice(-8e3)}` : String(state2.failure) }
|
|
791
1385
|
});
|
|
792
|
-
const capture = (effect5) =>
|
|
793
|
-
const copying = createEffectLogic(() => capture(
|
|
1386
|
+
const capture = (effect5) => Effect5.result(effect5);
|
|
1387
|
+
const copying = createEffectLogic(() => capture(Effect5.gen(function* () {
|
|
794
1388
|
const pool = yield* Pool.make({ acquire: scratch.acquire(config.root), size: jobs }).pipe(
|
|
795
|
-
|
|
1389
|
+
Effect5.provideService(Scope.Scope, scope)
|
|
796
1390
|
);
|
|
797
|
-
yield*
|
|
1391
|
+
yield* Effect5.scoped(Pool.get(pool));
|
|
798
1392
|
return new ScratchPool(pool);
|
|
799
1393
|
})));
|
|
800
|
-
const baselining = createEffectLogic(({ input }) => capture(
|
|
801
|
-
if (input === void 0) return yield*
|
|
802
|
-
const baseline = yield*
|
|
1394
|
+
const baselining = createEffectLogic(({ input }) => capture(Effect5.gen(function* () {
|
|
1395
|
+
if (input === void 0) return yield* Effect5.die("Missing scratch pool");
|
|
1396
|
+
const baseline = yield* Effect5.scoped(Effect5.gen(function* () {
|
|
803
1397
|
const dir = yield* Pool.get(input.value);
|
|
804
|
-
return yield* tests.baseline(dir);
|
|
1398
|
+
return yield* tests.baseline(dir, path.isAbsolute(config.tsconfig) ? path.relative(config.root, config.tsconfig) : config.tsconfig);
|
|
805
1399
|
}));
|
|
806
1400
|
return { baseline, timeoutMs: config.timeoutMs ?? Math.max(config.minimumTimeoutMs, Math.ceil(config.timeoutMultiplier * baseline.durationMs)) };
|
|
807
1401
|
})));
|
|
808
1402
|
const generating = createEffectLogic(() => capture(Stream3.runCollect(mutants ?? source.generate(config))));
|
|
809
|
-
const testing = createEffectLogic(({ input }) => capture(
|
|
1403
|
+
const testing = createEffectLogic(({ input }) => capture(Effect5.gen(function* () {
|
|
810
1404
|
const dirs = input.state.pool?.value;
|
|
811
|
-
if (dirs === void 0) return yield*
|
|
1405
|
+
if (dirs === void 0) return yield* Effect5.die("Missing scratch pool");
|
|
1406
|
+
const neverBudgets = /* @__PURE__ */ new Map();
|
|
1407
|
+
for (const mutant of input.state.pending) {
|
|
1408
|
+
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;
|
|
1409
|
+
const measured = yield* Effect5.scoped(Effect5.gen(function* () {
|
|
1410
|
+
const dir = yield* Pool.get(dirs);
|
|
1411
|
+
return yield* tests.runRelated(dir, path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file, input.state.timeoutMs);
|
|
1412
|
+
}));
|
|
1413
|
+
if (measured.status === "failed" || measured.status === "timedOut") {
|
|
1414
|
+
return yield* new BaselineFailed({ exitCode: 1, output: measured.output, command: measured.command });
|
|
1415
|
+
}
|
|
1416
|
+
neverBudgets.set(mutant.file, Math.max(config.neverTimeoutMs, Math.ceil(measured.durationMs * config.timeoutMultiplier)));
|
|
1417
|
+
}
|
|
812
1418
|
yield* Stream3.fromIterable(input.state.pending).pipe(
|
|
813
|
-
Stream3.mapEffect((mutant) =>
|
|
1419
|
+
Stream3.mapEffect((mutant) => Effect5.scoped(Effect5.gen(function* () {
|
|
814
1420
|
const viability = yield* source.checkViable(mutant);
|
|
815
1421
|
if (!viability.viable) {
|
|
816
1422
|
const result3 = { mutant, outcome: "unviable", durationMs: 0, testCommand: [], diagnostics: viability.diagnostics };
|
|
@@ -818,20 +1424,29 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
|
|
|
818
1424
|
yield* reporter.progress(result3);
|
|
819
1425
|
return;
|
|
820
1426
|
}
|
|
1427
|
+
const localFile = path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file;
|
|
1428
|
+
const unreliable = unreliableFor(input.state.baseline, localFile);
|
|
1429
|
+
if (unreliable.length) {
|
|
1430
|
+
const result3 = { mutant, outcome: "unreliable", durationMs: 0, testCommand: input.state.baseline.testCommand, diagnostics: unreliable.map((issue) => issue.reason) };
|
|
1431
|
+
yield* input.record(result3);
|
|
1432
|
+
yield* reporter.progress(result3);
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
821
1435
|
const dir = yield* Pool.get(dirs);
|
|
822
|
-
const run2 = yield*
|
|
1436
|
+
const run2 = yield* Effect5.acquireUseRelease(
|
|
823
1437
|
dir.apply(mutant),
|
|
824
|
-
() => tests.runRelated(dir, path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file, mutant.genre === "EffectNever" ?
|
|
1438
|
+
() => 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),
|
|
825
1439
|
// A dirty directory must never return to the pool, even on cancel.
|
|
826
|
-
() => dir.revert(mutant).pipe(
|
|
1440
|
+
() => dir.revert(mutant).pipe(Effect5.orDie)
|
|
827
1441
|
);
|
|
1442
|
+
const selectedIssues = unreliableFor(input.state.baseline, localFile, run2.testFiles);
|
|
828
1443
|
const result2 = {
|
|
829
1444
|
mutant,
|
|
830
|
-
//
|
|
831
|
-
outcome: run2.status === "timedOut" ? mutant.genre === "EffectNever" ? "caught" : "timeout" : run2.status === "failed" ? "caught" : "missed",
|
|
1445
|
+
// A kill before collection proves nothing about whether tests noticed.
|
|
1446
|
+
outcome: selectedIssues.length ? "unreliable" : run2.status === "timedOut" ? mutant.genre === "EffectNever" && run2.testsCollected ? "caught" : "timeout" : run2.status === "failed" ? "caught" : run2.status === "untested" ? "untested" : "missed",
|
|
832
1447
|
durationMs: run2.durationMs,
|
|
833
1448
|
testCommand: run2.command,
|
|
834
|
-
diagnostics:
|
|
1449
|
+
diagnostics: selectedIssues.map((issue) => issue.reason),
|
|
835
1450
|
...run2.output === "" ? {} : { output: run2.output }
|
|
836
1451
|
};
|
|
837
1452
|
yield* input.record(result2);
|
|
@@ -841,12 +1456,12 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
|
|
|
841
1456
|
);
|
|
842
1457
|
})));
|
|
843
1458
|
const reporting = createEffectLogic(({ input }) => capture(
|
|
844
|
-
input.reported ?
|
|
1459
|
+
input.reported ? Effect5.void : reporter.write(report(input))
|
|
845
1460
|
));
|
|
846
1461
|
const machine = setupEffect({
|
|
847
1462
|
schemas: {
|
|
848
1463
|
context: types(),
|
|
849
|
-
events: { CANCEL:
|
|
1464
|
+
events: { CANCEL: Schema7.Struct({}), RESULT: Schema7.Struct({ result: MutantResult }) }
|
|
850
1465
|
},
|
|
851
1466
|
actors: { copying, baselining, generating, testing, reporting }
|
|
852
1467
|
}).createMachine({
|
|
@@ -870,7 +1485,11 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
|
|
|
870
1485
|
baseline: { invoke: {
|
|
871
1486
|
src: "baselining",
|
|
872
1487
|
input: ({ context }) => context.pool,
|
|
873
|
-
onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "generating", context: { ...context, ...event.output.success } } : { target:
|
|
1488
|
+
onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "generating", context: { ...context, ...event.output.success } } : { target: "reporting", context: {
|
|
1489
|
+
...context,
|
|
1490
|
+
failure: event.output.failure,
|
|
1491
|
+
baseline: event.output.failure._tag === "BaselineFailed" ? { durationMs: 0, testCommand: event.output.failure.command } : context.baseline
|
|
1492
|
+
} }
|
|
874
1493
|
} },
|
|
875
1494
|
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 } } } },
|
|
876
1495
|
testing: { invoke: {
|
|
@@ -904,52 +1523,53 @@ var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
|
|
|
904
1523
|
failure: Result.isFailure(event.output) ? event.output.failure : context.failure
|
|
905
1524
|
} })
|
|
906
1525
|
} },
|
|
907
|
-
baselineFailed: { type: "final" },
|
|
908
1526
|
failed: { type: "final" },
|
|
909
1527
|
done: { type: "final" }
|
|
910
1528
|
}
|
|
911
1529
|
});
|
|
912
|
-
const state = yield*
|
|
1530
|
+
const state = yield* Effect5.scoped(Effect5.gen(function* () {
|
|
913
1531
|
const actor = yield* createEffectActor(machine);
|
|
914
|
-
return yield* join(actor).pipe(
|
|
1532
|
+
return yield* join(actor).pipe(Effect5.orDie, Effect5.onInterrupt(() => Effect5.gen(function* () {
|
|
915
1533
|
yield* send(actor, { type: "CANCEL" });
|
|
916
|
-
yield* join(actor).pipe(
|
|
1534
|
+
yield* join(actor).pipe(Effect5.orDie);
|
|
917
1535
|
})));
|
|
918
1536
|
}));
|
|
919
1537
|
if (state.failure !== void 0) return yield* state.failure;
|
|
920
1538
|
return report(state);
|
|
921
|
-
},
|
|
1539
|
+
}, Effect5.scoped);
|
|
922
1540
|
|
|
923
1541
|
// packages/cli/src/bin.ts
|
|
924
|
-
import * as
|
|
1542
|
+
import * as Effect9 from "effect/Effect";
|
|
925
1543
|
import * as Layer5 from "effect/Layer";
|
|
926
|
-
import * as
|
|
1544
|
+
import * as Stream6 from "effect/Stream";
|
|
927
1545
|
|
|
928
1546
|
// packages/cli/src/Command.ts
|
|
929
|
-
import * as
|
|
930
|
-
import * as
|
|
931
|
-
import * as
|
|
1547
|
+
import * as Console3 from "effect/Console";
|
|
1548
|
+
import * as Effect8 from "effect/Effect";
|
|
1549
|
+
import * as FileSystem9 from "effect/FileSystem";
|
|
932
1550
|
import * as Option from "effect/Option";
|
|
933
|
-
import * as
|
|
1551
|
+
import * as Path11 from "effect/Path";
|
|
934
1552
|
import * as Ref from "effect/Ref";
|
|
935
|
-
import * as
|
|
936
|
-
import * as
|
|
1553
|
+
import * as Schema10 from "effect/Schema";
|
|
1554
|
+
import * as Stream5 from "effect/Stream";
|
|
937
1555
|
import * as Command from "effect/cli/Command";
|
|
938
1556
|
import * as Flag from "effect/cli/Flag";
|
|
939
1557
|
|
|
940
1558
|
// packages/cli/src/Diff.ts
|
|
941
|
-
import * as
|
|
942
|
-
import * as
|
|
943
|
-
import * as
|
|
944
|
-
import * as
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
1559
|
+
import * as Effect6 from "effect/Effect";
|
|
1560
|
+
import * as FileSystem5 from "effect/FileSystem";
|
|
1561
|
+
import * as Path7 from "effect/Path";
|
|
1562
|
+
import * as Schema8 from "effect/Schema";
|
|
1563
|
+
import * as Stream4 from "effect/Stream";
|
|
1564
|
+
import * as ChildProcess3 from "effect/process/ChildProcess";
|
|
1565
|
+
var DiffMismatch = class extends Schema8.TaggedError()("DiffMismatch", {
|
|
1566
|
+
path: Schema8.String,
|
|
1567
|
+
message: Schema8.String
|
|
948
1568
|
}) {
|
|
949
1569
|
};
|
|
950
|
-
var parseDiff = (text, path) =>
|
|
1570
|
+
var parseDiff = (text, path) => Effect6.try({
|
|
951
1571
|
try: () => {
|
|
952
|
-
const
|
|
1572
|
+
const fail3 = (message) => {
|
|
953
1573
|
throw new DiffParseError({ path, message });
|
|
954
1574
|
};
|
|
955
1575
|
if (text === "") return [];
|
|
@@ -961,35 +1581,35 @@ var parseDiff = (text, path) => Effect5.try({
|
|
|
961
1581
|
while (i < input.length) {
|
|
962
1582
|
const line = input[i++];
|
|
963
1583
|
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;
|
|
964
|
-
if (!line.startsWith("--- "))
|
|
1584
|
+
if (!line.startsWith("--- ")) fail3("Expected a unified diff file header");
|
|
965
1585
|
const next = input[i++];
|
|
966
|
-
if (!next?.startsWith("+++ "))
|
|
1586
|
+
if (!next?.startsWith("+++ ")) fail3("Missing new-side file header");
|
|
967
1587
|
const raw = next.slice(4).split(" ")[0];
|
|
968
1588
|
const decoded = raw.startsWith('"') ? JSON.parse(raw) : raw;
|
|
969
|
-
if (typeof decoded !== "string")
|
|
1589
|
+
if (typeof decoded !== "string") fail3("Invalid file path");
|
|
970
1590
|
const file = String(decoded).replace(/^b\//, "");
|
|
971
|
-
const
|
|
1591
|
+
const lines2 = [];
|
|
972
1592
|
let hunks = 0;
|
|
973
1593
|
let previousEnd = 0;
|
|
974
1594
|
let previousOldEnd = 0;
|
|
975
1595
|
while (input[i]?.startsWith("@@")) {
|
|
976
1596
|
const match2 = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:.*)$/.exec(input[i++]);
|
|
977
|
-
if (!match2)
|
|
1597
|
+
if (!match2) fail3("Invalid hunk header");
|
|
978
1598
|
let oldRemaining = Number(match2[2] ?? 1);
|
|
979
1599
|
let newRemaining = Number(match2[4] ?? 1);
|
|
980
1600
|
let newLine = Number(match2[3]);
|
|
981
1601
|
const oldStart = Number(match2[1]);
|
|
982
1602
|
const oldCount = oldRemaining;
|
|
983
|
-
if (![oldStart, oldRemaining, newLine, newRemaining].every(Number.isSafeInteger))
|
|
984
|
-
if (oldRemaining > 0 && oldStart === 0 || newRemaining > 0 && newLine === 0)
|
|
985
|
-
if (newLine < previousEnd || oldStart < previousOldEnd)
|
|
1603
|
+
if (![oldStart, oldRemaining, newLine, newRemaining].every(Number.isSafeInteger)) fail3("Hunk range is not a safe integer");
|
|
1604
|
+
if (oldRemaining > 0 && oldStart === 0 || newRemaining > 0 && newLine === 0) fail3("Nonempty hunk cannot start at zero");
|
|
1605
|
+
if (newLine < previousEnd || oldStart < previousOldEnd) fail3("Overlapping or unordered hunks");
|
|
986
1606
|
let previousPrefix = "";
|
|
987
1607
|
const markNoNewline = () => {
|
|
988
1608
|
if (previousPrefix === "+" || previousPrefix === " ") {
|
|
989
|
-
const last =
|
|
990
|
-
if (last === void 0 || last.noNewline)
|
|
991
|
-
|
|
992
|
-
} else if (previousPrefix !== "-")
|
|
1609
|
+
const last = lines2.at(-1);
|
|
1610
|
+
if (last === void 0 || last.noNewline) fail3("Unexpected no-newline marker");
|
|
1611
|
+
lines2[lines2.length - 1] = { ...last, noNewline: true };
|
|
1612
|
+
} else if (previousPrefix !== "-") fail3("Unexpected no-newline marker");
|
|
993
1613
|
previousPrefix = "";
|
|
994
1614
|
};
|
|
995
1615
|
hunks++;
|
|
@@ -999,15 +1619,15 @@ var parseDiff = (text, path) => Effect5.try({
|
|
|
999
1619
|
markNoNewline();
|
|
1000
1620
|
continue;
|
|
1001
1621
|
}
|
|
1002
|
-
if (body === void 0)
|
|
1622
|
+
if (body === void 0) fail3("Truncated hunk");
|
|
1003
1623
|
const prefix = body[0];
|
|
1004
1624
|
if (prefix === " " || prefix === "-") oldRemaining--;
|
|
1005
1625
|
if (prefix === " " || prefix === "+") {
|
|
1006
1626
|
newRemaining--;
|
|
1007
|
-
|
|
1008
|
-
} else if (prefix !== "-")
|
|
1627
|
+
lines2.push({ number: newLine++, text: body.slice(1), added: prefix === "+", noNewline: false });
|
|
1628
|
+
} else if (prefix !== "-") fail3("Invalid hunk line");
|
|
1009
1629
|
previousPrefix = prefix;
|
|
1010
|
-
if (oldRemaining < 0 || newRemaining < 0)
|
|
1630
|
+
if (oldRemaining < 0 || newRemaining < 0) fail3("Hunk count does not match its body");
|
|
1011
1631
|
}
|
|
1012
1632
|
if (input[i] === "\") {
|
|
1013
1633
|
markNoNewline();
|
|
@@ -1016,48 +1636,67 @@ var parseDiff = (text, path) => Effect5.try({
|
|
|
1016
1636
|
previousEnd = newLine;
|
|
1017
1637
|
previousOldEnd = oldStart + oldCount;
|
|
1018
1638
|
}
|
|
1019
|
-
if (hunks === 0)
|
|
1639
|
+
if (hunks === 0) fail3("File has no hunks");
|
|
1020
1640
|
sawFile = true;
|
|
1021
|
-
if (file !== "/dev/null") patches.push({ file, lines });
|
|
1641
|
+
if (file !== "/dev/null") patches.push({ file, lines: lines2 });
|
|
1022
1642
|
}
|
|
1023
|
-
if (!sawFile)
|
|
1643
|
+
if (!sawFile) fail3("No unified diff found");
|
|
1024
1644
|
return patches;
|
|
1025
1645
|
},
|
|
1026
|
-
catch: (error2) =>
|
|
1646
|
+
catch: (error2) => Schema8.is(DiffParseError)(error2) ? error2 : new DiffParseError({ path, message: String(error2) })
|
|
1027
1647
|
});
|
|
1028
|
-
var
|
|
1029
|
-
const fs = yield*
|
|
1030
|
-
const path = yield*
|
|
1648
|
+
var selectDiffScope = Effect6.fn("selectDiffScope")(function* (options) {
|
|
1649
|
+
const fs = yield* FileSystem5.FileSystem;
|
|
1650
|
+
const path = yield* Path7.Path;
|
|
1031
1651
|
const diffPath = path.resolve(options.root, options.diffPath);
|
|
1032
|
-
const text = yield* fs.readFileString(diffPath).pipe(
|
|
1652
|
+
const text = yield* fs.readFileString(diffPath).pipe(Effect6.mapError((error2) => new DiffParseError({ path: diffPath, message: String(error2) })));
|
|
1033
1653
|
const patches = yield* parseDiff(text, diffPath);
|
|
1654
|
+
const gitRoot = yield* Effect6.scoped(Effect6.gen(function* () {
|
|
1655
|
+
const handle = yield* ChildProcess3.make("git", ["rev-parse", "--show-toplevel"], { cwd: options.root, stderr: "ignore" });
|
|
1656
|
+
const [output, code] = yield* Effect6.all([Stream4.mkString(Stream4.decodeText(handle.stdout)), handle.exitCode], { concurrency: "unbounded" });
|
|
1657
|
+
if (Number(code) !== 0 || !output.trim()) return options.root;
|
|
1658
|
+
const physicalRoot = yield* fs.realPath(options.root);
|
|
1659
|
+
return path.resolve(options.root, path.relative(physicalRoot, output.trim()));
|
|
1660
|
+
})).pipe(Effect6.catch(() => Effect6.succeed(options.root)));
|
|
1034
1661
|
const changed = /* @__PURE__ */ new Map();
|
|
1035
1662
|
for (const patch of patches) {
|
|
1036
|
-
const
|
|
1037
|
-
const
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
const
|
|
1046
|
-
|
|
1663
|
+
const repositoryPath = path.resolve(gitRoot, patch.file);
|
|
1664
|
+
const candidates = [.../* @__PURE__ */ new Set([repositoryPath, path.resolve(options.root, patch.file)])];
|
|
1665
|
+
let absolute;
|
|
1666
|
+
for (const candidate of candidates) {
|
|
1667
|
+
const relative2 = path.relative(gitRoot, candidate);
|
|
1668
|
+
if (relative2 === ".." || relative2.startsWith(`..${path.sep}`) || path.isAbsolute(relative2)) {
|
|
1669
|
+
return yield* new DiffParseError({ path: diffPath, message: "Diff path escapes repository root" });
|
|
1670
|
+
}
|
|
1671
|
+
if (!(yield* fs.exists(candidate))) continue;
|
|
1672
|
+
const current = yield* fs.readFileString(candidate).pipe(Effect6.mapError((error2) => new DiffMismatch({ path: patch.file, message: String(error2) })));
|
|
1673
|
+
const lines2 = current.split("\n");
|
|
1674
|
+
const finalLine = current.endsWith("\n") ? lines2.length - 1 : lines2.length;
|
|
1675
|
+
if (patch.lines.every((line) => {
|
|
1676
|
+
const newlineMismatch = line.noNewline ? line.number !== finalLine || current.endsWith("\n") : line.number === finalLine && !current.endsWith("\n");
|
|
1677
|
+
return lines2[line.number - 1] === line.text && !newlineMismatch;
|
|
1678
|
+
})) {
|
|
1679
|
+
absolute = candidate;
|
|
1680
|
+
break;
|
|
1681
|
+
}
|
|
1047
1682
|
}
|
|
1683
|
+
if (absolute === void 0) return yield* new DiffMismatch({ path: patch.file, message: "New-side lines do not match the tree at the Git toplevel or working directory" });
|
|
1048
1684
|
const added = changed.get(absolute) ?? /* @__PURE__ */ new Set();
|
|
1049
1685
|
for (const line of patch.lines) if (line.added) added.add(line.number);
|
|
1050
1686
|
changed.set(absolute, added);
|
|
1051
1687
|
}
|
|
1052
|
-
return
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1688
|
+
return {
|
|
1689
|
+
mutants: options.mutants.filter((mutant) => {
|
|
1690
|
+
const added = changed.get(path.resolve(options.root, mutant.file));
|
|
1691
|
+
const end = mutant.span.end.line - (mutant.span.end.column === 1 ? 1 : 0);
|
|
1692
|
+
return added !== void 0 && [...added].some((line) => line >= mutant.span.start.line && line <= end);
|
|
1693
|
+
}),
|
|
1694
|
+
notMutated: options.notMutated.filter((item) => changed.has(path.resolve(options.root, item.file)))
|
|
1695
|
+
};
|
|
1057
1696
|
});
|
|
1058
1697
|
|
|
1059
1698
|
// packages/cli/src/ExitCode.ts
|
|
1060
|
-
var reportExitCode = (report) => report.results.some((result2) => result2.outcome === "missed") ? 2 : report.results.some((result2) => result2.outcome === "timeout") ? 3 : 0;
|
|
1699
|
+
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;
|
|
1061
1700
|
var errorExitCode = (error2) => {
|
|
1062
1701
|
switch (error2._tag) {
|
|
1063
1702
|
case "BaselineFailed":
|
|
@@ -1066,6 +1705,7 @@ var errorExitCode = (error2) => {
|
|
|
1066
1705
|
return 5;
|
|
1067
1706
|
case "DiffParseError":
|
|
1068
1707
|
return 6;
|
|
1708
|
+
case "ProgramLoadError":
|
|
1069
1709
|
case "UsageError":
|
|
1070
1710
|
case "ShowHelp":
|
|
1071
1711
|
case "InvalidValue":
|
|
@@ -1079,39 +1719,117 @@ var errorExitCode = (error2) => {
|
|
|
1079
1719
|
|
|
1080
1720
|
// packages/cli/src/Reporter.ts
|
|
1081
1721
|
import * as Clock2 from "effect/Clock";
|
|
1082
|
-
import * as
|
|
1083
|
-
import * as
|
|
1084
|
-
import * as
|
|
1722
|
+
import * as Console2 from "effect/Console";
|
|
1723
|
+
import * as Effect7 from "effect/Effect";
|
|
1724
|
+
import * as FileSystem7 from "effect/FileSystem";
|
|
1085
1725
|
import * as Layer4 from "effect/Layer";
|
|
1086
|
-
import * as
|
|
1087
|
-
import * as
|
|
1726
|
+
import * as Path9 from "effect/Path";
|
|
1727
|
+
import * as Schema9 from "effect/Schema";
|
|
1088
1728
|
import * as Semaphore from "effect/Semaphore";
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
var
|
|
1729
|
+
|
|
1730
|
+
// packages/cli/src/UnifiedDiff.ts
|
|
1731
|
+
var shortestEdits = (before, after) => {
|
|
1732
|
+
const frontier = /* @__PURE__ */ new Map([[1, 0]]);
|
|
1733
|
+
const trace = [];
|
|
1734
|
+
for (let distance = 0; distance <= before.length + after.length; distance++) {
|
|
1735
|
+
trace.push(new Map(frontier));
|
|
1736
|
+
for (let diagonal = -distance; diagonal <= distance; diagonal += 2) {
|
|
1737
|
+
const down = diagonal === -distance || diagonal !== distance && (frontier.get(diagonal - 1) ?? -Infinity) < (frontier.get(diagonal + 1) ?? -Infinity);
|
|
1738
|
+
let x = down ? frontier.get(diagonal + 1) ?? 0 : (frontier.get(diagonal - 1) ?? 0) + 1;
|
|
1739
|
+
let y = x - diagonal;
|
|
1740
|
+
while (x < before.length && y < after.length && before[x] === after[y]) {
|
|
1741
|
+
x++;
|
|
1742
|
+
y++;
|
|
1743
|
+
}
|
|
1744
|
+
frontier.set(diagonal, x);
|
|
1745
|
+
if (x < before.length || y < after.length) continue;
|
|
1746
|
+
const result2 = [];
|
|
1747
|
+
x = before.length;
|
|
1748
|
+
y = after.length;
|
|
1749
|
+
for (let depth = trace.length - 1; depth >= 0; depth--) {
|
|
1750
|
+
const previous = trace[depth];
|
|
1751
|
+
const k = x - y;
|
|
1752
|
+
const down2 = k === -depth || k !== depth && (previous.get(k - 1) ?? -Infinity) < (previous.get(k + 1) ?? -Infinity);
|
|
1753
|
+
const previousK = down2 ? k + 1 : k - 1;
|
|
1754
|
+
const previousX = previous.get(previousK) ?? 0;
|
|
1755
|
+
const previousY = previousX - previousK;
|
|
1756
|
+
while (x > previousX && y > previousY) {
|
|
1757
|
+
result2.push({ sign: " ", text: before[--x] });
|
|
1758
|
+
y--;
|
|
1759
|
+
}
|
|
1760
|
+
if (depth === 0) break;
|
|
1761
|
+
if (x === previousX) result2.push({ sign: "+", text: after[--y] });
|
|
1762
|
+
else result2.push({ sign: "-", text: before[--x] });
|
|
1763
|
+
}
|
|
1764
|
+
return result2.reverse();
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
return [];
|
|
1768
|
+
};
|
|
1769
|
+
var edits = (before, after) => {
|
|
1770
|
+
let prefix = 0;
|
|
1771
|
+
while (prefix < before.length && prefix < after.length && before[prefix] === after[prefix]) prefix++;
|
|
1772
|
+
let suffix = 0;
|
|
1773
|
+
while (suffix < before.length - prefix && suffix < after.length - prefix && before[before.length - suffix - 1] === after[after.length - suffix - 1]) suffix++;
|
|
1774
|
+
const left = before.slice(prefix, before.length - suffix);
|
|
1775
|
+
const right = after.slice(prefix, after.length - suffix);
|
|
1776
|
+
const shared = new Set(left);
|
|
1777
|
+
const middle = right.some((text) => shared.has(text)) ? shortestEdits(left, right) : [...left.map((text) => ({ sign: "-", text })), ...right.map((text) => ({ sign: "+", text }))];
|
|
1778
|
+
return [
|
|
1779
|
+
...before.slice(0, prefix).map((text) => ({ sign: " ", text })),
|
|
1780
|
+
...middle,
|
|
1781
|
+
...before.slice(before.length - suffix).map((text) => ({ sign: " ", text }))
|
|
1782
|
+
];
|
|
1783
|
+
};
|
|
1784
|
+
var lines = (text) => {
|
|
1785
|
+
if (!text) return [];
|
|
1786
|
+
const result2 = text.split("\n");
|
|
1787
|
+
if (text.endsWith("\n")) result2.pop();
|
|
1788
|
+
else result2[result2.length - 1] += "\n\";
|
|
1789
|
+
return result2;
|
|
1790
|
+
};
|
|
1791
|
+
var unifiedDiff = (original, modified, file) => {
|
|
1792
|
+
if (original === modified) return "";
|
|
1793
|
+
const changes = edits(lines(original), lines(modified));
|
|
1794
|
+
const positions = [];
|
|
1795
|
+
let old = 1;
|
|
1796
|
+
let next = 1;
|
|
1797
|
+
for (const edit of changes) {
|
|
1798
|
+
positions.push({ old, next });
|
|
1799
|
+
if (edit.sign !== "+") old++;
|
|
1800
|
+
if (edit.sign !== "-") next++;
|
|
1801
|
+
}
|
|
1802
|
+
const changed = changes.flatMap((edit, index) => edit.sign === " " ? [] : [index]);
|
|
1803
|
+
const quotePath = (path) => /[\s"\\]/.test(path) ? JSON.stringify(path) : path;
|
|
1804
|
+
const output = [`--- ${quotePath(`a/${file}`)}`, `+++ ${quotePath(`b/${file}`)}`];
|
|
1805
|
+
for (let i = 0; i < changed.length; i++) {
|
|
1806
|
+
const start = Math.max(0, changed[i] - 3);
|
|
1807
|
+
let last = changed[i];
|
|
1808
|
+
while (i + 1 < changed.length && changed[i + 1] - last <= 7) last = changed[++i];
|
|
1809
|
+
const hunk = changes.slice(start, last + 4);
|
|
1810
|
+
const oldCount = hunk.filter((edit) => edit.sign !== "+").length;
|
|
1811
|
+
const newCount = hunk.filter((edit) => edit.sign !== "-").length;
|
|
1812
|
+
const position = positions[start];
|
|
1813
|
+
output.push(`@@ -${oldCount ? position.old : position.old - 1},${oldCount} +${newCount ? position.next : position.next - 1},${newCount} @@`, ...hunk.map((edit) => edit.sign + edit.text));
|
|
1814
|
+
}
|
|
1815
|
+
return [...output, ""].join("\n");
|
|
1816
|
+
};
|
|
1817
|
+
|
|
1818
|
+
// packages/cli/src/Reporter.ts
|
|
1819
|
+
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}]`;
|
|
1820
|
+
var shortType = (text) => {
|
|
1821
|
+
const line = text.replace(/\s+/g, " ");
|
|
1822
|
+
return line.length > 80 ? line.slice(0, 79) + "\u2026" : line;
|
|
1823
|
+
};
|
|
1824
|
+
var outcomes = ["caught", "missed", "timeout", "unviable", "untested", "unreliable"];
|
|
1825
|
+
var jsonReport = Schema9.encodeEffect(Schema9.fromJsonString(RunReport));
|
|
1092
1826
|
var logText = (result2) => [
|
|
1093
1827
|
..."output" in result2 && typeof result2.output === "string" ? [result2.output] : [],
|
|
1094
1828
|
...result2.diagnostics
|
|
1095
1829
|
].join("\n");
|
|
1096
|
-
var
|
|
1097
|
-
const
|
|
1098
|
-
const
|
|
1099
|
-
const body = (text, prefix) => {
|
|
1100
|
-
if (text === "") return [];
|
|
1101
|
-
const lines = text.split("\n");
|
|
1102
|
-
if (lines.at(-1) === "") lines.pop();
|
|
1103
|
-
const result2 = lines.map((line) => prefix + line);
|
|
1104
|
-
if (!text.endsWith("\n")) result2.push("\");
|
|
1105
|
-
return result2;
|
|
1106
|
-
};
|
|
1107
|
-
const count = (text) => text === "" ? 0 : text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
|
|
1108
|
-
const oldCount = count(original);
|
|
1109
|
-
const newCount = count(modified);
|
|
1110
|
-
return [`--- a/${mutant.file}`, `+++ b/${mutant.file}`, `@@ -${oldCount === 0 ? 0 : 1},${oldCount} +${newCount === 0 ? 0 : 1},${newCount} @@`, ...body(original, "-"), ...body(modified, "+"), ""].join("\n");
|
|
1111
|
-
};
|
|
1112
|
-
var makeReporter = Effect6.fn("makeReporter")(function* (options) {
|
|
1113
|
-
const fs = yield* FileSystem5.FileSystem;
|
|
1114
|
-
const path = yield* Path7.Path;
|
|
1830
|
+
var makeReporter = Effect7.fn("makeReporter")(function* (options) {
|
|
1831
|
+
const fs = yield* FileSystem7.FileSystem;
|
|
1832
|
+
const path = yield* Path9.Path;
|
|
1115
1833
|
const dir = path.resolve(options.root, options.outDir);
|
|
1116
1834
|
const started = yield* Clock2.currentTimeMillis;
|
|
1117
1835
|
const semaphore = yield* Semaphore.make(1);
|
|
@@ -1124,7 +1842,7 @@ var makeReporter = Effect6.fn("makeReporter")(function* (options) {
|
|
|
1124
1842
|
if (!/^[A-Za-z0-9_-]+$/.test(mutant.id) || ids.has(mutant.id)) return yield* writeError("Mutant ids must be unique safe filenames");
|
|
1125
1843
|
ids.add(mutant.id);
|
|
1126
1844
|
}
|
|
1127
|
-
yield*
|
|
1845
|
+
yield* Effect7.gen(function* () {
|
|
1128
1846
|
const relative2 = path.relative(dir, path.resolve(options.root));
|
|
1129
1847
|
if (relative2 === "" || relative2 !== ".." && !relative2.startsWith(`..${path.sep}`) && !path.isAbsolute(relative2)) {
|
|
1130
1848
|
return yield* new ReportWriteError({ path: dir, message: "Output cannot be the project root or an ancestor" });
|
|
@@ -1139,82 +1857,87 @@ var makeReporter = Effect6.fn("makeReporter")(function* (options) {
|
|
|
1139
1857
|
}
|
|
1140
1858
|
yield* fs.makeDirectory(path.join(dir, "diff"), { recursive: true });
|
|
1141
1859
|
yield* fs.makeDirectory(path.join(dir, "logs"), { recursive: true });
|
|
1142
|
-
}).pipe(
|
|
1143
|
-
const encodedMutants = yield*
|
|
1144
|
-
yield* fs.writeFileString(path.join(dir, "mutants.json"), encodedMutants).pipe(
|
|
1145
|
-
yield*
|
|
1860
|
+
}).pipe(Effect7.mapError(writeError));
|
|
1861
|
+
const encodedMutants = yield* Schema9.encodeEffect(Schema9.fromJsonString(Schema9.Array(Mutant)))(options.mutants).pipe(Effect7.mapError(writeError));
|
|
1862
|
+
yield* fs.writeFileString(path.join(dir, "mutants.json"), encodedMutants).pipe(Effect7.mapError(writeError));
|
|
1863
|
+
yield* fs.writeFileString(path.join(dir, "not-mutated.txt"), (options.notMutated ?? []).map((item) => `${path.relative(options.root, item.file)}: ${item.functionName}: ${item.reason}
|
|
1864
|
+
`).join("")).pipe(Effect7.mapError(writeError));
|
|
1865
|
+
yield* Effect7.forEach(outcomes, (outcome) => fs.writeFileString(path.join(dir, `${outcome}.txt`), ""), { discard: true }).pipe(Effect7.mapError(writeError));
|
|
1146
1866
|
for (const mutant of options.mutants) {
|
|
1147
|
-
const original = yield* fs.readFileString(path.resolve(options.root, mutant.file)).pipe(
|
|
1148
|
-
yield* fs.writeFileString(path.join(dir, "diff", `${mutant.id}.diff`), unifiedDiff(
|
|
1867
|
+
const original = yield* fs.readFileString(path.resolve(options.root, mutant.file)).pipe(Effect7.mapError(writeError));
|
|
1868
|
+
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));
|
|
1149
1869
|
}
|
|
1150
|
-
const writeLists = (items) =>
|
|
1151
|
-
const
|
|
1152
|
-
return fs.writeFileString(path.join(dir, `${outcome}.txt`),
|
|
1870
|
+
const writeLists = (items) => Effect7.forEach(outcomes, (outcome) => {
|
|
1871
|
+
const lines2 = items.filter((result2) => result2.outcome === outcome).map((result2) => mutantLine(result2.mutant, options.root, path));
|
|
1872
|
+
return fs.writeFileString(path.join(dir, `${outcome}.txt`), lines2.length === 0 ? "" : lines2.join("\n") + "\n");
|
|
1153
1873
|
}, { discard: true });
|
|
1154
1874
|
const service = Reporter.of({
|
|
1155
|
-
progress: (result2) => semaphore.withPermit(
|
|
1875
|
+
progress: (result2) => semaphore.withPermit(Effect7.gen(function* () {
|
|
1156
1876
|
results.push(result2);
|
|
1157
|
-
yield*
|
|
1158
|
-
yield*
|
|
1877
|
+
yield* Console2.log(`${result2.outcome} ${mutantLine(result2.mutant, options.root, path)} (${result2.durationMs}ms)`);
|
|
1878
|
+
yield* Effect7.gen(function* () {
|
|
1159
1879
|
if (!ids.has(result2.mutant.id)) return yield* writeError("Progress result does not belong to this report");
|
|
1160
1880
|
yield* writeLists(results);
|
|
1161
1881
|
yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2));
|
|
1162
|
-
}).pipe(
|
|
1882
|
+
}).pipe(Effect7.catch((error2) => Effect7.gen(function* () {
|
|
1163
1883
|
if (pendingError === void 0) {
|
|
1164
1884
|
pendingError = writeError(error2);
|
|
1165
|
-
yield*
|
|
1885
|
+
yield* Console2.warn(`Report write failed: ${pendingError.message}`);
|
|
1166
1886
|
}
|
|
1167
1887
|
})));
|
|
1168
1888
|
})),
|
|
1169
|
-
write: (report) => semaphore.withPermit(
|
|
1889
|
+
write: (report) => semaphore.withPermit(Effect7.gen(function* () {
|
|
1170
1890
|
if (pendingError !== void 0) return yield* pendingError;
|
|
1171
|
-
const encoded = yield* jsonReport(report).pipe(
|
|
1172
|
-
yield* fs.writeFileString(path.join(dir, "outcomes.json.tmp"), encoded).pipe(
|
|
1173
|
-
yield* fs.rename(path.join(dir, "outcomes.json.tmp"), path.join(dir, "outcomes.json")).pipe(
|
|
1174
|
-
yield* writeLists(report.results).pipe(
|
|
1891
|
+
const encoded = yield* jsonReport(report).pipe(Effect7.mapError(writeError));
|
|
1892
|
+
yield* fs.writeFileString(path.join(dir, "outcomes.json.tmp"), encoded).pipe(Effect7.mapError(writeError));
|
|
1893
|
+
yield* fs.rename(path.join(dir, "outcomes.json.tmp"), path.join(dir, "outcomes.json")).pipe(Effect7.mapError(writeError));
|
|
1894
|
+
yield* writeLists(report.results).pipe(Effect7.mapError(writeError));
|
|
1175
1895
|
for (const result2 of report.results) {
|
|
1176
1896
|
if (!ids.has(result2.mutant.id)) return yield* writeError("Final result does not belong to this report");
|
|
1177
|
-
yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2)).pipe(
|
|
1897
|
+
yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2)).pipe(Effect7.mapError(writeError));
|
|
1178
1898
|
}
|
|
1179
1899
|
if (summarized) return;
|
|
1180
1900
|
summarized = true;
|
|
1901
|
+
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.");
|
|
1181
1902
|
const elapsed = (yield* Clock2.currentTimeMillis) - started;
|
|
1182
|
-
yield*
|
|
1903
|
+
yield* Console2.log(outcomes.map((outcome) => `${report.results.filter((result2) => result2.outcome === outcome).length} ${outcome}`).join(", ") + `; ${options.notMutated?.length ?? 0} not mutated; ${(elapsed / 1e3).toFixed(2)}s`);
|
|
1183
1904
|
}))
|
|
1184
1905
|
});
|
|
1185
1906
|
return service;
|
|
1186
1907
|
});
|
|
1187
1908
|
|
|
1188
1909
|
// packages/cli/src/Command.ts
|
|
1189
|
-
var UsageError = class extends
|
|
1910
|
+
var UsageError = class extends Schema10.TaggedError()("UsageError", { message: Schema10.String }) {
|
|
1190
1911
|
};
|
|
1191
1912
|
var flags = {
|
|
1192
|
-
list: Flag.Boolean("list").pipe(Flag.withDefault(false)),
|
|
1193
|
-
inDiff: Flag.String("in-diff").pipe(Flag.optional),
|
|
1194
|
-
include: Flag.String("file").pipe(Flag.atLeast(0)),
|
|
1195
|
-
exclude: Flag.String("exclude").pipe(Flag.atLeast(0)),
|
|
1196
|
-
|
|
1913
|
+
list: Flag.Boolean("list").pipe(Flag.withDefault(false), Flag.withDescription("List mutants and skipped function count without running tests")),
|
|
1914
|
+
inDiff: Flag.String("in-diff").pipe(Flag.optional, Flag.withDescription("Only mutate bodies overlapping this unified diff")),
|
|
1915
|
+
include: Flag.String("file").pipe(Flag.atLeast(0), Flag.withDescription("Include source glob relative to package root; repeatable")),
|
|
1916
|
+
exclude: Flag.String("exclude").pipe(Flag.atLeast(0), Flag.withDescription("Exclude source glob; repeatable")),
|
|
1917
|
+
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")),
|
|
1918
|
+
jobs: Flag.Int("jobs").pipe(Flag.optional, Flag.withDescription("Concurrent scratch/test workers; default 1")),
|
|
1197
1919
|
timeout: Flag.Finite("timeout").pipe(Flag.optional, Flag.withDescription("Absolute test timeout in seconds")),
|
|
1198
|
-
timeoutMultiplier: Flag.Finite("timeout-multiplier").pipe(Flag.optional),
|
|
1920
|
+
timeoutMultiplier: Flag.Finite("timeout-multiplier").pipe(Flag.optional, Flag.withDescription("Baseline duration multiplier; default 5")),
|
|
1199
1921
|
minimumTimeout: Flag.Finite("minimum-test-timeout").pipe(Flag.optional, Flag.withDescription("Minimum test timeout in seconds")),
|
|
1200
|
-
output: Flag.String("output").pipe(Flag.withDefault("mutants.out")),
|
|
1201
|
-
tsconfig: Flag.String("tsconfig").pipe(Flag.withDefault("tsconfig.json"))
|
|
1922
|
+
output: Flag.String("output").pipe(Flag.withDefault("mutants.out"), Flag.withDescription("Report directory; default mutants.out")),
|
|
1923
|
+
tsconfig: Flag.String("tsconfig").pipe(Flag.withDefault("tsconfig.json"), Flag.withDescription("TypeScript project path; default tsconfig.json"))
|
|
1202
1924
|
};
|
|
1203
|
-
var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) =>
|
|
1204
|
-
const fs = yield*
|
|
1205
|
-
const path = yield*
|
|
1925
|
+
var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Effect8.gen(function* () {
|
|
1926
|
+
const fs = yield* FileSystem9.FileSystem;
|
|
1927
|
+
const path = yield* Path11.Path;
|
|
1206
1928
|
const root = path.resolve(options.root);
|
|
1207
1929
|
const configPath = path.join(root, "mutants.config.json");
|
|
1208
1930
|
const fileConfig = (yield* fs.exists(configPath)) ? yield* fs.readFileString(configPath).pipe(
|
|
1209
|
-
|
|
1210
|
-
|
|
1931
|
+
Effect8.flatMap(Schema10.decodeEffect(Schema10.fromJsonString(ConfigFile))),
|
|
1932
|
+
Effect8.mapError((error2) => new UsageError({ message: `Invalid mutants.config.json: ${String(error2)}` }))
|
|
1211
1933
|
) : {};
|
|
1212
1934
|
const timeoutMs = Option.map(input.timeout, (seconds) => Math.ceil(seconds * 1e3));
|
|
1213
1935
|
const inDiff = Option.getOrUndefined(input.inDiff);
|
|
1214
|
-
const config = yield*
|
|
1936
|
+
const config = yield* Schema10.decodeEffect(RunConfig)({
|
|
1215
1937
|
root,
|
|
1216
1938
|
tsconfig: input.tsconfig,
|
|
1217
|
-
|
|
1939
|
+
exportedOnly: input.exportedOnly,
|
|
1940
|
+
include: input.include.length > 0 ? input.include : fileConfig.include ?? ["**/*.{ts,tsx}"],
|
|
1218
1941
|
exclude: input.exclude.length > 0 ? input.exclude : fileConfig.exclude ?? [],
|
|
1219
1942
|
functionFilter: fileConfig.functionFilter ?? [],
|
|
1220
1943
|
...inDiff === void 0 ? {} : { inDiff },
|
|
@@ -1224,33 +1947,46 @@ var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Eff
|
|
|
1224
1947
|
minimumTimeoutMs: Option.match(input.minimumTimeout, { onNone: () => fileConfig.minimumTimeoutMs ?? 2e4, onSome: (seconds) => Math.ceil(seconds * 1e3) }),
|
|
1225
1948
|
neverTimeoutMs: 1e3,
|
|
1226
1949
|
outDir: input.output
|
|
1227
|
-
}).pipe(
|
|
1950
|
+
}).pipe(Effect8.mapError((error2) => new UsageError({ message: String(error2) })));
|
|
1228
1951
|
if (config.jobs < 1 || config.timeoutMultiplier <= 0 || config.minimumTimeoutMs <= 0 || config.timeoutMs !== void 0 && config.timeoutMs <= 0) {
|
|
1229
1952
|
return yield* new UsageError({ message: "Jobs and timeout values must be positive" });
|
|
1230
1953
|
}
|
|
1231
1954
|
const source = yield* MutantSource;
|
|
1232
|
-
const generated = yield*
|
|
1233
|
-
|
|
1955
|
+
const generated = yield* Stream5.runCollect(source.generate(config)).pipe(
|
|
1956
|
+
Effect8.mapError((error2) => error2.reason === "selection" ? new UsageError({ message: error2.diagnostics.join("\n") }) : error2)
|
|
1957
|
+
);
|
|
1958
|
+
const skipped2 = yield* source.notMutated(config);
|
|
1959
|
+
const selected = inDiff === void 0 ? { mutants: generated, notMutated: skipped2 } : yield* selectDiffScope({ root, diffPath: inDiff, mutants: generated, notMutated: skipped2 });
|
|
1960
|
+
const { mutants, notMutated } = selected;
|
|
1234
1961
|
if (input.list) {
|
|
1235
|
-
for (const mutant of mutants) yield*
|
|
1962
|
+
for (const mutant of mutants) yield* Console3.log(mutantLine(mutant, config.root, path));
|
|
1963
|
+
const counts = /* @__PURE__ */ new Map();
|
|
1964
|
+
for (const mutant of mutants) {
|
|
1965
|
+
const file = path.relative(root, path.resolve(root, mutant.file));
|
|
1966
|
+
counts.set(file, (counts.get(file) ?? 0) + 1);
|
|
1967
|
+
}
|
|
1968
|
+
for (const [file, count] of [...counts].sort(([a], [b]) => a.localeCompare(b))) yield* Console3.log(`${file}: ${count} mutants`);
|
|
1969
|
+
yield* Console3.log(`${mutants.length} mutants total; ${notMutated.length} not mutated`);
|
|
1236
1970
|
if (options.onExit !== void 0) yield* options.onExit(0);
|
|
1237
1971
|
return;
|
|
1238
1972
|
}
|
|
1239
|
-
const reporter = yield* makeReporter({ root, outDir: config.outDir, mutants });
|
|
1240
|
-
const report = yield* options.run(config, mutants).pipe(
|
|
1973
|
+
const reporter = yield* makeReporter({ root, outDir: config.outDir, mutants, notMutated });
|
|
1974
|
+
const report = yield* options.run(config, mutants).pipe(Effect8.provideService(Reporter, reporter));
|
|
1241
1975
|
yield* reporter.write(report);
|
|
1242
1976
|
if (options.onExit !== void 0) yield* options.onExit(reportExitCode(report));
|
|
1243
1977
|
}));
|
|
1244
|
-
var runCli =
|
|
1978
|
+
var runCli = Effect8.fn("runCli")(function* (options) {
|
|
1245
1979
|
const code = yield* Ref.make(0);
|
|
1246
1980
|
const command = makeCommand({ ...options, onExit: (value) => Ref.set(code, value) });
|
|
1247
|
-
yield* Command.runWith(command, { version: "0.1.
|
|
1248
|
-
|
|
1249
|
-
yield*
|
|
1981
|
+
yield* Command.runWith(command, { version: "0.1.3" })(options.args).pipe(
|
|
1982
|
+
Effect8.catch((error2) => Effect8.gen(function* () {
|
|
1983
|
+
yield* Console3.error(error2._tag === "ProgramLoadError" ? `${error2.tsconfig}:
|
|
1984
|
+
${error2.diagnostics.join("\n")}` : error2._tag === "BaselineFailed" ? `Baseline failed (${error2.exitCode}): ${error2.command.join(" ")}
|
|
1985
|
+
${error2.output.slice(-8e3)}` : String(error2));
|
|
1250
1986
|
yield* Ref.set(code, errorExitCode(error2));
|
|
1251
1987
|
})),
|
|
1252
|
-
|
|
1253
|
-
yield*
|
|
1988
|
+
Effect8.catchDefect((defect) => Effect8.gen(function* () {
|
|
1989
|
+
yield* Console3.error(`Internal error: ${String(defect)}`);
|
|
1254
1990
|
yield* Ref.set(code, 70);
|
|
1255
1991
|
}))
|
|
1256
1992
|
);
|
|
@@ -1258,15 +1994,15 @@ var runCli = Effect7.fn("runCli")(function* (options) {
|
|
|
1258
1994
|
});
|
|
1259
1995
|
|
|
1260
1996
|
// packages/cli/src/bin.ts
|
|
1261
|
-
var run = (config, mutants) => runMutants(config,
|
|
1997
|
+
var run = (config, mutants) => runMutants(config, Stream6.fromIterable(mutants));
|
|
1262
1998
|
var live = Layer5.mergeAll(MutantSourceLive, ScratchLive, TestRunnerLive).pipe(
|
|
1263
1999
|
Layer5.provideMerge(NodeServices.layer)
|
|
1264
2000
|
);
|
|
1265
|
-
var main =
|
|
2001
|
+
var main = Effect9.gen(function* () {
|
|
1266
2002
|
const code = yield* runCli({ root: process.cwd(), args: process.argv.slice(2), run });
|
|
1267
|
-
yield*
|
|
2003
|
+
yield* Effect9.sync(() => {
|
|
1268
2004
|
process.exitCode = code;
|
|
1269
2005
|
});
|
|
1270
|
-
}).pipe(
|
|
2006
|
+
}).pipe(Effect9.provide(live));
|
|
1271
2007
|
NodeRuntime.runMain(main);
|
|
1272
2008
|
//# sourceMappingURL=bin.js.map
|