targeted-mutation 0.1.1 → 0.2.0

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.
@@ -0,0 +1,183 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, globSync, readFileSync, realpathSync, statSync } from 'node:fs';
3
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { inside } from './vitest.mjs';
6
+
7
+ const GLOB_CHARS = /[*?[\]{]/;
8
+ const CONFIG_JSON = 'targeted-mutation.config.json';
9
+ const CONFIG_MJS = 'targeted-mutation.config.mjs';
10
+
11
+ export function hasGlobPattern(pattern) {
12
+ return GLOB_CHARS.test(String(pattern ?? ''));
13
+ }
14
+
15
+ // Expand a project-relative glob pattern using Node's built-in fs.globSync.
16
+ export function expandProjectGlob(root, pattern) {
17
+ if (!hasGlobPattern(pattern)) return [pattern];
18
+ const matches = globSync(pattern, {
19
+ cwd: root,
20
+ exclude: ['node_modules/**', '.git/**', '.worktree/**', '.worktrees/**'],
21
+ })
22
+ .filter(match => {
23
+ const full = resolve(root, match);
24
+ return statSync(full, { throwIfNoEntry: false })?.isFile();
25
+ })
26
+ .map(match => (sep === '/' ? match : match.replaceAll('/', sep)))
27
+ .sort();
28
+ return matches;
29
+ }
30
+
31
+ // Validate CLI/config source, test, config, and spec paths on the real project root
32
+ // BEFORE copying the project to a temporary directory.
33
+ export function validateAndExpandInputs(project, files = [], options = {}) {
34
+ if (!existsSync(project)) {
35
+ throw new Error(`Project directory not found: ${project}`);
36
+ }
37
+ const root = realpathSync(project);
38
+
39
+ const hintDash = p => (String(p).startsWith('-') ? ' (did an extra "--" treat an option as a file path?)' : '');
40
+
41
+ if (options.config !== undefined) {
42
+ const candidate = resolve(root, options.config);
43
+ if (!existsSync(candidate)) {
44
+ throw new Error(`Config file not found: ${options.config}`);
45
+ }
46
+ inside(root, options.config);
47
+ }
48
+
49
+ if (options.spec !== undefined) {
50
+ const candidate = resolve(root, options.spec);
51
+ if (!existsSync(candidate)) {
52
+ throw new Error(`Spec file not found: ${options.spec}`);
53
+ }
54
+ inside(root, options.spec);
55
+ }
56
+
57
+ const expandedFiles = [];
58
+ for (const entry of files) {
59
+ if (hasGlobPattern(entry)) {
60
+ const matched = expandProjectGlob(root, entry);
61
+ if (!matched.length) throw new Error(`Source file pattern matched no files: ${entry}`);
62
+ for (const m of matched) inside(root, m);
63
+ expandedFiles.push(...matched);
64
+ } else {
65
+ const candidate = resolve(root, entry);
66
+ if (!existsSync(candidate)) {
67
+ throw new Error(`Source file not found: ${entry}${hintDash(entry)}`);
68
+ }
69
+ inside(root, entry);
70
+ expandedFiles.push(entry);
71
+ }
72
+ }
73
+
74
+ let expandedTests;
75
+ if (options.test?.length) {
76
+ expandedTests = [];
77
+ for (const entry of options.test) {
78
+ if (hasGlobPattern(entry)) {
79
+ const matched = expandProjectGlob(root, entry);
80
+ if (!matched.length) throw new Error(`Test file pattern matched no files: ${entry}`);
81
+ for (const m of matched) inside(root, m);
82
+ expandedTests.push(...matched);
83
+ } else {
84
+ const candidate = resolve(root, entry);
85
+ if (!existsSync(candidate)) {
86
+ throw new Error(`Test file not found: ${entry}${hintDash(entry)}`);
87
+ }
88
+ inside(root, entry);
89
+ expandedTests.push(entry);
90
+ }
91
+ }
92
+ expandedTests = [...new Set(expandedTests)];
93
+ }
94
+
95
+ return {
96
+ root,
97
+ files: [...new Set(expandedFiles)],
98
+ tests: expandedTests,
99
+ };
100
+ }
101
+
102
+ // Discover top-level gitignored paths (excluding node_modules and already-excluded dirs)
103
+ // so temporary project copies skip build outputs and test artifacts like dist/ or test-results/.
104
+ export function gitignoredCopyExclusions(root) {
105
+ try {
106
+ const raw = execFileSync('git', ['-C', root, 'ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'], {
107
+ maxBuffer: 16 * 1024 * 1024,
108
+ stdio: ['ignore', 'pipe', 'pipe'],
109
+ }).toString('utf8');
110
+ const skipBuiltIn = new Set(['.git', '.worktree', '.worktrees', 'docs.local', 'node_modules', 'reports', '.stryker-tmp']);
111
+ const out = [];
112
+ for (const entry of raw.split('\0')) {
113
+ if (!entry) continue;
114
+ const cleaned = entry.replace(/\/+$/, '');
115
+ if (!cleaned) continue;
116
+ const firstPart = cleaned.split('/')[0];
117
+ if (skipBuiltIn.has(firstPart)) continue;
118
+ if (cleaned.split('/').includes('node_modules')) continue;
119
+ const candidate = resolve(root, cleaned);
120
+ if (!existsSync(candidate)) continue;
121
+ // Only include entries inside root without symlink parent traversal.
122
+ const rel = relative(root, candidate);
123
+ if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith('..' + sep)) continue;
124
+ out.push(sep === '/' ? cleaned : cleaned.replaceAll('/', sep));
125
+ }
126
+ return [...new Set(out)];
127
+ } catch {
128
+ return [];
129
+ }
130
+ }
131
+
132
+ // Load project defaults from `targeted-mutation.config.json`, `targeted-mutation.config.mjs`,
133
+ // or `package.json`'s `targetedMutation` field.
134
+ // When `allowCodeConfig` is false (e.g. `--list`), only data-only JSON configs are loaded.
135
+ export async function loadProjectConfig(project, { allowCodeConfig = true } = {}) {
136
+ if (!existsSync(project)) return null;
137
+ const root = realpathSync(project);
138
+ const jsonPath = resolve(root, CONFIG_JSON);
139
+ if (existsSync(jsonPath)) {
140
+ const data = JSON.parse(readFileSync(jsonPath, 'utf8'));
141
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
142
+ throw new Error(`Invalid configuration in ${CONFIG_JSON}: expected a JSON object`);
143
+ }
144
+ return { source: CONFIG_JSON, config: data };
145
+ }
146
+ const mjsPath = resolve(root, CONFIG_MJS);
147
+ if (allowCodeConfig && existsSync(mjsPath)) {
148
+ const mod = await import(pathToFileURL(mjsPath).href);
149
+ const data = mod.default;
150
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
151
+ throw new Error(`Invalid configuration in ${CONFIG_MJS}: expected default export object`);
152
+ }
153
+ return { source: CONFIG_MJS, config: data };
154
+ }
155
+ const pkgPath = resolve(root, 'package.json');
156
+ if (existsSync(pkgPath)) {
157
+ try {
158
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
159
+ if (pkg?.targetedMutation && typeof pkg.targetedMutation === 'object' && !Array.isArray(pkg.targetedMutation)) {
160
+ return { source: 'package.json#targetedMutation', config: pkg.targetedMutation };
161
+ }
162
+ } catch {
163
+ // Ignore invalid package.json here; downstream runner will report if needed.
164
+ }
165
+ }
166
+ return null;
167
+ }
168
+
169
+ export function mergeProjectConfig(configObj, cliValues, cliFiles) {
170
+ if (!configObj) return { files: cliFiles, values: cliValues };
171
+ const values = { ...cliValues };
172
+ if (values.mutators === undefined && typeof configObj.mutators === 'string') values.mutators = configObj.mutators;
173
+ if (values.timeout === undefined && configObj.timeout !== undefined) values.timeout = String(configObj.timeout);
174
+ if (values.concurrency === undefined && configObj.concurrency !== undefined) values.concurrency = String(configObj.concurrency);
175
+ if (values.config === undefined && typeof configObj.config === 'string') values.config = configObj.config;
176
+ if (values.baseline === undefined && typeof configObj.baseline === 'string') values.baseline = configObj.baseline;
177
+ if (!values.test?.length && Array.isArray(configObj.tests)) values.test = configObj.tests.map(String);
178
+ if (!values['copy-exclude']?.length && Array.isArray(configObj.copyExclude)) values['copy-exclude'] = configObj.copyExclude.map(String);
179
+ if (values['copy-exclude-gitignore'] === undefined && configObj.copyExcludeGitignore === true) values['copy-exclude-gitignore'] = true;
180
+ if (!values['exclude-rule']?.length && Array.isArray(configObj.excludeRules)) values['exclude-rule'] = configObj.excludeRules.map(String);
181
+ const files = cliFiles.length ? cliFiles : (Array.isArray(configObj.files) ? configObj.files.map(String) : []);
182
+ return { files, values };
183
+ }
@@ -0,0 +1,335 @@
1
+ import { loadTypeScript } from './typescript-compiler.mjs';
2
+
3
+ function stripParens(node, ts) {
4
+ while (node && ts.isParenthesizedExpression(node)) node = node.expression;
5
+ return node;
6
+ }
7
+
8
+ function intLiteral(node, ts) {
9
+ node = stripParens(node, ts);
10
+ if (!node) return undefined;
11
+ if (ts.isNumericLiteral(node)) {
12
+ const value = Number(node.text);
13
+ return Number.isSafeInteger(value) ? value : undefined;
14
+ }
15
+ if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(node.operand)) {
16
+ const value = -Number(node.operand.text);
17
+ return Number.isSafeInteger(value) ? value : undefined;
18
+ }
19
+ return undefined;
20
+ }
21
+
22
+ function isNonNegativeExpr(node, ts) {
23
+ node = stripParens(node, ts);
24
+ if (!node) return false;
25
+ if (ts.isPropertyAccessExpression(node) && ['length', 'size', 'byteLength'].includes(node.name.text)) {
26
+ return true;
27
+ }
28
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) &&
29
+ ts.isIdentifier(node.expression.expression) && node.expression.expression.text === 'Math' &&
30
+ node.expression.name.text === 'abs') {
31
+ return true;
32
+ }
33
+ return false;
34
+ }
35
+
36
+ // Extract a sound integer reachability constraint from the outer operator of a comparison's LHS.
37
+ export function extractReachability(lhsText, ts = loadTypeScript()) {
38
+ if (typeof lhsText !== 'string' || !lhsText.trim()) return null;
39
+ const wrapped = `(${lhsText});`;
40
+ const sf = ts.createSourceFile('lhs.ts', wrapped, ts.ScriptTarget.Latest, true);
41
+ if (sf.parseDiagnostics.length || sf.statements.length !== 1 || !ts.isExpressionStatement(sf.statements[0])) {
42
+ return null;
43
+ }
44
+ const node = stripParens(sf.statements[0].expression, ts);
45
+ if (!node) return null;
46
+
47
+ if (isNonNegativeExpr(node, ts)) {
48
+ return { kind: 'nonNegative', min: 0 };
49
+ }
50
+
51
+ if (ts.isBinaryExpression(node)) {
52
+ const op = node.operatorToken.kind;
53
+ const leftLit = intLiteral(node.left, ts);
54
+ const rightLit = intLiteral(node.right, ts);
55
+
56
+ if (op === ts.SyntaxKind.PercentToken && rightLit !== undefined && rightLit > 0) {
57
+ const nonNeg = isNonNegativeExpr(node.left, ts);
58
+ return { kind: 'remainder', divisor: rightLit, min: nonNeg ? 0 : -(rightLit - 1), max: rightLit - 1 };
59
+ }
60
+
61
+ if (op === ts.SyntaxKind.AmpersandToken) {
62
+ const mask = rightLit !== undefined ? rightLit : leftLit;
63
+ if (mask !== undefined && mask >= 0 && mask <= 0x7fffffff) {
64
+ return { kind: 'bitmask', mask };
65
+ }
66
+ }
67
+
68
+ if (op === ts.SyntaxKind.LessThanLessThanToken && rightLit !== undefined && rightLit >= 1 && rightLit <= 30) {
69
+ return { kind: 'step', step: 1 << rightLit };
70
+ }
71
+ }
72
+
73
+ return null;
74
+ }
75
+
76
+ export function isReachable(value, constraint) {
77
+ if (!Number.isSafeInteger(value)) return false;
78
+ if (!constraint) return true;
79
+ switch (constraint.kind) {
80
+ case 'nonNegative':
81
+ return value >= constraint.min;
82
+ case 'remainder':
83
+ return value >= constraint.min && value <= constraint.max;
84
+ case 'bitmask':
85
+ return value >= 0 && value <= constraint.mask && ((value & ~constraint.mask) === 0);
86
+ case 'step':
87
+ return value % constraint.step === 0;
88
+ default:
89
+ return true;
90
+ }
91
+ }
92
+
93
+ // Find the smallest reachable integer >= start (up to limit), or null if none exists.
94
+ export function nextReachableAtOrAbove(start, limit, constraint) {
95
+ if (start > limit) return null;
96
+ if (!constraint) return start;
97
+ switch (constraint.kind) {
98
+ case 'nonNegative': {
99
+ const v = Math.max(start, constraint.min);
100
+ return v <= limit ? v : null;
101
+ }
102
+ case 'remainder': {
103
+ const v = Math.max(start, constraint.min);
104
+ const hi = Math.min(limit, constraint.max);
105
+ return v <= hi ? v : null;
106
+ }
107
+ case 'step': {
108
+ const s = constraint.step;
109
+ const rem = ((start % s) + s) % s;
110
+ const v = rem === 0 ? start : start + (s - rem);
111
+ return Number.isSafeInteger(v) && v <= limit ? v : null;
112
+ }
113
+ case 'bitmask': {
114
+ const mask = constraint.mask;
115
+ const lo = Math.max(0, start);
116
+ const hi = Math.min(mask, limit);
117
+ if (lo > hi) return null;
118
+ // Compute smallest v >= lo such that (v & ~mask) === 0 via bit trick:
119
+ // For any bit in lo that is outside mask, clear lower bits and carry into the lowest mask bit above it.
120
+ let v = lo;
121
+ const bad = v & ~mask;
122
+ if (bad !== 0) {
123
+ const highestBadBit = 1 << (31 - Math.clz32(bad));
124
+ // Find lowest mask bit strictly above highestBadBit that is not already set in v.
125
+ const aboveFreeMask = (mask & ~v) & (~((highestBadBit << 1) - 1));
126
+ if (aboveFreeMask === 0) return null;
127
+ const carryBit = aboveFreeMask & -aboveFreeMask;
128
+ v = (v & ~(carryBit - 1)) | carryBit;
129
+ }
130
+ return v <= hi ? v : null;
131
+ }
132
+ default:
133
+ return start;
134
+ }
135
+ }
136
+
137
+ // Find the largest reachable integer <= end (down to floor), or null if none exists.
138
+ export function prevReachableAtOrBelow(end, floor, constraint) {
139
+ if (end < floor) return null;
140
+ if (!constraint) return end;
141
+ switch (constraint.kind) {
142
+ case 'nonNegative': {
143
+ const lo = Math.max(floor, constraint.min);
144
+ return end >= lo ? end : null;
145
+ }
146
+ case 'remainder': {
147
+ const lo = Math.max(floor, constraint.min);
148
+ const v = Math.min(end, constraint.max);
149
+ return v >= lo ? v : null;
150
+ }
151
+ case 'step': {
152
+ const s = constraint.step;
153
+ const rem = ((end % s) + s) % s;
154
+ const v = end - rem;
155
+ return Number.isSafeInteger(v) && v >= floor ? v : null;
156
+ }
157
+ case 'bitmask': {
158
+ const mask = constraint.mask;
159
+ const lo = Math.max(0, floor);
160
+ const hi = Math.min(mask, end);
161
+ if (lo > hi) return null;
162
+ let v = hi;
163
+ const bad = v & ~mask;
164
+ if (bad !== 0) {
165
+ const highestBadBit = 1 << (31 - Math.clz32(bad));
166
+ // Keep bits above highestBadBit masked by `mask`, and set all mask bits below highestBadBit.
167
+ v = (v & ~(highestBadBit - 1) & ~highestBadBit & mask) | (mask & (highestBadBit - 1));
168
+ }
169
+ return v >= lo ? v : null;
170
+ }
171
+ default:
172
+ return end;
173
+ }
174
+ }
175
+
176
+ function evaluateOp(operator, lhs, rhs) {
177
+ switch (operator) {
178
+ case '<': return lhs < rhs;
179
+ case '<=': return lhs <= rhs;
180
+ case '>': return lhs > rhs;
181
+ case '>=': return lhs >= rhs;
182
+ }
183
+ }
184
+
185
+ // Filter a thresholdGap result using an extracted reachability constraint.
186
+ // Returns null when no reachable integer can distinguish any feasible alternate threshold from `threshold`.
187
+ export function filterReachableThresholdGap(gap, constraint, threshold, operator, observations = []) {
188
+ if (!gap || !constraint) return gap;
189
+ // Soundness guard: only apply the constraint if every observed LHS value actually obeys it.
190
+ if (observations.length > 0 && observations.some(v => !isReachable(v, constraint))) {
191
+ return gap;
192
+ }
193
+ const [lo, hi] = gap.interval;
194
+ const upper = operator === '>' || operator === '<=';
195
+
196
+ // Check both directions from threshold inside [lo, hi] for the nearest reachable distinguishing witness.
197
+ // For upper-inclusive (`>` / `<=`):
198
+ // - alt > threshold separates values v in (threshold, alt] -> need reachable v in [threshold + 1, hi].
199
+ // - alt < threshold separates values v in (alt, threshold] -> need reachable v in [lo + 1, threshold].
200
+ // For lower-inclusive (`<` / `>=`):
201
+ // - alt < threshold separates values v in [alt, threshold) -> need reachable v in [lo, threshold - 1].
202
+ // - alt > threshold separates values v in [threshold, alt) -> need reachable v in [threshold, hi - 1].
203
+ const checkAbove = () => {
204
+ if (threshold >= hi) return null;
205
+ if (upper) {
206
+ const v = nextReachableAtOrAbove(threshold + 1, hi, constraint);
207
+ if (v === null) return null;
208
+ return { alternate: v, witness: v };
209
+ }
210
+ const v = nextReachableAtOrAbove(threshold, hi - 1, constraint);
211
+ if (v === null) return null;
212
+ return { alternate: v + 1, witness: v };
213
+ };
214
+
215
+ const checkBelow = () => {
216
+ if (lo >= threshold) return null;
217
+ if (upper) {
218
+ const v = prevReachableAtOrBelow(threshold, lo + 1, constraint);
219
+ if (v === null) return null;
220
+ return { alternate: v - 1, witness: v };
221
+ }
222
+ const v = prevReachableAtOrBelow(threshold - 1, lo, constraint);
223
+ if (v === null) return null;
224
+ return { alternate: v, witness: v };
225
+ };
226
+
227
+ const chosen = upper ? (checkAbove() ?? checkBelow()) : (checkBelow() ?? checkAbove());
228
+ if (!chosen) return null;
229
+ return {
230
+ interval: gap.interval,
231
+ alternate: chosen.alternate,
232
+ witness: chosen.witness,
233
+ expected: evaluateOp(operator, chosen.witness, threshold),
234
+ mutant: evaluateOp(operator, chosen.witness, chosen.alternate),
235
+ constraint: constraint.kind,
236
+ };
237
+ }
238
+
239
+ // Check whether the exact equality boundary `lhs === threshold` is reachable under the constraint.
240
+ export function isBoundaryReachable(constraint, threshold, observations = []) {
241
+ if (!constraint) return true;
242
+ if (observations.length > 0 && observations.some(v => !isReachable(v, constraint))) return true;
243
+ return isReachable(threshold, constraint);
244
+ }
245
+
246
+ // Check if `lhsText` is a simple identifier initialized to >= 0 and monotonically incremented
247
+ // in an enclosing `for (let i = 0; ...; i++)` statement without downward mutation in the loop body.
248
+ export function extractLoopCounterNonNegative(sourceText, siteOffset, lhsText, ts = loadTypeScript()) {
249
+ if (typeof lhsText !== 'string' || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(lhsText.trim())) return null;
250
+ const name = lhsText.trim();
251
+ const sf = ts.createSourceFile('loop.ts', sourceText, ts.ScriptTarget.Latest, true);
252
+ if (sf.parseDiagnostics.length) return null;
253
+
254
+ function initNonNegative(forNode) {
255
+ const init = forNode.initializer;
256
+ if (!init || !ts.isVariableDeclarationList(init)) return false;
257
+ for (const decl of init.declarations) {
258
+ if (ts.isIdentifier(decl.name) && decl.name.text === name && decl.initializer) {
259
+ const val = intLiteral(decl.initializer, ts);
260
+ if (val !== undefined && val >= 0) return true;
261
+ }
262
+ }
263
+ return false;
264
+ }
265
+
266
+ function incrementorNonDecreasing(forNode) {
267
+ const inc = stripParens(forNode.incrementor, ts);
268
+ if (!inc) return false;
269
+ if ((ts.isPostfixUnaryExpression(inc) || ts.isPrefixUnaryExpression(inc)) &&
270
+ inc.operator === ts.SyntaxKind.PlusPlusToken &&
271
+ ts.isIdentifier(inc.operand) && inc.operand.text === name) {
272
+ return true;
273
+ }
274
+ if (ts.isBinaryExpression(inc) && inc.operatorToken.kind === ts.SyntaxKind.PlusEqualsToken &&
275
+ ts.isIdentifier(inc.left) && inc.left.text === name) {
276
+ const step = intLiteral(inc.right, ts);
277
+ return step !== undefined && step >= 0;
278
+ }
279
+ return false;
280
+ }
281
+
282
+ function bodyMutatesName(body) {
283
+ let mutated = false;
284
+ (function walk(node) {
285
+ if (mutated) return;
286
+ if (ts.isBinaryExpression(node) &&
287
+ node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
288
+ node.operatorToken.kind <= ts.SyntaxKind.LastAssignment &&
289
+ ts.isIdentifier(stripParens(node.left, ts)) && stripParens(node.left, ts).text === name) {
290
+ mutated = true;
291
+ return;
292
+ }
293
+ if ((ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) &&
294
+ (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken) &&
295
+ ts.isIdentifier(stripParens(node.operand, ts)) && stripParens(node.operand, ts).text === name) {
296
+ mutated = true;
297
+ return;
298
+ }
299
+ ts.forEachChild(node, walk);
300
+ })(body);
301
+ return mutated;
302
+ }
303
+
304
+ let found = false;
305
+ (function visit(node, shadowed = false) {
306
+ if (found) return;
307
+ if (node.pos <= siteOffset && siteOffset <= node.end) {
308
+ if (ts.isForStatement(node) && initNonNegative(node) && incrementorNonDecreasing(node) && !bodyMutatesName(node.statement)) {
309
+ // Verify no inner block/declaration shadows `name` around `siteOffset`.
310
+ let innerShadowed = false;
311
+ (function checkShadow(inner) {
312
+ if (innerShadowed || inner === node.initializer) return;
313
+ if (inner.pos <= siteOffset && siteOffset <= inner.end) {
314
+ if (ts.isVariableDeclaration(inner) && ts.isIdentifier(inner.name) && inner.name.text === name && inner.end <= siteOffset) {
315
+ innerShadowed = true;
316
+ return;
317
+ }
318
+ if (ts.isParameter(inner) && ts.isIdentifier(inner.name) && inner.name.text === name) {
319
+ innerShadowed = true;
320
+ return;
321
+ }
322
+ ts.forEachChild(inner, checkShadow);
323
+ }
324
+ })(node.statement);
325
+ if (!innerShadowed) {
326
+ found = true;
327
+ return;
328
+ }
329
+ }
330
+ ts.forEachChild(node, child => visit(child, shadowed));
331
+ }
332
+ })(sf);
333
+
334
+ return found ? { kind: 'nonNegative', min: 0 } : null;
335
+ }
package/src/sarif.mjs ADDED
@@ -0,0 +1,156 @@
1
+ import { annotateFindingIds } from './baseline.mjs';
2
+
3
+ const SARIF_SCHEMA = 'https://json.schemastore.org/sarif-2.1.0.json';
4
+ const SARIF_VERSION = '2.1.0';
5
+
6
+ const RULES = [
7
+ {
8
+ id: 'input-gap',
9
+ name: 'InputGap',
10
+ shortDescription: { text: 'Missing test input distinguishing a targeted mutation' },
11
+ defaultConfiguration: { level: 'warning' },
12
+ },
13
+ {
14
+ id: 'assertion-gap',
15
+ name: 'AssertionGap',
16
+ shortDescription: { text: 'Tests execute changed behavior without asserting on it' },
17
+ defaultConfiguration: { level: 'warning' },
18
+ },
19
+ {
20
+ id: 'untested-change',
21
+ name: 'UntestedChange',
22
+ shortDescription: { text: 'Test suite still passes when a recent change is reverted' },
23
+ defaultConfiguration: { level: 'warning' },
24
+ },
25
+ {
26
+ id: 'weakened-test',
27
+ name: 'WeakenedTest',
28
+ shortDescription: { text: 'A recent test change allowed a previously caught mutation to survive' },
29
+ defaultConfiguration: { level: 'error' },
30
+ },
31
+ {
32
+ id: 'witness-gap',
33
+ name: 'WitnessGap',
34
+ shortDescription: { text: 'Confirmed distinguishing witness reveals a test gap' },
35
+ defaultConfiguration: { level: 'warning' },
36
+ },
37
+ ];
38
+
39
+ function toPosixUri(file) {
40
+ return String(file ?? '').replaceAll('\\', '/').replace(/^\.\//, '');
41
+ }
42
+
43
+ function ruleIdFor(diagnostic) {
44
+ if (diagnostic.weakened) return 'weakened-test';
45
+ switch (diagnostic.kind) {
46
+ case 'INPUT GAP': return 'input-gap';
47
+ case 'ASSERTION GAP': return 'assertion-gap';
48
+ case 'UNTESTED CHANGE': return 'untested-change';
49
+ default: return diagnostic.verification?.status === 'confirmed' ? 'witness-gap' : 'input-gap';
50
+ }
51
+ }
52
+
53
+ function messageFor(diagnostic) {
54
+ const parts = [];
55
+ const kind = diagnostic.kind ?? 'GAP';
56
+ const rule = diagnostic.rule ? ` (${diagnostic.rule})` : '';
57
+ if (diagnostic.expression !== undefined) {
58
+ const edit = diagnostic.mutations?.[0]?.replacement;
59
+ parts.push(`${kind}${rule}: \`${String(diagnostic.expression).trim()}\` passes every test as \`${String(edit ?? '').trim()}\`.`);
60
+ } else if (diagnostic.kind === 'UNTESTED CHANGE') {
61
+ parts.push(`UNTESTED CHANGE: tests pass with this change reverted to ${String(diagnostic.since ?? '').slice(0, 12)}.`);
62
+ } else {
63
+ parts.push(`${kind}${rule}.`);
64
+ }
65
+ if (diagnostic.missing) parts.push(`Add ${diagnostic.missing}.`);
66
+ else if (diagnostic.advice) parts.push(diagnostic.advice);
67
+ if (diagnostic.suggestedTest) parts.push(`Suggested test: ${diagnostic.suggestedTest}`);
68
+ if (diagnostic.weakened) {
69
+ parts.push(`Weakened test: tests as they were at ${String(diagnostic.weakened.since).slice(0, 12)} caught this.`);
70
+ }
71
+ return parts.join(' ');
72
+ }
73
+
74
+ export function renderSarif(report, { version = '0.0.0' } = {}) {
75
+ const annotated = annotateFindingIds(report.diagnostics ?? []);
76
+ const results = annotated.map(diagnostic => {
77
+ const ruleId = ruleIdFor(diagnostic);
78
+ const location = diagnostic.location ?? {};
79
+ const result = {
80
+ ruleId,
81
+ level: ruleId === 'weakened-test' ? 'error' : 'warning',
82
+ message: { text: messageFor(diagnostic) },
83
+ partialFingerprints: {
84
+ tmtFindingId: diagnostic.findingId,
85
+ },
86
+ properties: {
87
+ kind: diagnostic.kind ?? 'GAP',
88
+ ...(diagnostic.rule ? { rule: diagnostic.rule } : {}),
89
+ ...(diagnostic.suggestedTest ? { suggestedTest: diagnostic.suggestedTest } : {}),
90
+ ...(diagnostic.weakened ? { weakened: diagnostic.weakened } : {}),
91
+ },
92
+ };
93
+ if (location.file) {
94
+ result.locations = [{
95
+ physicalLocation: {
96
+ artifactLocation: { uri: toPosixUri(location.file) },
97
+ region: {
98
+ startLine: Math.max(1, Number(location.line) || 1),
99
+ startColumn: Math.max(1, Number(location.column) || 1),
100
+ },
101
+ },
102
+ }];
103
+ }
104
+ return result;
105
+ });
106
+
107
+ const executionSuccessful = report.evaluation !== 'baseline_error' && report.evaluation !== 'incomplete' &&
108
+ !(report.extraction ?? []).some(entry => entry.path === 'diagnostic');
109
+
110
+ return {
111
+ $schema: SARIF_SCHEMA,
112
+ version: SARIF_VERSION,
113
+ runs: [{
114
+ tool: {
115
+ driver: {
116
+ name: 'targeted-mutation',
117
+ version,
118
+ informationUri: 'https://github.com/t-k/targeted-mutation-ts',
119
+ rules: RULES,
120
+ },
121
+ },
122
+ invocations: [{
123
+ executionSuccessful,
124
+ }],
125
+ results,
126
+ properties: {
127
+ analysis: {
128
+ runner: report.runner,
129
+ mutators: report.mutators,
130
+ evaluation: report.evaluation,
131
+ ...(report.suppressed ? { suppressed: report.suppressed } : {}),
132
+ ...(report.shard ? { shard: report.shard } : {}),
133
+ },
134
+ },
135
+ }],
136
+ };
137
+ }
138
+
139
+ export function renderJsonl(report) {
140
+ const lines = [];
141
+ const { mutants = [], diagnostics = [], ...summary } = report;
142
+ lines.push(JSON.stringify({ event: 'summary', ...summary }));
143
+ for (const mutant of mutants) {
144
+ lines.push(JSON.stringify({ event: 'mutant', ...mutant }));
145
+ }
146
+ for (const diagnostic of annotateFindingIds(diagnostics)) {
147
+ lines.push(JSON.stringify({ event: 'diagnostic', ...diagnostic }));
148
+ }
149
+ lines.push(JSON.stringify({
150
+ event: 'complete',
151
+ evaluation: report.evaluation,
152
+ mutants: mutants.length,
153
+ diagnostics: diagnostics.length,
154
+ }));
155
+ return lines.join('\n');
156
+ }