mutant-cafe 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +66 -2
- package/dist/bin.js +1272 -0
- package/dist/bin.js.map +7 -0
- package/package.json +35 -4
package/dist/bin.js
ADDED
|
@@ -0,0 +1,1272 @@
|
|
|
1
|
+
#!/usr/bin/env -S node --experimental-strip-types
|
|
2
|
+
|
|
3
|
+
// packages/cli/src/bin.ts
|
|
4
|
+
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
|
5
|
+
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
6
|
+
|
|
7
|
+
// packages/core/src/Config.ts
|
|
8
|
+
import * as Schema from "effect/Schema";
|
|
9
|
+
var RunConfig = Schema.Struct({
|
|
10
|
+
root: Schema.String,
|
|
11
|
+
tsconfig: Schema.String,
|
|
12
|
+
include: Schema.Array(Schema.String),
|
|
13
|
+
exclude: Schema.Array(Schema.String),
|
|
14
|
+
functionFilter: Schema.Array(Schema.String),
|
|
15
|
+
inDiff: Schema.optional(Schema.String),
|
|
16
|
+
jobs: Schema.Int,
|
|
17
|
+
timeoutMs: Schema.optional(Schema.Int),
|
|
18
|
+
timeoutMultiplier: Schema.Finite,
|
|
19
|
+
minimumTimeoutMs: Schema.Int,
|
|
20
|
+
neverTimeoutMs: Schema.Int,
|
|
21
|
+
outDir: Schema.String
|
|
22
|
+
});
|
|
23
|
+
var ConfigFile = Schema.Struct({
|
|
24
|
+
include: Schema.optional(Schema.Array(Schema.String)),
|
|
25
|
+
exclude: Schema.optional(Schema.Array(Schema.String)),
|
|
26
|
+
functionFilter: Schema.optional(Schema.Array(Schema.String)),
|
|
27
|
+
jobs: Schema.optional(Schema.Int),
|
|
28
|
+
timeoutMultiplier: Schema.optional(Schema.Finite),
|
|
29
|
+
minimumTimeoutMs: Schema.optional(Schema.Int)
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// packages/core/src/Errors.ts
|
|
33
|
+
import * as Schema2 from "effect/Schema";
|
|
34
|
+
var ProgramLoadError = class extends Schema2.TaggedError()("ProgramLoadError", {
|
|
35
|
+
tsconfig: Schema2.String,
|
|
36
|
+
diagnostics: Schema2.Array(Schema2.String)
|
|
37
|
+
}) {
|
|
38
|
+
};
|
|
39
|
+
var BaselineFailed = class extends Schema2.TaggedError()("BaselineFailed", {
|
|
40
|
+
exitCode: Schema2.Int,
|
|
41
|
+
output: Schema2.String
|
|
42
|
+
}) {
|
|
43
|
+
};
|
|
44
|
+
var ScratchError = class extends Schema2.TaggedError()("ScratchError", {
|
|
45
|
+
operation: Schema2.String,
|
|
46
|
+
path: Schema2.String,
|
|
47
|
+
message: Schema2.String
|
|
48
|
+
}) {
|
|
49
|
+
};
|
|
50
|
+
var TestSpawnError = class extends Schema2.TaggedError()("TestSpawnError", {
|
|
51
|
+
command: Schema2.Array(Schema2.String),
|
|
52
|
+
message: Schema2.String
|
|
53
|
+
}) {
|
|
54
|
+
};
|
|
55
|
+
var DiffParseError = class extends Schema2.TaggedError()("DiffParseError", {
|
|
56
|
+
path: Schema2.String,
|
|
57
|
+
message: Schema2.String
|
|
58
|
+
}) {
|
|
59
|
+
};
|
|
60
|
+
var ReportWriteError = class extends Schema2.TaggedError()("ReportWriteError", {
|
|
61
|
+
path: Schema2.String,
|
|
62
|
+
message: Schema2.String
|
|
63
|
+
}) {
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// packages/core/src/Mutant.ts
|
|
67
|
+
import * as Schema3 from "effect/Schema";
|
|
68
|
+
var Genre = Schema3.Literals([
|
|
69
|
+
"EffectSucceed",
|
|
70
|
+
"EffectFail",
|
|
71
|
+
"SwallowTag",
|
|
72
|
+
"EffectDie",
|
|
73
|
+
"EffectNever",
|
|
74
|
+
"OptionNone",
|
|
75
|
+
"OptionSome",
|
|
76
|
+
"StreamEmpty",
|
|
77
|
+
"StreamOne",
|
|
78
|
+
"StreamFail",
|
|
79
|
+
"LayerFail",
|
|
80
|
+
"SchemaAcceptAnything",
|
|
81
|
+
"BooleanFlip",
|
|
82
|
+
"LiteralCycle",
|
|
83
|
+
"FnValue"
|
|
84
|
+
]);
|
|
85
|
+
var Span = Schema3.Struct({
|
|
86
|
+
start: Schema3.Struct({ line: Schema3.Int, column: Schema3.Int }),
|
|
87
|
+
end: Schema3.Struct({ line: Schema3.Int, column: Schema3.Int })
|
|
88
|
+
});
|
|
89
|
+
var Replacement = Schema3.Struct({
|
|
90
|
+
startOffset: Schema3.Int,
|
|
91
|
+
endOffset: Schema3.Int,
|
|
92
|
+
text: Schema3.String
|
|
93
|
+
});
|
|
94
|
+
var Mutant = Schema3.Struct({
|
|
95
|
+
id: Schema3.String,
|
|
96
|
+
file: Schema3.String,
|
|
97
|
+
functionName: Schema3.String,
|
|
98
|
+
returnType: Schema3.String,
|
|
99
|
+
genre: Genre,
|
|
100
|
+
description: Schema3.String,
|
|
101
|
+
span: Span,
|
|
102
|
+
replacement: Replacement,
|
|
103
|
+
synthetic: Schema3.Boolean
|
|
104
|
+
});
|
|
105
|
+
var Outcome = Schema3.Literals(["caught", "missed", "unviable", "timeout"]);
|
|
106
|
+
var MutantResult = Schema3.Struct({
|
|
107
|
+
mutant: Mutant,
|
|
108
|
+
outcome: Outcome,
|
|
109
|
+
durationMs: Schema3.Int,
|
|
110
|
+
testCommand: Schema3.Array(Schema3.String),
|
|
111
|
+
diagnostics: Schema3.Array(Schema3.String),
|
|
112
|
+
output: Schema3.optional(Schema3.String)
|
|
113
|
+
});
|
|
114
|
+
var Baseline = Schema3.Struct({
|
|
115
|
+
durationMs: Schema3.Int,
|
|
116
|
+
testCommand: Schema3.Array(Schema3.String)
|
|
117
|
+
});
|
|
118
|
+
var RunReport = Schema3.Struct({
|
|
119
|
+
schemaVersion: Schema3.Literal(1),
|
|
120
|
+
tool: Schema3.Literal("mutant.cafe"),
|
|
121
|
+
root: Schema3.String,
|
|
122
|
+
baseline: Baseline,
|
|
123
|
+
timeoutMs: Schema3.Int,
|
|
124
|
+
results: Schema3.Array(MutantResult)
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
// packages/core/src/Services.ts
|
|
128
|
+
import * as Context from "effect/Context";
|
|
129
|
+
var MutantSource = class extends Context.Service()("mutant.cafe/MutantSource") {
|
|
130
|
+
};
|
|
131
|
+
var Scratch = class extends Context.Service()("mutant.cafe/Scratch") {
|
|
132
|
+
};
|
|
133
|
+
var TestRunner = class extends Context.Service()("mutant.cafe/TestRunner") {
|
|
134
|
+
};
|
|
135
|
+
var Reporter = class extends Context.Service()("mutant.cafe/Reporter") {
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
// packages/engine/src/index.ts
|
|
139
|
+
import * as Effect from "effect/Effect";
|
|
140
|
+
import * as Layer from "effect/Layer";
|
|
141
|
+
import * as Stream from "effect/Stream";
|
|
142
|
+
import * as Schema4 from "effect/Schema";
|
|
143
|
+
|
|
144
|
+
// packages/engine/src/Generate.ts
|
|
145
|
+
import { createHash } from "node:crypto";
|
|
146
|
+
function* generateFunction(fn7) {
|
|
147
|
+
const api = fn7.api;
|
|
148
|
+
const candidate = (genre, expression, value = { text: "", synthetic: false }, description = expression) => {
|
|
149
|
+
const text = fn7.block ? `{ return ${fn7.generator ? "yield* " : ""}${expression}; }` : `(${expression})`;
|
|
150
|
+
return makeMutant(fn7, genre, text, value.synthetic, description);
|
|
151
|
+
};
|
|
152
|
+
const shape = fn7.shape;
|
|
153
|
+
switch (shape.kind) {
|
|
154
|
+
case "Effect": {
|
|
155
|
+
const succeed2 = api("Effect", "succeed");
|
|
156
|
+
if (succeed2) {
|
|
157
|
+
for (const value of shape.values) yield candidate("EffectSucceed", `${succeed2}(${value.text})`, value);
|
|
158
|
+
}
|
|
159
|
+
const fail4 = api("Effect", "fail");
|
|
160
|
+
const catchTag2 = api("Effect", "catchTag");
|
|
161
|
+
for (const error2 of shape.errors) {
|
|
162
|
+
if (fail4) yield candidate("EffectFail", `${fail4}(${error2.text})`, error2);
|
|
163
|
+
const value = shape.values[0];
|
|
164
|
+
const die3 = api("Effect", "die");
|
|
165
|
+
const recovery = value && succeed2 ? `${succeed2}(${value.text})` : die3 ? `${die3}(${JSON.stringify(`mutant.cafe: swallowed ${error2.tag}`)})` : void 0;
|
|
166
|
+
if (catchTag2 && recovery) {
|
|
167
|
+
const gen7 = api("Effect", "gen");
|
|
168
|
+
const original = fn7.generator ? gen7 && `((): ${fn7.returnType} => ${gen7}(function* () ${fn7.original}))()` : fn7.block ? `((): ${fn7.returnType} => ${fn7.original})()` : `((): ${fn7.returnType} => (${fn7.original}))()`;
|
|
169
|
+
if (original) yield candidate("SwallowTag", `${original}.pipe(${catchTag2}(${JSON.stringify(error2.tag)}, () => ${recovery}))`, value, `body.pipe(${catchTag2}(${JSON.stringify(error2.tag)}, () => ${recovery}))`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const die2 = api("Effect", "die");
|
|
173
|
+
if (die2) yield candidate("EffectDie", `${die2}("mutant.cafe")`);
|
|
174
|
+
const never = api("Effect", "never");
|
|
175
|
+
if (never) yield candidate("EffectNever", never);
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
case "Option": {
|
|
179
|
+
const none = api("Option", "none");
|
|
180
|
+
const some = api("Option", "some");
|
|
181
|
+
if (none) yield candidate("OptionNone", `${none}()`);
|
|
182
|
+
if (some) for (const value of shape.values) yield candidate("OptionSome", `${some}(${value.text})`, value);
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
case "Stream": {
|
|
186
|
+
const empty = api("Stream", "empty");
|
|
187
|
+
const make6 = api("Stream", "make");
|
|
188
|
+
const fail4 = api("Stream", "fail");
|
|
189
|
+
if (empty) yield candidate("StreamEmpty", empty);
|
|
190
|
+
if (make6) for (const value of shape.values) yield candidate("StreamOne", `${make6}(${value.text})`, value);
|
|
191
|
+
if (fail4) for (const error2 of shape.errors) yield candidate("StreamFail", `${fail4}(${error2.text})`, error2);
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
case "Layer": {
|
|
195
|
+
const layer2 = api("Layer", "effect");
|
|
196
|
+
const fail4 = api("Effect", "fail");
|
|
197
|
+
if (layer2 && fail4 && shape.service) {
|
|
198
|
+
for (const error2 of shape.errors) yield candidate("LayerFail", `${layer2}(${shape.service}, ${fail4}(${error2.text}))`, error2);
|
|
199
|
+
}
|
|
200
|
+
break;
|
|
201
|
+
}
|
|
202
|
+
case "Void":
|
|
203
|
+
yield makeMutant(fn7, "FnValue", "{}", false, "an empty body");
|
|
204
|
+
break;
|
|
205
|
+
default: {
|
|
206
|
+
const genre = shape.kind === "Boolean" ? "BooleanFlip" : shape.kind === "Literal" ? "LiteralCycle" : "FnValue";
|
|
207
|
+
for (const value of shape.values) {
|
|
208
|
+
if (shape.kind === "Literal" && value.text === fn7.literal) continue;
|
|
209
|
+
yield candidate(genre, value.text, value);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
function makeMutant(fn7, genre, text, synthetic, description) {
|
|
215
|
+
const replacement = { startOffset: fn7.startOffset, endOffset: fn7.endOffset, text };
|
|
216
|
+
const id = createHash("sha256").update(JSON.stringify([fn7.file, fn7.span, genre, text])).digest("hex").slice(0, 24);
|
|
217
|
+
return {
|
|
218
|
+
id,
|
|
219
|
+
file: fn7.file,
|
|
220
|
+
functionName: fn7.name,
|
|
221
|
+
returnType: fn7.returnType,
|
|
222
|
+
genre,
|
|
223
|
+
description: `replace ${fn7.name} -> ${fn7.returnType} with ${description}`,
|
|
224
|
+
span: fn7.span,
|
|
225
|
+
replacement,
|
|
226
|
+
synthetic
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// packages/engine/src/TypeScriptOracle.ts
|
|
231
|
+
import { dirname, resolve, relative, matchesGlob } from "node:path";
|
|
232
|
+
import ts from "typescript";
|
|
233
|
+
var diagnosticsText = (items) => items.map((d) => {
|
|
234
|
+
const message = ts.flattenDiagnosticMessageText(d.messageText, "\n");
|
|
235
|
+
if (!d.file || d.start === void 0) return `TS${d.code}: ${message}`;
|
|
236
|
+
const position = d.file.getLineAndCharacterOfPosition(d.start);
|
|
237
|
+
return `${d.file.fileName}:${position.line + 1}:${position.character + 1} TS${d.code}: ${message}`;
|
|
238
|
+
});
|
|
239
|
+
var ProgramSession = class {
|
|
240
|
+
host;
|
|
241
|
+
originals = /* @__PURE__ */ new Map();
|
|
242
|
+
program;
|
|
243
|
+
overlay;
|
|
244
|
+
configPath;
|
|
245
|
+
constructor(configPath) {
|
|
246
|
+
this.configPath = configPath;
|
|
247
|
+
const config = ts.readConfigFile(configPath, ts.sys.readFile);
|
|
248
|
+
if (config.error) throw new ProgramLoadError({ tsconfig: configPath, diagnostics: diagnosticsText([config.error]) });
|
|
249
|
+
const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, resolve(configPath, ".."));
|
|
250
|
+
if (parsed.errors.length) throw new ProgramLoadError({ tsconfig: configPath, diagnostics: diagnosticsText(parsed.errors) });
|
|
251
|
+
this.host = ts.createCompilerHost(parsed.options, true);
|
|
252
|
+
const read = this.host.getSourceFile;
|
|
253
|
+
this.host.getSourceFile = (file, languageVersion, onError, shouldCreateNewSourceFile) => {
|
|
254
|
+
const absolute = resolve(file);
|
|
255
|
+
if (this.overlay?.file === absolute) return ts.createSourceFile(file, this.overlay.text, languageVersion, true);
|
|
256
|
+
const cached = this.originals.get(absolute);
|
|
257
|
+
if (cached) return cached;
|
|
258
|
+
const source = read(file, languageVersion, onError, shouldCreateNewSourceFile);
|
|
259
|
+
if (source) this.originals.set(absolute, source);
|
|
260
|
+
return source;
|
|
261
|
+
};
|
|
262
|
+
this.program = ts.createProgram(parsed.fileNames, parsed.options, this.host);
|
|
263
|
+
const errors = [...this.program.getOptionsDiagnostics(), ...this.program.getSyntacticDiagnostics()];
|
|
264
|
+
if (errors.length) throw new ProgramLoadError({ tsconfig: configPath, diagnostics: diagnosticsText(errors) });
|
|
265
|
+
}
|
|
266
|
+
check(mutant) {
|
|
267
|
+
const file = resolve(mutant.file);
|
|
268
|
+
const source = this.originals.get(file);
|
|
269
|
+
if (!source) throw new ProgramLoadError({ tsconfig: this.configPath, diagnostics: [`File not loaded: ${mutant.file}`] });
|
|
270
|
+
const { startOffset, endOffset, text } = mutant.replacement;
|
|
271
|
+
if (startOffset < 0 || endOffset < startOffset || endOffset > source.text.length) {
|
|
272
|
+
return { viable: false, diagnostics: ["Replacement offsets are outside the original file"] };
|
|
273
|
+
}
|
|
274
|
+
this.overlay = { file, text: source.text.slice(0, startOffset) + text + source.text.slice(endOffset) };
|
|
275
|
+
try {
|
|
276
|
+
const mutated = ts.createProgram({ rootNames: this.program.getRootFileNames(), options: this.program.getCompilerOptions(), host: this.host, oldProgram: this.program });
|
|
277
|
+
const changed = mutated.getSourceFile(file);
|
|
278
|
+
if (!changed) throw new Error(`Mutated source not found: ${file}`);
|
|
279
|
+
const diagnostics = [...mutated.getSyntacticDiagnostics(changed), ...mutated.getSemanticDiagnostics(changed)];
|
|
280
|
+
return { viable: diagnostics.length === 0, diagnostics: diagnosticsText(diagnostics) };
|
|
281
|
+
} finally {
|
|
282
|
+
this.overlay = void 0;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
function makeTypeScriptOracle() {
|
|
287
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
288
|
+
const owners = /* @__PURE__ */ new Map();
|
|
289
|
+
return {
|
|
290
|
+
*discover(config) {
|
|
291
|
+
const configPath = resolve(config.root, config.tsconfig);
|
|
292
|
+
let session = sessions.get(configPath);
|
|
293
|
+
if (!session) {
|
|
294
|
+
session = new ProgramSession(configPath);
|
|
295
|
+
sessions.set(configPath, session);
|
|
296
|
+
}
|
|
297
|
+
const checker = session.program.getTypeChecker();
|
|
298
|
+
for (const source of session.program.getSourceFiles()) {
|
|
299
|
+
const file = resolve(source.fileName);
|
|
300
|
+
const local = relative(config.root, file).replaceAll("\\", "/");
|
|
301
|
+
const project = relative(dirname(configPath), file).replaceAll("\\", "/");
|
|
302
|
+
if (source.isDeclarationFile || local.startsWith("../") || /(?:^|\/)(?:node_modules|__tests__|__mocks__|tests?)\//.test(project) || /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(local)) continue;
|
|
303
|
+
if (config.include.length && !config.include.some((glob) => matchesGlob(local, glob))) continue;
|
|
304
|
+
if (config.exclude.some((glob) => matchesGlob(local, glob))) continue;
|
|
305
|
+
owners.set(file, session);
|
|
306
|
+
const api = imports(source);
|
|
307
|
+
const visit = (node) => {
|
|
308
|
+
if (isFunction(node) && node.body && mutable(node, checker) && !skipped(node)) {
|
|
309
|
+
const name = functionName(node);
|
|
310
|
+
if (!config.functionFilter.length || config.functionFilter.some((filter) => matchesGlob(name, filter))) {
|
|
311
|
+
const signature = checker.getSignatureFromDeclaration(node);
|
|
312
|
+
if (signature) {
|
|
313
|
+
const wrapped = wrappedEffect(node, checker);
|
|
314
|
+
const type = wrapped ?? checker.getReturnTypeOfSignature(signature);
|
|
315
|
+
const generator = wrapped && ts.isFunctionExpression(node) ? node : generatorBody(node, checker);
|
|
316
|
+
const body = generator?.body ?? node.body;
|
|
317
|
+
const start = body.getStart(source);
|
|
318
|
+
const end = body.getEnd();
|
|
319
|
+
const a = source.getLineAndCharacterOfPosition(start);
|
|
320
|
+
const b = source.getLineAndCharacterOfPosition(end);
|
|
321
|
+
found.push({
|
|
322
|
+
file,
|
|
323
|
+
name,
|
|
324
|
+
returnType: checker.typeToString(type, node, ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope | ts.TypeFormatFlags.NoTruncation),
|
|
325
|
+
span: { start: { line: a.line + 1, column: a.character + 1 }, end: { line: b.line + 1, column: b.character + 1 } },
|
|
326
|
+
startOffset: start,
|
|
327
|
+
endOffset: end,
|
|
328
|
+
original: body.getText(source),
|
|
329
|
+
literal: literalOfBody(body, checker),
|
|
330
|
+
block: ts.isBlock(body),
|
|
331
|
+
generator: generator !== void 0,
|
|
332
|
+
shape: shapeOf(type, checker, node, body),
|
|
333
|
+
api
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
ts.forEachChild(node, visit);
|
|
340
|
+
};
|
|
341
|
+
const found = [];
|
|
342
|
+
visit(source);
|
|
343
|
+
yield* found;
|
|
344
|
+
}
|
|
345
|
+
},
|
|
346
|
+
checkViable(mutant) {
|
|
347
|
+
const session = owners.get(resolve(mutant.file));
|
|
348
|
+
if (!session) throw new ProgramLoadError({ tsconfig: "", diagnostics: ["Generate mutants before checking viability"] });
|
|
349
|
+
return session.check(mutant);
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
function isFunction(node) {
|
|
354
|
+
return ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node);
|
|
355
|
+
}
|
|
356
|
+
function exported(node) {
|
|
357
|
+
return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false);
|
|
358
|
+
}
|
|
359
|
+
function mutable(node, checker) {
|
|
360
|
+
if (ts.isMethodDeclaration(node)) return true;
|
|
361
|
+
if (ts.isFunctionDeclaration(node)) return exported(node);
|
|
362
|
+
const wrapper = wrappedEffect(node, checker);
|
|
363
|
+
let current = node;
|
|
364
|
+
if (wrapper) current = node.parent;
|
|
365
|
+
while (ts.isParenthesizedExpression(current.parent)) current = current.parent;
|
|
366
|
+
if (!ts.isVariableDeclaration(current.parent) || current.parent.initializer !== current) return false;
|
|
367
|
+
const statement = current.parent.parent.parent;
|
|
368
|
+
return ts.isVariableStatement(statement) && exported(statement);
|
|
369
|
+
}
|
|
370
|
+
function skipped(node) {
|
|
371
|
+
let current = node;
|
|
372
|
+
while (!ts.isSourceFile(current)) {
|
|
373
|
+
if (ts.getJSDocTags(current).some((tag) => tag.tagName.text === "mutants-skip")) return true;
|
|
374
|
+
current = current.parent;
|
|
375
|
+
}
|
|
376
|
+
return false;
|
|
377
|
+
}
|
|
378
|
+
function functionName(node) {
|
|
379
|
+
if (node.name) {
|
|
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
|
+
}
|
|
383
|
+
let current = node;
|
|
384
|
+
while (!ts.isSourceFile(current)) {
|
|
385
|
+
if (ts.isVariableDeclaration(current)) return current.name.getText();
|
|
386
|
+
current = current.parent;
|
|
387
|
+
}
|
|
388
|
+
return "default";
|
|
389
|
+
}
|
|
390
|
+
function wrappedEffect(node, checker) {
|
|
391
|
+
if (!ts.isFunctionExpression(node) || !node.asteriskToken || !ts.isCallExpression(node.parent)) return void 0;
|
|
392
|
+
const result2 = checker.getTypeAtLocation(node.parent);
|
|
393
|
+
if (family(result2, checker)?.kind === "Effect") return result2;
|
|
394
|
+
const signature = result2.getCallSignatures()[0];
|
|
395
|
+
if (!signature) return void 0;
|
|
396
|
+
const returned = checker.getReturnTypeOfSignature(signature);
|
|
397
|
+
return family(returned, checker)?.kind === "Effect" ? returned : void 0;
|
|
398
|
+
}
|
|
399
|
+
function literalOfBody(body, checker) {
|
|
400
|
+
const first = ts.isBlock(body) && body.statements.length === 1 ? body.statements[0] : void 0;
|
|
401
|
+
const expression = ts.isBlock(body) ? first && ts.isReturnStatement(first) ? first.expression : void 0 : body;
|
|
402
|
+
if (!expression) return void 0;
|
|
403
|
+
const type = checker.getTypeAtLocation(expression);
|
|
404
|
+
return type.isStringLiteral() ? JSON.stringify(type.value) : type.isNumberLiteral() ? String(type.value) : void 0;
|
|
405
|
+
}
|
|
406
|
+
function generatorBody(node, checker) {
|
|
407
|
+
if (!node.body) return void 0;
|
|
408
|
+
const expression = ts.isBlock(node.body) ? node.body.statements.length === 1 && ts.isReturnStatement(node.body.statements[0]) ? node.body.statements[0].expression : void 0 : node.body;
|
|
409
|
+
const signature = checker.getSignatureFromDeclaration(node);
|
|
410
|
+
if (!signature || family(checker.getReturnTypeOfSignature(signature), checker)?.kind !== "Effect") return void 0;
|
|
411
|
+
if (expression && ts.isCallExpression(expression)) {
|
|
412
|
+
return expression.arguments.find((arg) => ts.isFunctionExpression(arg) && arg.asteriskToken !== void 0);
|
|
413
|
+
}
|
|
414
|
+
return void 0;
|
|
415
|
+
}
|
|
416
|
+
function imports(source) {
|
|
417
|
+
const namespaces = /* @__PURE__ */ new Map();
|
|
418
|
+
const named = /* @__PURE__ */ new Map();
|
|
419
|
+
for (const statement of source.statements) {
|
|
420
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || statement.importClause?.isTypeOnly) continue;
|
|
421
|
+
const path = statement.moduleSpecifier.text;
|
|
422
|
+
const bindings = statement.importClause?.namedBindings;
|
|
423
|
+
if (!bindings) continue;
|
|
424
|
+
if (ts.isNamespaceImport(bindings)) {
|
|
425
|
+
if (path.startsWith("effect/")) namespaces.set(path.slice(7), bindings.name.text);
|
|
426
|
+
if (path === "effect") for (const module of ["Effect", "Option", "Stream", "Layer"]) namespaces.set(module, `${bindings.name.text}.${module}`);
|
|
427
|
+
}
|
|
428
|
+
if (ts.isNamedImports(bindings)) for (const binding of bindings.elements) {
|
|
429
|
+
if (binding.isTypeOnly) continue;
|
|
430
|
+
const imported = (binding.propertyName ?? binding.name).text;
|
|
431
|
+
if (path === "effect") namespaces.set(imported, binding.name.text);
|
|
432
|
+
else if (path.startsWith("effect/")) named.set(`${path.slice(7)}.${imported}`, binding.name.text);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return (module, member) => {
|
|
436
|
+
const namespace = namespaces.get(module);
|
|
437
|
+
return namespace ? `${namespace}.${member}` : named.get(`${module}.${member}`);
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
function family(type, checker) {
|
|
441
|
+
const symbol = type.aliasSymbol ?? type.getSymbol();
|
|
442
|
+
const name = symbol?.getName();
|
|
443
|
+
const fromEffect = symbol?.declarations?.some((d) => /(?:^|\/)effect\/(?:.*\/)?(?:Effect|Option|Stream|Layer)\.(?:d\.)?ts$/.test(d.getSourceFile().fileName));
|
|
444
|
+
if (fromEffect && (name === "Effect" || name === "Option" || name === "Stream" || name === "Layer")) {
|
|
445
|
+
const args = type.aliasTypeArguments ?? (type.flags & ts.TypeFlags.Object && type.objectFlags & ts.ObjectFlags.Reference ? checker.getTypeArguments(type) : []);
|
|
446
|
+
return { kind: name, args };
|
|
447
|
+
}
|
|
448
|
+
const direct = type.getSymbol();
|
|
449
|
+
if (direct && direct !== symbol) {
|
|
450
|
+
const name2 = direct.getName();
|
|
451
|
+
if ((name2 === "Effect" || name2 === "Stream" || name2 === "Layer") && direct.declarations?.some((d) => d.getSourceFile().fileName.includes("/effect/"))) {
|
|
452
|
+
return { kind: name2, args: checker.getTypeArguments(type) };
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
if (type.isUnion()) {
|
|
456
|
+
const members = type.types;
|
|
457
|
+
const option = members.every((member) => {
|
|
458
|
+
const symbol2 = member.getSymbol();
|
|
459
|
+
return (symbol2?.name === "Some" || symbol2?.name === "None") && symbol2.declarations?.some((d) => /\/effect\/.*Option\.(?:d\.)?ts$/.test(d.getSourceFile().fileName));
|
|
460
|
+
});
|
|
461
|
+
if (option && members[0]) {
|
|
462
|
+
const first = members.find((m) => m.getSymbol()?.name === "Some") ?? members[0];
|
|
463
|
+
return { kind: "Option", args: checker.getTypeArguments(first) };
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
if (type.flags & ts.TypeFlags.Object && type.objectFlags & (ts.ObjectFlags.Class | ts.ObjectFlags.Interface)) {
|
|
467
|
+
for (const base of checker.getBaseTypes(type) ?? []) {
|
|
468
|
+
const detected = family(base, checker);
|
|
469
|
+
if (detected) return detected;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
return void 0;
|
|
473
|
+
}
|
|
474
|
+
function shapeOf(type, checker, node, body) {
|
|
475
|
+
const detected = family(type, checker);
|
|
476
|
+
if (detected) {
|
|
477
|
+
const [a, e] = detected.args;
|
|
478
|
+
const values = a ? valuesOf(a, checker, node) : [];
|
|
479
|
+
if (detected.kind === "Option") return { kind: "Option", values };
|
|
480
|
+
const errors = e ? taggedValues(e, checker, node) : [];
|
|
481
|
+
if (detected.kind === "Layer") {
|
|
482
|
+
let service;
|
|
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 };
|
|
495
|
+
}
|
|
496
|
+
if (type.flags & ts.TypeFlags.Void) return { kind: "Void", values: [] };
|
|
497
|
+
const members = type.isUnion() ? type.types : [type];
|
|
498
|
+
const boolean = members.every((t) => (t.flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral)) !== 0);
|
|
499
|
+
const literal = members.every((t) => t.isLiteral());
|
|
500
|
+
return { kind: boolean ? "Boolean" : literal ? "Literal" : "Value", values: valuesOf(type, checker, node) };
|
|
501
|
+
}
|
|
502
|
+
function taggedValues(type, checker, location) {
|
|
503
|
+
return (type.isUnion() ? type.types : [type]).flatMap((member) => {
|
|
504
|
+
const tag = member.getProperty("_tag");
|
|
505
|
+
if (!tag) return [];
|
|
506
|
+
const tagType = checker.getTypeOfSymbolAtLocation(tag, location);
|
|
507
|
+
if (!tagType.isStringLiteral()) return [];
|
|
508
|
+
const value = constructError(member, checker, location, tagType.value);
|
|
509
|
+
return [{ ...value, tag: tagType.value }];
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
function constructError(type, checker, location, tag) {
|
|
513
|
+
const symbol = type.getSymbol();
|
|
514
|
+
if (symbol) {
|
|
515
|
+
const visible = checker.getSymbolsInScope(location, ts.SymbolFlags.Value).find((candidate) => {
|
|
516
|
+
const target = candidate.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(candidate) : candidate;
|
|
517
|
+
return target === symbol;
|
|
518
|
+
});
|
|
519
|
+
if (visible) {
|
|
520
|
+
const constructor = checker.getTypeOfSymbolAtLocation(visible, location).getConstructSignatures()[0];
|
|
521
|
+
if (constructor) {
|
|
522
|
+
const param = constructor.parameters[0];
|
|
523
|
+
if (!param) return { text: `new ${visible.name}()`, synthetic: false };
|
|
524
|
+
const fields = checker.getTypeOfSymbolAtLocation(param, location);
|
|
525
|
+
const value = valuesOf(fields, checker, location)[0];
|
|
526
|
+
if (value && !value.synthetic) return { text: `new ${visible.name}(${value.text})`, synthetic: false };
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
return { text: `({ _tag: ${JSON.stringify(tag)} } as unknown as ${checker.typeToString(type, location, ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope)})`, synthetic: true };
|
|
531
|
+
}
|
|
532
|
+
function valuesOf(type, checker, location, depth = 0) {
|
|
533
|
+
if (depth > 4 || type.flags & ts.TypeFlags.Never) return [];
|
|
534
|
+
const value = (text) => ({ text, synthetic: false });
|
|
535
|
+
const detected = family(type, checker);
|
|
536
|
+
if (detected && (detected.kind === "Option" || detected.kind === "Effect")) {
|
|
537
|
+
const api = imports(location.getSourceFile());
|
|
538
|
+
const inner = detected.args[0];
|
|
539
|
+
const values = inner ? valuesOf(inner, checker, location, depth + 1) : [];
|
|
540
|
+
const wrap = api(detected.kind, detected.kind === "Option" ? "some" : "succeed");
|
|
541
|
+
const none = detected.kind === "Option" ? api("Option", "none") : void 0;
|
|
542
|
+
return [
|
|
543
|
+
...none ? [value(`${none}()`)] : [],
|
|
544
|
+
...wrap ? values.map((v) => ({ text: `${wrap}(${v.text})`, synthetic: v.synthetic })) : []
|
|
545
|
+
];
|
|
546
|
+
}
|
|
547
|
+
if (type.isUnion()) return type.types.flatMap((member) => valuesOf(member, checker, location, depth + 1));
|
|
548
|
+
if (type.isStringLiteral()) return [value(JSON.stringify(type.value))];
|
|
549
|
+
if (type.isNumberLiteral()) return [value(String(type.value))];
|
|
550
|
+
if (type.flags & ts.TypeFlags.BooleanLiteral) return [value(checker.typeToString(type))];
|
|
551
|
+
if (type.flags & ts.TypeFlags.Boolean) return [value("true"), value("false")];
|
|
552
|
+
if (type.flags & ts.TypeFlags.String) return [value('""'), value('"xyzzy"')];
|
|
553
|
+
if (type.flags & ts.TypeFlags.Number) return [value("0"), value("1"), value("-1")];
|
|
554
|
+
if (type.flags & ts.TypeFlags.BigInt) return [value("0n"), value("1n")];
|
|
555
|
+
if (type.flags & ts.TypeFlags.Null) return [value("null")];
|
|
556
|
+
if (type.flags & (ts.TypeFlags.Unknown | ts.TypeFlags.Any)) return [value("undefined")];
|
|
557
|
+
if (type.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Void)) return [value("undefined")];
|
|
558
|
+
if (checker.isTupleType(type)) {
|
|
559
|
+
const elements = checker.getTypeArguments(type).map((t) => valuesOf(t, checker, location, depth + 1)[0]);
|
|
560
|
+
return elements.every((v) => v !== void 0) ? [value(`[${elements.map((v) => v.text).join(", ")}]`)] : [];
|
|
561
|
+
}
|
|
562
|
+
if (checker.isArrayType(type) || checker.isArrayLikeType(type)) {
|
|
563
|
+
const element = checker.getIndexTypeOfType(type, ts.IndexKind.Number);
|
|
564
|
+
const elements = element ? valuesOf(element, checker, location, depth + 1) : [];
|
|
565
|
+
return [value("[]"), ...elements.map((v) => ({ text: `[${v.text}]`, synthetic: v.synthetic }))];
|
|
566
|
+
}
|
|
567
|
+
if (type.flags & ts.TypeFlags.Object && !type.getCallSignatures().length && !type.getConstructSignatures().length) {
|
|
568
|
+
const fields = [];
|
|
569
|
+
for (const prop of type.getProperties()) {
|
|
570
|
+
if (prop.flags & ts.SymbolFlags.Optional) continue;
|
|
571
|
+
if (!/^[$\w]+$/.test(prop.name)) return [];
|
|
572
|
+
const first = valuesOf(checker.getTypeOfSymbolAtLocation(prop, location), checker, location, depth + 1)[0];
|
|
573
|
+
if (!first) return [];
|
|
574
|
+
fields.push(`${JSON.stringify(prop.name)}: ${first.text}`);
|
|
575
|
+
}
|
|
576
|
+
return [value(`{ ${fields.join(", ")} }`)];
|
|
577
|
+
}
|
|
578
|
+
return [];
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// packages/engine/src/index.ts
|
|
582
|
+
var MutantSourceLive = Layer.effect(
|
|
583
|
+
MutantSource,
|
|
584
|
+
Effect.sync(() => makeMutantSource(makeTypeScriptOracle()))
|
|
585
|
+
);
|
|
586
|
+
function makeMutantSource(oracle) {
|
|
587
|
+
return {
|
|
588
|
+
generate: (config) => Stream.unwrap(Effect.try({
|
|
589
|
+
try: () => Stream.fromIterable({
|
|
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
|
+
),
|
|
599
|
+
checkViable: (mutant) => Effect.try({
|
|
600
|
+
try: () => oracle.checkViable(mutant),
|
|
601
|
+
catch: (error2) => loadError("", error2)
|
|
602
|
+
})
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
function loadError(tsconfig, error2) {
|
|
606
|
+
return Schema4.is(ProgramLoadError)(error2) ? error2 : new ProgramLoadError({
|
|
607
|
+
tsconfig,
|
|
608
|
+
diagnostics: [error2 instanceof Error ? error2.message : String(error2)]
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// packages/runner/src/Scratch.ts
|
|
613
|
+
import * as Effect2 from "effect/Effect";
|
|
614
|
+
import * as FileSystem from "effect/FileSystem";
|
|
615
|
+
import * as Layer2 from "effect/Layer";
|
|
616
|
+
import * as Path from "effect/Path";
|
|
617
|
+
var ScratchLive = Layer2.effect(Scratch, Effect2.gen(function* () {
|
|
618
|
+
const fs = yield* FileSystem.FileSystem;
|
|
619
|
+
const path = yield* Path.Path;
|
|
620
|
+
const failure = (operation, location, error2) => new ScratchError({ operation, path: location, message: error2.message });
|
|
621
|
+
return Scratch.of({
|
|
622
|
+
acquire: Effect2.fn("Scratch.acquire")(function* (root) {
|
|
623
|
+
const source = path.resolve(root);
|
|
624
|
+
let copyRoot = source;
|
|
625
|
+
let ancestor = source;
|
|
626
|
+
while (true) {
|
|
627
|
+
if ((yield* fs.exists(path.join(ancestor, "pnpm-workspace.yaml"))) || (yield* fs.exists(path.join(ancestor, ".git")))) {
|
|
628
|
+
copyRoot = ancestor;
|
|
629
|
+
break;
|
|
630
|
+
}
|
|
631
|
+
const parent = path.dirname(ancestor);
|
|
632
|
+
if (parent === ancestor) break;
|
|
633
|
+
ancestor = parent;
|
|
634
|
+
}
|
|
635
|
+
const temp = yield* Effect2.acquireRelease(
|
|
636
|
+
fs.makeTempDirectory({ prefix: "mutant-cafe-" }).pipe(
|
|
637
|
+
Effect2.mapError((error2) => failure("create", source, error2))
|
|
638
|
+
),
|
|
639
|
+
(dir2) => fs.remove(dir2, { recursive: true }).pipe(Effect2.orDie)
|
|
640
|
+
);
|
|
641
|
+
const copy = (from, to, ancestors) => Effect2.gen(function* () {
|
|
642
|
+
const real = yield* fs.realPath(from);
|
|
643
|
+
const info = yield* fs.stat(from);
|
|
644
|
+
if (info.type === "Directory") {
|
|
645
|
+
if (ancestors.includes(real)) {
|
|
646
|
+
return yield* Effect2.fail(new ScratchError({ operation: "copy", path: from, message: "Cyclic directory symlink" }));
|
|
647
|
+
}
|
|
648
|
+
yield* fs.makeDirectory(to, { recursive: true });
|
|
649
|
+
const entries = yield* fs.readDirectory(from);
|
|
650
|
+
for (const entry of entries) {
|
|
651
|
+
if ([".git", "mutants.out", ".agent_sources", ".agent-sources", ".brain", ".pi", ".rift"].includes(entry)) continue;
|
|
652
|
+
const src = path.join(from, entry);
|
|
653
|
+
const dest = path.join(to, entry);
|
|
654
|
+
if (entry === "node_modules") {
|
|
655
|
+
yield* fs.symlink(path.resolve(src), dest);
|
|
656
|
+
} else {
|
|
657
|
+
yield* copy(src, dest, [...ancestors, real]);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
} else if (info.type === "File") {
|
|
661
|
+
yield* fs.copyFile(from, to);
|
|
662
|
+
}
|
|
663
|
+
}).pipe(Effect2.mapError((error2) => failure("copy", from, error2)));
|
|
664
|
+
yield* copy(copyRoot, temp, []);
|
|
665
|
+
const packageRoot = yield* fs.realPath(path.join(temp, path.relative(copyRoot, source))).pipe(
|
|
666
|
+
Effect2.mapError((error2) => failure("resolve", source, error2))
|
|
667
|
+
);
|
|
668
|
+
const originals = /* @__PURE__ */ new Map();
|
|
669
|
+
const target = (mutant) => Effect2.gen(function* () {
|
|
670
|
+
const relative2 = path.isAbsolute(mutant.file) ? path.relative(source, mutant.file) : mutant.file;
|
|
671
|
+
const location = path.resolve(packageRoot, relative2);
|
|
672
|
+
const rel = path.relative(packageRoot, location);
|
|
673
|
+
if (rel === "" || rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel) || rel.split(path.sep).includes("node_modules")) {
|
|
674
|
+
return yield* Effect2.fail(new ScratchError({ operation: "resolve", path: mutant.file, message: "Mutant file must be inside the copied source tree" }));
|
|
675
|
+
}
|
|
676
|
+
const real = yield* fs.realPath(location).pipe(Effect2.mapError((error2) => failure("resolve", location, error2)));
|
|
677
|
+
const realRelative = path.relative(packageRoot, real);
|
|
678
|
+
if (realRelative === ".." || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative)) {
|
|
679
|
+
return yield* Effect2.fail(new ScratchError({ operation: "resolve", path: mutant.file, message: "Mutant file resolves outside the scratch package" }));
|
|
680
|
+
}
|
|
681
|
+
return location;
|
|
682
|
+
});
|
|
683
|
+
const dir = {
|
|
684
|
+
path: packageRoot,
|
|
685
|
+
apply: Effect2.fn("Scratch.apply")(function* (mutant) {
|
|
686
|
+
const location = yield* target(mutant);
|
|
687
|
+
const bytes = yield* fs.readFile(location);
|
|
688
|
+
originals.set(location, bytes);
|
|
689
|
+
const original = new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes);
|
|
690
|
+
const { startOffset, endOffset, text } = mutant.replacement;
|
|
691
|
+
if (startOffset < 0 || endOffset < startOffset || endOffset > original.length) {
|
|
692
|
+
return yield* Effect2.fail(new ScratchError({ operation: "apply", path: location, message: "Replacement offsets are outside the file" }));
|
|
693
|
+
}
|
|
694
|
+
yield* fs.writeFileString(location, original.slice(0, startOffset) + text + original.slice(endOffset));
|
|
695
|
+
}, (effect5, mutant) => effect5.pipe(Effect2.mapError((error2) => failure("apply", mutant.file, error2)))),
|
|
696
|
+
revert: Effect2.fn("Scratch.revert")(function* (mutant) {
|
|
697
|
+
const location = yield* target(mutant);
|
|
698
|
+
const bytes = originals.get(location);
|
|
699
|
+
if (bytes !== void 0) {
|
|
700
|
+
yield* fs.writeFile(location, bytes);
|
|
701
|
+
originals.delete(location);
|
|
702
|
+
}
|
|
703
|
+
}, (effect5, mutant) => effect5.pipe(Effect2.mapError((error2) => failure("revert", mutant.file, error2))))
|
|
704
|
+
};
|
|
705
|
+
return dir;
|
|
706
|
+
}, (effect5, root) => effect5.pipe(Effect2.mapError((error2) => error2._tag === "ScratchError" ? error2 : failure("acquire", root, error2))))
|
|
707
|
+
});
|
|
708
|
+
}));
|
|
709
|
+
|
|
710
|
+
// packages/runner/src/TestRunner.ts
|
|
711
|
+
import * as Clock from "effect/Clock";
|
|
712
|
+
import * as Effect3 from "effect/Effect";
|
|
713
|
+
import * as Layer3 from "effect/Layer";
|
|
714
|
+
import * as Stream2 from "effect/Stream";
|
|
715
|
+
import * as ChildProcess from "effect/process/ChildProcess";
|
|
716
|
+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
|
|
717
|
+
var TestRunnerLive = Layer3.effect(TestRunner, Effect3.gen(function* () {
|
|
718
|
+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
|
719
|
+
const execute = Effect3.fn("TestRunner.execute")(function* (dir, args, timeoutMs) {
|
|
720
|
+
const command = ["npx", "--no", "vitest", ...args, "--no-cache", "--no-fsModuleCache"];
|
|
721
|
+
const started = yield* Clock.currentTimeMillis;
|
|
722
|
+
const chunks = [];
|
|
723
|
+
let exitCode = 1;
|
|
724
|
+
const child = Effect3.scoped(Effect3.gen(function* () {
|
|
725
|
+
const handle = yield* spawner.spawn(ChildProcess.make(command[0], command.slice(1), {
|
|
726
|
+
cwd: dir.path,
|
|
727
|
+
// Node's scoped spawner kills the detached process group, not just pnpm.
|
|
728
|
+
detached: true,
|
|
729
|
+
killSignal: "SIGKILL",
|
|
730
|
+
forceKillAfter: "100 millis",
|
|
731
|
+
stdin: "ignore"
|
|
732
|
+
}));
|
|
733
|
+
const collect = handle.all.pipe(Stream2.decodeText(), Stream2.runForEach((chunk) => Effect3.sync(() => {
|
|
734
|
+
chunks.push(chunk);
|
|
735
|
+
})));
|
|
736
|
+
const [code] = yield* Effect3.all([handle.exitCode, collect], { concurrency: "unbounded" });
|
|
737
|
+
exitCode = code;
|
|
738
|
+
return code === 0 ? "passed" : "failed";
|
|
739
|
+
}));
|
|
740
|
+
const status = yield* (timeoutMs === void 0 ? child : child.pipe(
|
|
741
|
+
Effect3.timeout(timeoutMs),
|
|
742
|
+
Effect3.catchTag("TimeoutError", () => Effect3.succeed("timedOut"))
|
|
743
|
+
)).pipe(Effect3.mapError((error2) => new TestSpawnError({ command, message: error2.message })));
|
|
744
|
+
const ended = yield* Clock.currentTimeMillis;
|
|
745
|
+
const run2 = { status, durationMs: ended - started, command, output: chunks.join("") };
|
|
746
|
+
return { ...run2, exitCode };
|
|
747
|
+
});
|
|
748
|
+
return TestRunner.of({
|
|
749
|
+
baseline: Effect3.fn("TestRunner.baseline")(function* (dir) {
|
|
750
|
+
const run2 = yield* execute(dir, ["run"]);
|
|
751
|
+
if (run2.status !== "passed") {
|
|
752
|
+
return yield* Effect3.fail(new BaselineFailed({ exitCode: run2.exitCode, output: run2.output }));
|
|
753
|
+
}
|
|
754
|
+
return { durationMs: run2.durationMs, testCommand: run2.command };
|
|
755
|
+
}),
|
|
756
|
+
runRelated: Effect3.fn("TestRunner.runRelated")((dir, file, timeoutMs) => execute(dir, ["related", file, "--run", "--passWithNoTests"], timeoutMs))
|
|
757
|
+
});
|
|
758
|
+
}));
|
|
759
|
+
|
|
760
|
+
// packages/runner/src/Run.ts
|
|
761
|
+
import { createEffectActor, createEffectLogic, join, send, setupEffect } from "@xstate/effect";
|
|
762
|
+
import { types } from "xstate";
|
|
763
|
+
import * as Effect4 from "effect/Effect";
|
|
764
|
+
import * as Pool from "effect/Pool";
|
|
765
|
+
import * as Path3 from "effect/Path";
|
|
766
|
+
import * as Result from "effect/Result";
|
|
767
|
+
import * as Schema5 from "effect/Schema";
|
|
768
|
+
import * as Scope from "effect/Scope";
|
|
769
|
+
import * as Stream3 from "effect/Stream";
|
|
770
|
+
var ScratchPool = class {
|
|
771
|
+
value;
|
|
772
|
+
constructor(value) {
|
|
773
|
+
this.value = value;
|
|
774
|
+
}
|
|
775
|
+
};
|
|
776
|
+
var runMutants = Effect4.fn("Runner.runMutants")(function* (config, mutants) {
|
|
777
|
+
const scratch = yield* Scratch;
|
|
778
|
+
const tests = yield* TestRunner;
|
|
779
|
+
const source = yield* MutantSource;
|
|
780
|
+
const reporter = yield* Reporter;
|
|
781
|
+
const scope = yield* Scope.Scope;
|
|
782
|
+
const path = yield* Path3.Path;
|
|
783
|
+
const jobs = Math.max(1, Math.floor(config.jobs));
|
|
784
|
+
const report = (state2) => ({
|
|
785
|
+
schemaVersion: 1,
|
|
786
|
+
tool: "mutant.cafe",
|
|
787
|
+
root: config.root,
|
|
788
|
+
baseline: state2.baseline,
|
|
789
|
+
timeoutMs: state2.timeoutMs,
|
|
790
|
+
results: state2.results
|
|
791
|
+
});
|
|
792
|
+
const capture = (effect5) => Effect4.result(effect5);
|
|
793
|
+
const copying = createEffectLogic(() => capture(Effect4.gen(function* () {
|
|
794
|
+
const pool = yield* Pool.make({ acquire: scratch.acquire(config.root), size: jobs }).pipe(
|
|
795
|
+
Effect4.provideService(Scope.Scope, scope)
|
|
796
|
+
);
|
|
797
|
+
yield* Effect4.scoped(Pool.get(pool));
|
|
798
|
+
return new ScratchPool(pool);
|
|
799
|
+
})));
|
|
800
|
+
const baselining = createEffectLogic(({ input }) => capture(Effect4.gen(function* () {
|
|
801
|
+
if (input === void 0) return yield* Effect4.die("Missing scratch pool");
|
|
802
|
+
const baseline = yield* Effect4.scoped(Effect4.gen(function* () {
|
|
803
|
+
const dir = yield* Pool.get(input.value);
|
|
804
|
+
return yield* tests.baseline(dir);
|
|
805
|
+
}));
|
|
806
|
+
return { baseline, timeoutMs: config.timeoutMs ?? Math.max(config.minimumTimeoutMs, Math.ceil(config.timeoutMultiplier * baseline.durationMs)) };
|
|
807
|
+
})));
|
|
808
|
+
const generating = createEffectLogic(() => capture(Stream3.runCollect(mutants ?? source.generate(config))));
|
|
809
|
+
const testing = createEffectLogic(({ input }) => capture(Effect4.gen(function* () {
|
|
810
|
+
const dirs = input.state.pool?.value;
|
|
811
|
+
if (dirs === void 0) return yield* Effect4.die("Missing scratch pool");
|
|
812
|
+
yield* Stream3.fromIterable(input.state.pending).pipe(
|
|
813
|
+
Stream3.mapEffect((mutant) => Effect4.scoped(Effect4.gen(function* () {
|
|
814
|
+
const viability = yield* source.checkViable(mutant);
|
|
815
|
+
if (!viability.viable) {
|
|
816
|
+
const result3 = { mutant, outcome: "unviable", durationMs: 0, testCommand: [], diagnostics: viability.diagnostics };
|
|
817
|
+
yield* input.record(result3);
|
|
818
|
+
yield* reporter.progress(result3);
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
const dir = yield* Pool.get(dirs);
|
|
822
|
+
const run2 = yield* Effect4.acquireUseRelease(
|
|
823
|
+
dir.apply(mutant),
|
|
824
|
+
() => tests.runRelated(dir, path.isAbsolute(mutant.file) ? path.relative(config.root, mutant.file) : mutant.file, mutant.genre === "EffectNever" ? config.neverTimeoutMs : input.state.timeoutMs),
|
|
825
|
+
// A dirty directory must never return to the pool, even on cancel.
|
|
826
|
+
() => dir.revert(mutant).pipe(Effect4.orDie)
|
|
827
|
+
);
|
|
828
|
+
const result2 = {
|
|
829
|
+
mutant,
|
|
830
|
+
// Effect.never is meant to hang: a test that waits on it and times out noticed the mutant.
|
|
831
|
+
outcome: run2.status === "timedOut" ? mutant.genre === "EffectNever" ? "caught" : "timeout" : run2.status === "failed" ? "caught" : "missed",
|
|
832
|
+
durationMs: run2.durationMs,
|
|
833
|
+
testCommand: run2.command,
|
|
834
|
+
diagnostics: [],
|
|
835
|
+
...run2.output === "" ? {} : { output: run2.output }
|
|
836
|
+
};
|
|
837
|
+
yield* input.record(result2);
|
|
838
|
+
yield* reporter.progress(result2);
|
|
839
|
+
})), { concurrency: jobs }),
|
|
840
|
+
Stream3.runDrain
|
|
841
|
+
);
|
|
842
|
+
})));
|
|
843
|
+
const reporting = createEffectLogic(({ input }) => capture(
|
|
844
|
+
input.reported ? Effect4.void : reporter.write(report(input))
|
|
845
|
+
));
|
|
846
|
+
const machine = setupEffect({
|
|
847
|
+
schemas: {
|
|
848
|
+
context: types(),
|
|
849
|
+
events: { CANCEL: Schema5.Struct({}), RESULT: Schema5.Struct({ result: MutantResult }) }
|
|
850
|
+
},
|
|
851
|
+
actors: { copying, baselining, generating, testing, reporting }
|
|
852
|
+
}).createMachine({
|
|
853
|
+
context: {
|
|
854
|
+
baseline: { durationMs: 0, testCommand: [] },
|
|
855
|
+
timeoutMs: config.timeoutMs ?? config.minimumTimeoutMs,
|
|
856
|
+
failure: void 0,
|
|
857
|
+
pool: void 0,
|
|
858
|
+
pending: [],
|
|
859
|
+
results: [],
|
|
860
|
+
reported: false
|
|
861
|
+
},
|
|
862
|
+
output: ({ context }) => context,
|
|
863
|
+
initial: "copying",
|
|
864
|
+
on: {
|
|
865
|
+
CANCEL: { target: ".interrupted" },
|
|
866
|
+
RESULT: ({ context, event }) => ({ context: { ...context, results: [...context.results, event.result] } })
|
|
867
|
+
},
|
|
868
|
+
states: {
|
|
869
|
+
copying: { invoke: { src: "copying", onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "baseline", context: { ...context, pool: event.output.success } } : { target: "failed", context: { ...context, failure: event.output.failure } } } },
|
|
870
|
+
baseline: { invoke: {
|
|
871
|
+
src: "baselining",
|
|
872
|
+
input: ({ context }) => context.pool,
|
|
873
|
+
onDone: ({ context, event }) => Result.isSuccess(event.output) ? { target: "generating", context: { ...context, ...event.output.success } } : { target: event.output.failure._tag === "BaselineFailed" ? "baselineFailed" : "failed", context: { ...context, failure: event.output.failure } }
|
|
874
|
+
} },
|
|
875
|
+
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
|
+
testing: { invoke: {
|
|
877
|
+
src: "testing",
|
|
878
|
+
input: ({ context, self }) => ({
|
|
879
|
+
state: context,
|
|
880
|
+
// Queue completion before progress can trigger CANCEL. The parent's
|
|
881
|
+
// FIFO mailbox commits this result before handling that cancellation.
|
|
882
|
+
record: (result2) => send(self, { type: "RESULT", result: result2 })
|
|
883
|
+
}),
|
|
884
|
+
onDone: ({ context, event }) => ({ target: "reporting", context: {
|
|
885
|
+
...context,
|
|
886
|
+
failure: Result.isFailure(event.output) ? event.output.failure : context.failure
|
|
887
|
+
} })
|
|
888
|
+
} },
|
|
889
|
+
reporting: { invoke: {
|
|
890
|
+
src: "reporting",
|
|
891
|
+
input: ({ context }) => context,
|
|
892
|
+
onDone: ({ context, event }) => ({ target: "done", context: {
|
|
893
|
+
...context,
|
|
894
|
+
reported: Result.isSuccess(event.output),
|
|
895
|
+
failure: Result.isFailure(event.output) ? event.output.failure : context.failure
|
|
896
|
+
} })
|
|
897
|
+
} },
|
|
898
|
+
interrupted: { invoke: {
|
|
899
|
+
src: "reporting",
|
|
900
|
+
input: ({ context }) => context,
|
|
901
|
+
onDone: ({ context, event }) => ({ target: "done", context: {
|
|
902
|
+
...context,
|
|
903
|
+
reported: Result.isSuccess(event.output),
|
|
904
|
+
failure: Result.isFailure(event.output) ? event.output.failure : context.failure
|
|
905
|
+
} })
|
|
906
|
+
} },
|
|
907
|
+
baselineFailed: { type: "final" },
|
|
908
|
+
failed: { type: "final" },
|
|
909
|
+
done: { type: "final" }
|
|
910
|
+
}
|
|
911
|
+
});
|
|
912
|
+
const state = yield* Effect4.scoped(Effect4.gen(function* () {
|
|
913
|
+
const actor = yield* createEffectActor(machine);
|
|
914
|
+
return yield* join(actor).pipe(Effect4.orDie, Effect4.onInterrupt(() => Effect4.gen(function* () {
|
|
915
|
+
yield* send(actor, { type: "CANCEL" });
|
|
916
|
+
yield* join(actor).pipe(Effect4.orDie);
|
|
917
|
+
})));
|
|
918
|
+
}));
|
|
919
|
+
if (state.failure !== void 0) return yield* state.failure;
|
|
920
|
+
return report(state);
|
|
921
|
+
}, Effect4.scoped);
|
|
922
|
+
|
|
923
|
+
// packages/cli/src/bin.ts
|
|
924
|
+
import * as Effect8 from "effect/Effect";
|
|
925
|
+
import * as Layer5 from "effect/Layer";
|
|
926
|
+
import * as Stream5 from "effect/Stream";
|
|
927
|
+
|
|
928
|
+
// packages/cli/src/Command.ts
|
|
929
|
+
import * as Console2 from "effect/Console";
|
|
930
|
+
import * as Effect7 from "effect/Effect";
|
|
931
|
+
import * as FileSystem7 from "effect/FileSystem";
|
|
932
|
+
import * as Option from "effect/Option";
|
|
933
|
+
import * as Path9 from "effect/Path";
|
|
934
|
+
import * as Ref from "effect/Ref";
|
|
935
|
+
import * as Schema8 from "effect/Schema";
|
|
936
|
+
import * as Stream4 from "effect/Stream";
|
|
937
|
+
import * as Command from "effect/cli/Command";
|
|
938
|
+
import * as Flag from "effect/cli/Flag";
|
|
939
|
+
|
|
940
|
+
// packages/cli/src/Diff.ts
|
|
941
|
+
import * as Effect5 from "effect/Effect";
|
|
942
|
+
import * as FileSystem3 from "effect/FileSystem";
|
|
943
|
+
import * as Path5 from "effect/Path";
|
|
944
|
+
import * as Schema6 from "effect/Schema";
|
|
945
|
+
var DiffMismatch = class extends Schema6.TaggedError()("DiffMismatch", {
|
|
946
|
+
path: Schema6.String,
|
|
947
|
+
message: Schema6.String
|
|
948
|
+
}) {
|
|
949
|
+
};
|
|
950
|
+
var parseDiff = (text, path) => Effect5.try({
|
|
951
|
+
try: () => {
|
|
952
|
+
const fail4 = (message) => {
|
|
953
|
+
throw new DiffParseError({ path, message });
|
|
954
|
+
};
|
|
955
|
+
if (text === "") return [];
|
|
956
|
+
const input = text.split("\n");
|
|
957
|
+
if (input.at(-1) === "") input.pop();
|
|
958
|
+
const patches = [];
|
|
959
|
+
let i = 0;
|
|
960
|
+
let sawFile = false;
|
|
961
|
+
while (i < input.length) {
|
|
962
|
+
const line = input[i++];
|
|
963
|
+
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("--- ")) fail4("Expected a unified diff file header");
|
|
965
|
+
const next = input[i++];
|
|
966
|
+
if (!next?.startsWith("+++ ")) fail4("Missing new-side file header");
|
|
967
|
+
const raw = next.slice(4).split(" ")[0];
|
|
968
|
+
const decoded = raw.startsWith('"') ? JSON.parse(raw) : raw;
|
|
969
|
+
if (typeof decoded !== "string") fail4("Invalid file path");
|
|
970
|
+
const file = String(decoded).replace(/^b\//, "");
|
|
971
|
+
const lines = [];
|
|
972
|
+
let hunks = 0;
|
|
973
|
+
let previousEnd = 0;
|
|
974
|
+
let previousOldEnd = 0;
|
|
975
|
+
while (input[i]?.startsWith("@@")) {
|
|
976
|
+
const match2 = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:.*)$/.exec(input[i++]);
|
|
977
|
+
if (!match2) fail4("Invalid hunk header");
|
|
978
|
+
let oldRemaining = Number(match2[2] ?? 1);
|
|
979
|
+
let newRemaining = Number(match2[4] ?? 1);
|
|
980
|
+
let newLine = Number(match2[3]);
|
|
981
|
+
const oldStart = Number(match2[1]);
|
|
982
|
+
const oldCount = oldRemaining;
|
|
983
|
+
if (![oldStart, oldRemaining, newLine, newRemaining].every(Number.isSafeInteger)) fail4("Hunk range is not a safe integer");
|
|
984
|
+
if (oldRemaining > 0 && oldStart === 0 || newRemaining > 0 && newLine === 0) fail4("Nonempty hunk cannot start at zero");
|
|
985
|
+
if (newLine < previousEnd || oldStart < previousOldEnd) fail4("Overlapping or unordered hunks");
|
|
986
|
+
let previousPrefix = "";
|
|
987
|
+
const markNoNewline = () => {
|
|
988
|
+
if (previousPrefix === "+" || previousPrefix === " ") {
|
|
989
|
+
const last = lines.at(-1);
|
|
990
|
+
if (last === void 0 || last.noNewline) fail4("Unexpected no-newline marker");
|
|
991
|
+
lines[lines.length - 1] = { ...last, noNewline: true };
|
|
992
|
+
} else if (previousPrefix !== "-") fail4("Unexpected no-newline marker");
|
|
993
|
+
previousPrefix = "";
|
|
994
|
+
};
|
|
995
|
+
hunks++;
|
|
996
|
+
while (oldRemaining > 0 || newRemaining > 0) {
|
|
997
|
+
const body = input[i++];
|
|
998
|
+
if (body === "\") {
|
|
999
|
+
markNoNewline();
|
|
1000
|
+
continue;
|
|
1001
|
+
}
|
|
1002
|
+
if (body === void 0) fail4("Truncated hunk");
|
|
1003
|
+
const prefix = body[0];
|
|
1004
|
+
if (prefix === " " || prefix === "-") oldRemaining--;
|
|
1005
|
+
if (prefix === " " || prefix === "+") {
|
|
1006
|
+
newRemaining--;
|
|
1007
|
+
lines.push({ number: newLine++, text: body.slice(1), added: prefix === "+", noNewline: false });
|
|
1008
|
+
} else if (prefix !== "-") fail4("Invalid hunk line");
|
|
1009
|
+
previousPrefix = prefix;
|
|
1010
|
+
if (oldRemaining < 0 || newRemaining < 0) fail4("Hunk count does not match its body");
|
|
1011
|
+
}
|
|
1012
|
+
if (input[i] === "\") {
|
|
1013
|
+
markNoNewline();
|
|
1014
|
+
i++;
|
|
1015
|
+
}
|
|
1016
|
+
previousEnd = newLine;
|
|
1017
|
+
previousOldEnd = oldStart + oldCount;
|
|
1018
|
+
}
|
|
1019
|
+
if (hunks === 0) fail4("File has no hunks");
|
|
1020
|
+
sawFile = true;
|
|
1021
|
+
if (file !== "/dev/null") patches.push({ file, lines });
|
|
1022
|
+
}
|
|
1023
|
+
if (!sawFile) fail4("No unified diff found");
|
|
1024
|
+
return patches;
|
|
1025
|
+
},
|
|
1026
|
+
catch: (error2) => Schema6.is(DiffParseError)(error2) ? error2 : new DiffParseError({ path, message: String(error2) })
|
|
1027
|
+
});
|
|
1028
|
+
var selectInDiff = Effect5.fn("selectInDiff")(function* (options) {
|
|
1029
|
+
const fs = yield* FileSystem3.FileSystem;
|
|
1030
|
+
const path = yield* Path5.Path;
|
|
1031
|
+
const diffPath = path.resolve(options.root, options.diffPath);
|
|
1032
|
+
const text = yield* fs.readFileString(diffPath).pipe(Effect5.mapError((error2) => new DiffParseError({ path: diffPath, message: String(error2) })));
|
|
1033
|
+
const patches = yield* parseDiff(text, diffPath);
|
|
1034
|
+
const changed = /* @__PURE__ */ new Map();
|
|
1035
|
+
for (const patch of patches) {
|
|
1036
|
+
const absolute = path.resolve(options.root, patch.file);
|
|
1037
|
+
const relative2 = path.relative(options.root, absolute);
|
|
1038
|
+
if (relative2 === ".." || relative2.startsWith(`..${path.sep}`) || path.isAbsolute(relative2)) {
|
|
1039
|
+
return yield* new DiffParseError({ path: diffPath, message: "Diff path escapes project root" });
|
|
1040
|
+
}
|
|
1041
|
+
const current = yield* fs.readFileString(absolute).pipe(Effect5.mapError((error2) => new DiffMismatch({ path: patch.file, message: String(error2) })));
|
|
1042
|
+
const lines = current.split("\n");
|
|
1043
|
+
for (const line of patch.lines) {
|
|
1044
|
+
const finalLine = current.endsWith("\n") ? lines.length - 1 : lines.length;
|
|
1045
|
+
const newlineMismatch = line.noNewline ? line.number !== finalLine || current.endsWith("\n") : line.number === finalLine && !current.endsWith("\n");
|
|
1046
|
+
if (lines[line.number - 1] !== line.text || newlineMismatch) return yield* new DiffMismatch({ path: patch.file, message: `New-side line ${line.number} does not match tree` });
|
|
1047
|
+
}
|
|
1048
|
+
const added = changed.get(absolute) ?? /* @__PURE__ */ new Set();
|
|
1049
|
+
for (const line of patch.lines) if (line.added) added.add(line.number);
|
|
1050
|
+
changed.set(absolute, added);
|
|
1051
|
+
}
|
|
1052
|
+
return options.mutants.filter((mutant) => {
|
|
1053
|
+
const added = changed.get(path.resolve(options.root, mutant.file));
|
|
1054
|
+
const end = mutant.span.end.line - (mutant.span.end.column === 1 ? 1 : 0);
|
|
1055
|
+
return added !== void 0 && [...added].some((line) => line >= mutant.span.start.line && line <= end);
|
|
1056
|
+
});
|
|
1057
|
+
});
|
|
1058
|
+
|
|
1059
|
+
// 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;
|
|
1061
|
+
var errorExitCode = (error2) => {
|
|
1062
|
+
switch (error2._tag) {
|
|
1063
|
+
case "BaselineFailed":
|
|
1064
|
+
return 4;
|
|
1065
|
+
case "DiffMismatch":
|
|
1066
|
+
return 5;
|
|
1067
|
+
case "DiffParseError":
|
|
1068
|
+
return 6;
|
|
1069
|
+
case "UsageError":
|
|
1070
|
+
case "ShowHelp":
|
|
1071
|
+
case "InvalidValue":
|
|
1072
|
+
case "MissingFlag":
|
|
1073
|
+
case "UnrecognizedArgument":
|
|
1074
|
+
return 1;
|
|
1075
|
+
default:
|
|
1076
|
+
return 70;
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
|
|
1080
|
+
// packages/cli/src/Reporter.ts
|
|
1081
|
+
import * as Clock2 from "effect/Clock";
|
|
1082
|
+
import * as Console from "effect/Console";
|
|
1083
|
+
import * as Effect6 from "effect/Effect";
|
|
1084
|
+
import * as FileSystem5 from "effect/FileSystem";
|
|
1085
|
+
import * as Layer4 from "effect/Layer";
|
|
1086
|
+
import * as Path7 from "effect/Path";
|
|
1087
|
+
import * as Schema7 from "effect/Schema";
|
|
1088
|
+
import * as Semaphore from "effect/Semaphore";
|
|
1089
|
+
var mutantLine = (mutant, root, path) => `${path.relative(root, path.resolve(root, mutant.file))}:${mutant.span.start.line}:${mutant.span.start.column}: ${mutant.description}`;
|
|
1090
|
+
var outcomes = ["caught", "missed", "timeout", "unviable"];
|
|
1091
|
+
var jsonReport = Schema7.encodeEffect(Schema7.fromJsonString(RunReport));
|
|
1092
|
+
var logText = (result2) => [
|
|
1093
|
+
..."output" in result2 && typeof result2.output === "string" ? [result2.output] : [],
|
|
1094
|
+
...result2.diagnostics
|
|
1095
|
+
].join("\n");
|
|
1096
|
+
var unifiedDiff = (mutant, original) => {
|
|
1097
|
+
const replacement = mutant.replacement;
|
|
1098
|
+
const modified = original.slice(0, replacement.startOffset) + replacement.text + original.slice(replacement.endOffset);
|
|
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;
|
|
1115
|
+
const dir = path.resolve(options.root, options.outDir);
|
|
1116
|
+
const started = yield* Clock2.currentTimeMillis;
|
|
1117
|
+
const semaphore = yield* Semaphore.make(1);
|
|
1118
|
+
const results = [];
|
|
1119
|
+
let pendingError;
|
|
1120
|
+
let summarized = false;
|
|
1121
|
+
const writeError = (error2) => new ReportWriteError({ path: dir, message: String(error2) });
|
|
1122
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1123
|
+
for (const mutant of options.mutants) {
|
|
1124
|
+
if (!/^[A-Za-z0-9_-]+$/.test(mutant.id) || ids.has(mutant.id)) return yield* writeError("Mutant ids must be unique safe filenames");
|
|
1125
|
+
ids.add(mutant.id);
|
|
1126
|
+
}
|
|
1127
|
+
yield* Effect6.gen(function* () {
|
|
1128
|
+
const relative2 = path.relative(dir, path.resolve(options.root));
|
|
1129
|
+
if (relative2 === "" || relative2 !== ".." && !relative2.startsWith(`..${path.sep}`) && !path.isAbsolute(relative2)) {
|
|
1130
|
+
return yield* new ReportWriteError({ path: dir, message: "Output cannot be the project root or an ancestor" });
|
|
1131
|
+
}
|
|
1132
|
+
if (yield* fs.exists(dir)) {
|
|
1133
|
+
if (!(yield* fs.exists(path.join(dir, "mutants.json")))) return yield* writeError("Existing output is not a mutant report; choose another --output");
|
|
1134
|
+
if (yield* fs.exists(`${dir}.old`)) {
|
|
1135
|
+
if (!(yield* fs.exists(path.join(`${dir}.old`, "mutants.json")))) return yield* writeError("Previous output is not a mutant report; choose another --output");
|
|
1136
|
+
yield* fs.remove(`${dir}.old`, { recursive: true });
|
|
1137
|
+
}
|
|
1138
|
+
yield* fs.rename(dir, `${dir}.old`);
|
|
1139
|
+
}
|
|
1140
|
+
yield* fs.makeDirectory(path.join(dir, "diff"), { recursive: true });
|
|
1141
|
+
yield* fs.makeDirectory(path.join(dir, "logs"), { recursive: true });
|
|
1142
|
+
}).pipe(Effect6.mapError(writeError));
|
|
1143
|
+
const encodedMutants = yield* Schema7.encodeEffect(Schema7.fromJsonString(Schema7.Array(Mutant)))(options.mutants).pipe(Effect6.mapError(writeError));
|
|
1144
|
+
yield* fs.writeFileString(path.join(dir, "mutants.json"), encodedMutants).pipe(Effect6.mapError(writeError));
|
|
1145
|
+
yield* Effect6.forEach(outcomes, (outcome) => fs.writeFileString(path.join(dir, `${outcome}.txt`), ""), { discard: true }).pipe(Effect6.mapError(writeError));
|
|
1146
|
+
for (const mutant of options.mutants) {
|
|
1147
|
+
const original = yield* fs.readFileString(path.resolve(options.root, mutant.file)).pipe(Effect6.mapError(writeError));
|
|
1148
|
+
yield* fs.writeFileString(path.join(dir, "diff", `${mutant.id}.diff`), unifiedDiff(mutant, original)).pipe(Effect6.mapError(writeError));
|
|
1149
|
+
}
|
|
1150
|
+
const writeLists = (items) => Effect6.forEach(outcomes, (outcome) => {
|
|
1151
|
+
const lines = items.filter((result2) => result2.outcome === outcome).map((result2) => mutantLine(result2.mutant, options.root, path));
|
|
1152
|
+
return fs.writeFileString(path.join(dir, `${outcome}.txt`), lines.length === 0 ? "" : lines.join("\n") + "\n");
|
|
1153
|
+
}, { discard: true });
|
|
1154
|
+
const service = Reporter.of({
|
|
1155
|
+
progress: (result2) => semaphore.withPermit(Effect6.gen(function* () {
|
|
1156
|
+
results.push(result2);
|
|
1157
|
+
yield* Console.log(`${result2.outcome} ${mutantLine(result2.mutant, options.root, path)} (${result2.durationMs}ms)`);
|
|
1158
|
+
yield* Effect6.gen(function* () {
|
|
1159
|
+
if (!ids.has(result2.mutant.id)) return yield* writeError("Progress result does not belong to this report");
|
|
1160
|
+
yield* writeLists(results);
|
|
1161
|
+
yield* fs.writeFileString(path.join(dir, "logs", `${result2.mutant.id}.log`), logText(result2));
|
|
1162
|
+
}).pipe(Effect6.catch((error2) => Effect6.gen(function* () {
|
|
1163
|
+
if (pendingError === void 0) {
|
|
1164
|
+
pendingError = writeError(error2);
|
|
1165
|
+
yield* Console.warn(`Report write failed: ${pendingError.message}`);
|
|
1166
|
+
}
|
|
1167
|
+
})));
|
|
1168
|
+
})),
|
|
1169
|
+
write: (report) => semaphore.withPermit(Effect6.gen(function* () {
|
|
1170
|
+
if (pendingError !== void 0) return yield* pendingError;
|
|
1171
|
+
const encoded = yield* jsonReport(report).pipe(Effect6.mapError(writeError));
|
|
1172
|
+
yield* fs.writeFileString(path.join(dir, "outcomes.json.tmp"), encoded).pipe(Effect6.mapError(writeError));
|
|
1173
|
+
yield* fs.rename(path.join(dir, "outcomes.json.tmp"), path.join(dir, "outcomes.json")).pipe(Effect6.mapError(writeError));
|
|
1174
|
+
yield* writeLists(report.results).pipe(Effect6.mapError(writeError));
|
|
1175
|
+
for (const result2 of report.results) {
|
|
1176
|
+
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(Effect6.mapError(writeError));
|
|
1178
|
+
}
|
|
1179
|
+
if (summarized) return;
|
|
1180
|
+
summarized = true;
|
|
1181
|
+
const elapsed = (yield* Clock2.currentTimeMillis) - started;
|
|
1182
|
+
yield* Console.log(outcomes.map((outcome) => `${report.results.filter((result2) => result2.outcome === outcome).length} ${outcome}`).join(", ") + `; ${(elapsed / 1e3).toFixed(2)}s`);
|
|
1183
|
+
}))
|
|
1184
|
+
});
|
|
1185
|
+
return service;
|
|
1186
|
+
});
|
|
1187
|
+
|
|
1188
|
+
// packages/cli/src/Command.ts
|
|
1189
|
+
var UsageError = class extends Schema8.TaggedError()("UsageError", { message: Schema8.String }) {
|
|
1190
|
+
};
|
|
1191
|
+
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
|
+
jobs: Flag.Int("jobs").pipe(Flag.optional),
|
|
1197
|
+
timeout: Flag.Finite("timeout").pipe(Flag.optional, Flag.withDescription("Absolute test timeout in seconds")),
|
|
1198
|
+
timeoutMultiplier: Flag.Finite("timeout-multiplier").pipe(Flag.optional),
|
|
1199
|
+
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"))
|
|
1202
|
+
};
|
|
1203
|
+
var makeCommand = (options) => Command.make("mutant-cafe", flags, (input) => Effect7.gen(function* () {
|
|
1204
|
+
const fs = yield* FileSystem7.FileSystem;
|
|
1205
|
+
const path = yield* Path9.Path;
|
|
1206
|
+
const root = path.resolve(options.root);
|
|
1207
|
+
const configPath = path.join(root, "mutants.config.json");
|
|
1208
|
+
const fileConfig = (yield* fs.exists(configPath)) ? yield* fs.readFileString(configPath).pipe(
|
|
1209
|
+
Effect7.flatMap(Schema8.decodeEffect(Schema8.fromJsonString(ConfigFile))),
|
|
1210
|
+
Effect7.mapError((error2) => new UsageError({ message: `Invalid mutants.config.json: ${String(error2)}` }))
|
|
1211
|
+
) : {};
|
|
1212
|
+
const timeoutMs = Option.map(input.timeout, (seconds) => Math.ceil(seconds * 1e3));
|
|
1213
|
+
const inDiff = Option.getOrUndefined(input.inDiff);
|
|
1214
|
+
const config = yield* Schema8.decodeEffect(RunConfig)({
|
|
1215
|
+
root,
|
|
1216
|
+
tsconfig: input.tsconfig,
|
|
1217
|
+
include: input.include.length > 0 ? input.include : fileConfig.include ?? ["**/*.ts", "**/*.tsx"],
|
|
1218
|
+
exclude: input.exclude.length > 0 ? input.exclude : fileConfig.exclude ?? [],
|
|
1219
|
+
functionFilter: fileConfig.functionFilter ?? [],
|
|
1220
|
+
...inDiff === void 0 ? {} : { inDiff },
|
|
1221
|
+
jobs: Option.getOrElse(input.jobs, () => fileConfig.jobs ?? 1),
|
|
1222
|
+
...Option.isSome(timeoutMs) ? { timeoutMs: timeoutMs.value } : {},
|
|
1223
|
+
timeoutMultiplier: Option.getOrElse(input.timeoutMultiplier, () => fileConfig.timeoutMultiplier ?? 5),
|
|
1224
|
+
minimumTimeoutMs: Option.match(input.minimumTimeout, { onNone: () => fileConfig.minimumTimeoutMs ?? 2e4, onSome: (seconds) => Math.ceil(seconds * 1e3) }),
|
|
1225
|
+
neverTimeoutMs: 1e3,
|
|
1226
|
+
outDir: input.output
|
|
1227
|
+
}).pipe(Effect7.mapError((error2) => new UsageError({ message: String(error2) })));
|
|
1228
|
+
if (config.jobs < 1 || config.timeoutMultiplier <= 0 || config.minimumTimeoutMs <= 0 || config.timeoutMs !== void 0 && config.timeoutMs <= 0) {
|
|
1229
|
+
return yield* new UsageError({ message: "Jobs and timeout values must be positive" });
|
|
1230
|
+
}
|
|
1231
|
+
const source = yield* MutantSource;
|
|
1232
|
+
const generated = yield* Stream4.runCollect(source.generate(config));
|
|
1233
|
+
const mutants = inDiff === void 0 ? generated : yield* selectInDiff({ root, diffPath: inDiff, mutants: generated });
|
|
1234
|
+
if (input.list) {
|
|
1235
|
+
for (const mutant of mutants) yield* Console2.log(mutantLine(mutant, config.root, path));
|
|
1236
|
+
if (options.onExit !== void 0) yield* options.onExit(0);
|
|
1237
|
+
return;
|
|
1238
|
+
}
|
|
1239
|
+
const reporter = yield* makeReporter({ root, outDir: config.outDir, mutants });
|
|
1240
|
+
const report = yield* options.run(config, mutants).pipe(Effect7.provideService(Reporter, reporter));
|
|
1241
|
+
yield* reporter.write(report);
|
|
1242
|
+
if (options.onExit !== void 0) yield* options.onExit(reportExitCode(report));
|
|
1243
|
+
}));
|
|
1244
|
+
var runCli = Effect7.fn("runCli")(function* (options) {
|
|
1245
|
+
const code = yield* Ref.make(0);
|
|
1246
|
+
const command = makeCommand({ ...options, onExit: (value) => Ref.set(code, value) });
|
|
1247
|
+
yield* Command.runWith(command, { version: "0.1.1" })(options.args).pipe(
|
|
1248
|
+
Effect7.catch((error2) => Effect7.gen(function* () {
|
|
1249
|
+
yield* Console2.error(String(error2));
|
|
1250
|
+
yield* Ref.set(code, errorExitCode(error2));
|
|
1251
|
+
})),
|
|
1252
|
+
Effect7.catchDefect((defect) => Effect7.gen(function* () {
|
|
1253
|
+
yield* Console2.error(`Internal error: ${String(defect)}`);
|
|
1254
|
+
yield* Ref.set(code, 70);
|
|
1255
|
+
}))
|
|
1256
|
+
);
|
|
1257
|
+
return yield* Ref.get(code);
|
|
1258
|
+
});
|
|
1259
|
+
|
|
1260
|
+
// packages/cli/src/bin.ts
|
|
1261
|
+
var run = (config, mutants) => runMutants(config, Stream5.fromIterable(mutants));
|
|
1262
|
+
var live = Layer5.mergeAll(MutantSourceLive, ScratchLive, TestRunnerLive).pipe(
|
|
1263
|
+
Layer5.provideMerge(NodeServices.layer)
|
|
1264
|
+
);
|
|
1265
|
+
var main = Effect8.gen(function* () {
|
|
1266
|
+
const code = yield* runCli({ root: process.cwd(), args: process.argv.slice(2), run });
|
|
1267
|
+
yield* Effect8.sync(() => {
|
|
1268
|
+
process.exitCode = code;
|
|
1269
|
+
});
|
|
1270
|
+
}).pipe(Effect8.provide(live));
|
|
1271
|
+
NodeRuntime.runMain(main);
|
|
1272
|
+
//# sourceMappingURL=bin.js.map
|