targeted-mutation 0.3.0 → 0.4.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/README.md +22 -3
- package/bin/tmt.mjs +98 -32
- package/docs/how-it-works.svg +99 -180
- package/docs/why-targeted.svg +117 -0
- package/package.json +5 -5
- package/src/analysis.mjs +32 -13
- package/src/builtin-mutations.mjs +7 -2
- package/src/checkpoint.mjs +3 -0
- package/src/cli-output.mjs +66 -16
- package/src/conventional.mjs +67 -4
- package/src/operator-analysis.mjs +7 -0
- package/src/project-config.mjs +6 -0
- package/src/shard.mjs +6 -1
- package/src/standard-session.mjs +88 -24
- package/src/targeted-gaps.mjs +14 -5
- package/src/type-equivalence.mjs +227 -31
- package/src/vitest.mjs +272 -22
package/src/standard-session.mjs
CHANGED
|
@@ -9,7 +9,7 @@ import { inside } from './vitest.mjs';
|
|
|
9
9
|
// Vitest and Vite are loaded on every run. Node keeps their compiled code between runs when it can.
|
|
10
10
|
try { enableCompileCache?.(); } catch { /* The cache is an optimisation only. */ }
|
|
11
11
|
const input = JSON.parse(readFileSync(process.argv[2], 'utf8'));
|
|
12
|
-
const { workspace, config, files, selectedSpecs, mutants, setup, workerRunner, output, temporary, isolatedTrials, concurrency = 1, verifyTrials = 0, awaitsExtras = false, runTimeout = 60_000 } = input;
|
|
12
|
+
const { workspace, config, files, selectedSpecs, mutants, setup, workerRunner, output, temporary, isolatedTrials, concurrency = 1, verifyTrials = 0, awaitsExtras = false, runTimeout = 60_000, baselineTimeout = runTimeout, baselineWorkers, progressIntervalMs } = input;
|
|
13
13
|
const destination = resolve(temporary, 'coverage.jsonl');
|
|
14
14
|
const record = event => appendFileSync(output, JSON.stringify(event) + '\n');
|
|
15
15
|
const lanes = [];
|
|
@@ -52,23 +52,23 @@ function follow(path) {
|
|
|
52
52
|
};
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
function filterSelectedSpecs(allSpecs) {
|
|
56
|
+
if (!selectedSpecs?.length) return allSpecs;
|
|
57
|
+
const allowed = new Set(selectedSpecs.map(({ project, file }) => JSON.stringify([project ?? '', file])));
|
|
58
|
+
return allSpecs.filter(spec => allowed.has(JSON.stringify([spec.project.name ?? '', inside(workspace, spec.moduleId)])));
|
|
59
|
+
}
|
|
60
|
+
|
|
55
61
|
// A lane is one Vitest instance with its own worker. The first lane also runs the baseline and the isolated trials.
|
|
56
|
-
async function openLane(index, serial = false) {
|
|
57
|
-
const lane = { snapshot: null, events: resolve(temporary, `trials-${index}.jsonl`), serial };
|
|
62
|
+
async function openLane(index, serial = false, workerOverride = undefined) {
|
|
63
|
+
const lane = { snapshot: null, events: resolve(temporary, `trials-${index}.jsonl`), serial, workerOverride };
|
|
58
64
|
lane.context = await createContext(lane);
|
|
59
|
-
|
|
60
|
-
if (selectedSpecs?.length) {
|
|
61
|
-
const allowed = new Set(selectedSpecs.map(({ project, file }) => JSON.stringify([project ?? '', file])));
|
|
62
|
-
lane.specs = allSpecs.filter(spec => allowed.has(JSON.stringify([spec.project.name ?? '', inside(workspace, spec.moduleId)])));
|
|
63
|
-
} else {
|
|
64
|
-
lane.specs = allSpecs;
|
|
65
|
-
}
|
|
65
|
+
lane.specs = filterSelectedSpecs(await lane.context.globTestSpecifications(files));
|
|
66
66
|
return lane;
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
// Runs a lane's share of the planned mutations inside its worker, one Vitest run per round. A worker that stops
|
|
70
70
|
// answering is replaced, its mutation is a timeout, and the rest continue in the next round.
|
|
71
|
-
async function runInThread(lane, plans, limit, deadline) {
|
|
71
|
+
async function runInThread(lane, plans, limit, deadline, onEvent, onTick) {
|
|
72
72
|
const events = [];
|
|
73
73
|
let remaining = plans;
|
|
74
74
|
while (Object.keys(remaining).length) {
|
|
@@ -87,10 +87,12 @@ async function runInThread(lane, plans, limit, deadline) {
|
|
|
87
87
|
const ended = finished;
|
|
88
88
|
for (const event of read()) {
|
|
89
89
|
round.push(event);
|
|
90
|
+
onEvent?.(event);
|
|
90
91
|
if (event.start !== undefined) started.set(event.module, { id: event.start, at: Date.now() });
|
|
91
92
|
else if (event.control !== undefined) started.set(event.module, { id: event.control, at: Date.now(), control: true });
|
|
92
93
|
else started.delete(event.module);
|
|
93
94
|
}
|
|
95
|
+
onTick?.();
|
|
94
96
|
if (ended) break;
|
|
95
97
|
stuck = [...started].find(([, { at }]) => Date.now() - at > limit);
|
|
96
98
|
if (!stuck) await Promise.race([running, new Promise(resolvePoll => setTimeout(resolvePoll, 50))]);
|
|
@@ -115,21 +117,21 @@ async function runInThread(lane, plans, limit, deadline) {
|
|
|
115
117
|
.filter(([, list]) => list.length));
|
|
116
118
|
await Promise.race([lane.context.close(), new Promise(resolveClose => setTimeout(resolveClose, 5_000))]);
|
|
117
119
|
lane.context = await createContext(lane);
|
|
118
|
-
lane.specs = await lane.context.globTestSpecifications(files);
|
|
120
|
+
lane.specs = filterSelectedSpecs(await lane.context.globTestSpecifications(files));
|
|
119
121
|
}
|
|
120
122
|
return events;
|
|
121
123
|
}
|
|
122
124
|
|
|
123
|
-
async function run(specs, state, lane = lanes[0]) {
|
|
125
|
+
async function run(specs, state, lane = lanes[0], timeoutMs = runTimeout) {
|
|
124
126
|
lane.snapshot = null;
|
|
125
127
|
rmSync(destination, { force: true });
|
|
126
128
|
lane.context.provide('tmtSession', { ...state, destination });
|
|
127
129
|
const timeout = setTimeout(() => {
|
|
128
130
|
record(state.id === undefined
|
|
129
|
-
? { baseline: { status: 'timeout' } }
|
|
131
|
+
? { baseline: { status: 'timeout', timeoutSeconds: Math.round(timeoutMs / 1000) } }
|
|
130
132
|
: { id: state.id, status: 'timeout', statusReason: 'Vitest did not finish before its deadline' });
|
|
131
133
|
process.exit(124);
|
|
132
|
-
},
|
|
134
|
+
}, timeoutMs);
|
|
133
135
|
try {
|
|
134
136
|
await lane.context.runTestSpecifications(specs);
|
|
135
137
|
if (!lane.snapshot) throw new Error('Vitest did not report a completed run');
|
|
@@ -172,8 +174,14 @@ try {
|
|
|
172
174
|
// its mutations are kept per file.
|
|
173
175
|
const oneByOne = { maxWorkers: 1, fileParallelism: false };
|
|
174
176
|
const beside = concurrency === 1 || isolatedTrials ? oneByOne : { maxWorkers: concurrency };
|
|
177
|
+
const resolveWorkers = lane => {
|
|
178
|
+
if (lane.workerOverride !== undefined) {
|
|
179
|
+
return lane.workerOverride === 1 ? oneByOne : { maxWorkers: lane.workerOverride };
|
|
180
|
+
}
|
|
181
|
+
return lane.serial ? oneByOne : beside;
|
|
182
|
+
};
|
|
175
183
|
createContext = async lane => {
|
|
176
|
-
const workers = lane
|
|
184
|
+
const workers = resolveWorkers(lane);
|
|
177
185
|
const created = await createVitest('test', {
|
|
178
186
|
root: workspace, config, watch: false, api: false, ui: false, cache: false,
|
|
179
187
|
pool: 'threads', isolate: true, maxConcurrency: 1, ...workers,
|
|
@@ -194,17 +202,25 @@ try {
|
|
|
194
202
|
}
|
|
195
203
|
return created;
|
|
196
204
|
};
|
|
197
|
-
|
|
198
|
-
const
|
|
205
|
+
const trialWorkers = concurrency === 1 || isolatedTrials ? 1 : concurrency;
|
|
206
|
+
const distinctBaselineLane = baselineWorkers !== undefined && baselineWorkers !== trialWorkers;
|
|
207
|
+
const baselineLane = await openLane('baseline', false, distinctBaselineLane ? baselineWorkers : undefined);
|
|
208
|
+
lanes.push(baselineLane);
|
|
209
|
+
const { specs } = baselineLane;
|
|
199
210
|
const discovered = new Set(specs.map(spec => inside(workspace, spec.moduleId)));
|
|
200
211
|
if (files.length && (files.some(file => !discovered.has(file)) || discovered.size !== files.length)) {
|
|
201
212
|
throw new Error('Vitest test selection mismatch');
|
|
202
213
|
}
|
|
203
214
|
const baselineState = { phase: 'baseline' };
|
|
204
215
|
const baselineStarted = Date.now();
|
|
205
|
-
const baseline = await run(specs, baselineState);
|
|
206
|
-
const baselineTiming =
|
|
216
|
+
const baseline = await run(specs, baselineState, baselineLane, baselineTimeout);
|
|
217
|
+
const baselineTiming = baselineLane.timing;
|
|
207
218
|
const baselineTime = Date.now() - baselineStarted;
|
|
219
|
+
if (distinctBaselineLane) {
|
|
220
|
+
await Promise.race([baselineLane.context.close(), new Promise(resolveClose => setTimeout(resolveClose, 5_000))]);
|
|
221
|
+
lanes.length = 0;
|
|
222
|
+
lanes.push(await openLane(0));
|
|
223
|
+
}
|
|
208
224
|
const passed = baseline.snapshot.tests.filter(test => test.status === 'passed');
|
|
209
225
|
const tests = new Map(passed.map(test => [test.id, test]));
|
|
210
226
|
const coveredModules = new Set(baseline.records.flatMap(record => record.modules.map(([project, file]) =>
|
|
@@ -226,11 +242,13 @@ try {
|
|
|
226
242
|
unknown: seen.unknown, ...(seen.realCopy ? { realCopy: true } : {}), ...(seen.nonArray ? { nonArray: true } : {}), ...(seen.nonPlain ? { nonPlain: true } : {}) }])) });
|
|
227
243
|
}
|
|
228
244
|
const pending = [];
|
|
245
|
+
let settledBeforeDecide = 0;
|
|
229
246
|
for (const mutant of mutants.filter(candidate => !candidate.parametric)) {
|
|
230
247
|
const { id } = mutant;
|
|
231
248
|
const plan = baselineCoverage(id);
|
|
232
249
|
if (!plan.hits) {
|
|
233
250
|
record({ id, status: 'unreached' });
|
|
251
|
+
settledBeforeDecide++;
|
|
234
252
|
continue;
|
|
235
253
|
}
|
|
236
254
|
// `??` and `||` give the same for null, undefined and every object. Where no test gave the left side a value
|
|
@@ -238,12 +256,14 @@ try {
|
|
|
238
256
|
const seen = agreement.get(id);
|
|
239
257
|
if (mutant.evidence && seen && !seen.differing.size && !seen.unsure.size && !seen.outside && !seen.outsideUnsure && !seen.typed) {
|
|
240
258
|
record({ id, status: 'ignored', statusReason: 'No test gives the left side a number, a string or a boolean, so both operators are taken to behave alike here' });
|
|
259
|
+
settledBeforeDecide++;
|
|
241
260
|
continue;
|
|
242
261
|
}
|
|
243
262
|
// `expr[0]` on a plain map or `arguments` object is not a sequence: mutating to `.at(-1)` would only raise
|
|
244
263
|
// a TypeError noise kill. Never skip if any baseline evaluation threw (exception behavior is unverified).
|
|
245
264
|
if (mutant.sequenceIndex && seen && !seen.sequence && seen.nonSequence && !seen.threw && !seen.differing.size && !seen.outside) {
|
|
246
265
|
record({ id, status: 'ignored', statusReason: 'No test passes a sequence (array, string, or typed array) to this index expression' });
|
|
266
|
+
settledBeforeDecide++;
|
|
247
267
|
continue;
|
|
248
268
|
}
|
|
249
269
|
pending.push({ mutant, plan });
|
|
@@ -257,7 +277,7 @@ try {
|
|
|
257
277
|
const { now, gone } = changedReach(reach, runs);
|
|
258
278
|
return { now: named(now), gone: named(gone) };
|
|
259
279
|
};
|
|
260
|
-
const decide = async (pending, report) => {
|
|
280
|
+
const decide = async (pending, report, trackProgress = false) => {
|
|
261
281
|
const plans = isolatedTrials ? null : planInThread(baseline.records, tests, pending, workspace, baselineTiming);
|
|
262
282
|
let settled = new Map();
|
|
263
283
|
let reasons = new Map();
|
|
@@ -267,11 +287,55 @@ try {
|
|
|
267
287
|
const sampled = new Set();
|
|
268
288
|
if (plans) {
|
|
269
289
|
const limit = 15_000 + 3 * baselineTime;
|
|
290
|
+
let onTrialEvent = null;
|
|
291
|
+
let onProgressTick = null;
|
|
292
|
+
if (trackProgress) {
|
|
293
|
+
const remainingFiles = new Map();
|
|
294
|
+
for (const list of Object.values(plans)) {
|
|
295
|
+
for (const plan of list) {
|
|
296
|
+
remainingFiles.set(plan.id, (remainingFiles.get(plan.id) ?? 0) + 1);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
const completedInWorker = new Set();
|
|
300
|
+
const seenModuleAnswer = new Set();
|
|
301
|
+
const maxProvisional = Math.max(0, pending.length - 1);
|
|
302
|
+
const emitIntervalMs = Math.min(2_000, Math.max(50, Math.floor((progressIntervalMs ?? 5_000) / 2)));
|
|
303
|
+
let lastEmitted = 0;
|
|
304
|
+
let lastEmitAt = Date.now();
|
|
305
|
+
const flushProgress = () => {
|
|
306
|
+
const reportedCount = Math.min(completedInWorker.size, maxProvisional);
|
|
307
|
+
const now = Date.now();
|
|
308
|
+
if (reportedCount > lastEmitted && now - lastEmitAt >= emitIntervalMs) {
|
|
309
|
+
lastEmitted = reportedCount;
|
|
310
|
+
lastEmitAt = now;
|
|
311
|
+
record({ progress: { completed: settledBeforeDecide + reportedCount } });
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
onProgressTick = flushProgress;
|
|
315
|
+
onTrialEvent = event => {
|
|
316
|
+
if (event.id === undefined || !remainingFiles.has(event.id)) return;
|
|
317
|
+
const cleanAnswer = event.elapsed !== undefined && event.hits > 0 && !event.unhandled &&
|
|
318
|
+
!(event.errors?.length) && !event.foreign && !event.missing;
|
|
319
|
+
const isKilled = cleanAnswer && Array.isArray(event.failed) && event.failed.length > 0;
|
|
320
|
+
if (isKilled) {
|
|
321
|
+
completedInWorker.add(event.id);
|
|
322
|
+
} else if (cleanAnswer) {
|
|
323
|
+
const key = JSON.stringify([event.module, event.id]);
|
|
324
|
+
if (!seenModuleAnswer.has(key)) {
|
|
325
|
+
seenModuleAnswer.add(key);
|
|
326
|
+
const left = remainingFiles.get(event.id) - 1;
|
|
327
|
+
remainingFiles.set(event.id, left);
|
|
328
|
+
if (left <= 0) completedInWorker.add(event.id);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
flushProgress();
|
|
332
|
+
};
|
|
333
|
+
}
|
|
270
334
|
// The first lane starts alone with a deadline. Most plans end within it. What is left is timed by then, and a
|
|
271
335
|
// further lane, which costs a Vitest instance, its transforms and an environment per test file, opens for
|
|
272
336
|
// every six seconds of measured work in the longest test file.
|
|
273
337
|
const inLanes = async step => {
|
|
274
|
-
const events = await runInThread(lanes[0], step, limit, Date.now() + 2_000);
|
|
338
|
+
const events = await runInThread(lanes[0], step, limit, Date.now() + 2_000, onTrialEvent, onProgressTick);
|
|
275
339
|
// Each further round takes what is left: entries the deadline cut off, and test files that start again
|
|
276
340
|
// in a new worker after a control run differed.
|
|
277
341
|
for (let round = 0; round < 12; round++) {
|
|
@@ -290,7 +354,7 @@ try {
|
|
|
290
354
|
(_, index) => openLane(lanes.length + index).catch(() => null)));
|
|
291
355
|
lanes.push(...opened.filter(Boolean));
|
|
292
356
|
const shares = sharePlans(left, Math.min(wanted, lanes.length));
|
|
293
|
-
const answered = (await Promise.all(shares.map((share, index) => runInThread(lanes[index], share, limit)))).flat();
|
|
357
|
+
const answered = (await Promise.all(shares.map((share, index) => runInThread(lanes[index], share, limit, undefined, onTrialEvent, onProgressTick)))).flat();
|
|
294
358
|
if (!answered.some(event => event.id !== undefined || event.stop !== undefined)) break;
|
|
295
359
|
events.push(...answered);
|
|
296
360
|
}
|
|
@@ -339,7 +403,7 @@ try {
|
|
|
339
403
|
totals.sampled += sampled.size;
|
|
340
404
|
totals.inWorkerUsed ||= plans !== null;
|
|
341
405
|
};
|
|
342
|
-
await decide(pending, (mutant, result) => record({ id: mutant.id, ...result }));
|
|
406
|
+
await decide(pending, (mutant, result) => record({ id: mutant.id, ...result }), true);
|
|
343
407
|
if (awaitsExtras) {
|
|
344
408
|
// Threshold edits of the focused analysis: each names a comparison and how far its right side moves.
|
|
345
409
|
const extras = [];
|
package/src/targeted-gaps.mjs
CHANGED
|
@@ -25,7 +25,7 @@ const roundingDiffers = { 'floor trunc': 'negative and not a whole number (-0.5)
|
|
|
25
25
|
'floor round': 'a number that rounds up (1.5, -1.5)', 'ceil round': 'a number that rounds down (1.4, -1.6)',
|
|
26
26
|
'round trunc': 'a number that rounds away from zero (1.5, -1.6)', 'ceil floor': 'not a whole number (0.5)' };
|
|
27
27
|
|
|
28
|
-
function missingInput({ operator, form, boolean, left, right: rightExpr, differsFor, subject, pureRight, rightFalsy, key, boundKind, pruned, argName }, expression, rule, replacement) {
|
|
28
|
+
function missingInput({ operator, form, boolean, left, right: rightExpr, differsFor, subject, pureRight, rightFalsy, possibleFalsy, key, boundKind, pruned, argName }, expression, rule, replacement) {
|
|
29
29
|
const side = '`' + clip(left) + '`';
|
|
30
30
|
if (rule === rules.spreadDrop) return `a test in which \`${clip(left)}.${key}\` is missing or differs from its updated value`;
|
|
31
31
|
if (rule === rules.prefixSubstring) {
|
|
@@ -49,12 +49,21 @@ function missingInput({ operator, form, boolean, left, right: rightExpr, differs
|
|
|
49
49
|
if (form === 'true' || form === 'false') return `a test in which \`${clip(expression)}\` is ${form === 'true' ? 'false' : 'true'}`;
|
|
50
50
|
if (form === 'loose' || form === 'strict' || form === 'other') return `a test in which \`${clip(subject)}\` is ${differsFor}`;
|
|
51
51
|
if (form === 'or' || form === 'nullish') {
|
|
52
|
+
const allFalsy = ['0', '0n', "''", 'false', 'NaN'];
|
|
53
|
+
const baseValues = Array.isArray(possibleFalsy) && possibleFalsy.length ? possibleFalsy : allFalsy;
|
|
54
|
+
const formatList = values => values.length === 1
|
|
55
|
+
? values[0]
|
|
56
|
+
: `${values.slice(0, -1).join(', ')} or ${values.at(-1)}`;
|
|
52
57
|
if (rightFalsy) {
|
|
53
|
-
const
|
|
54
|
-
const
|
|
55
|
-
|
|
58
|
+
const filtered = baseValues.filter(value => value !== rightFalsy);
|
|
59
|
+
const values = filtered.length
|
|
60
|
+
? filtered
|
|
61
|
+
: baseValues.length === 1 && baseValues[0] === '0' && rightFalsy === '0'
|
|
62
|
+
? ['-0']
|
|
63
|
+
: allFalsy.filter(value => value !== rightFalsy);
|
|
64
|
+
return `a test in which ${side} is ${formatList(values)}`;
|
|
56
65
|
}
|
|
57
|
-
return `a test in which ${side} is
|
|
66
|
+
return `a test in which ${side} is ${formatList(baseValues)}${pureRight ? ' and not the right side\'s value' : ''}`;
|
|
58
67
|
}
|
|
59
68
|
const takesRight = { '&&': 'truthy', '||': 'falsy', '??': 'null or undefined' }[operator];
|
|
60
69
|
if (form === 'left') return `a test in which ${side} is ${{ '&&': 'falsy', '||': 'truthy', '??': 'neither null nor undefined' }[operator]}`;
|
package/src/type-equivalence.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { existsSync, realpathSync } from 'node:fs';
|
|
2
|
-
import { dirname, resolve } from 'node:path';
|
|
1
|
+
import { existsSync, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
3
3
|
import { loadTypeScript } from './typescript-compiler.mjs';
|
|
4
4
|
|
|
5
5
|
const PRIMITIVE_PROTOTYPE_KEYS = new Set([
|
|
@@ -99,9 +99,13 @@ function collectNonNullishFalsy(ts, checker, type, out = new Set(), seen = new S
|
|
|
99
99
|
}
|
|
100
100
|
if (flags & ts.TypeFlags.NumberLiteral) {
|
|
101
101
|
// Numeric enum types accept arbitrary numbers (including 0 and NaN) without a TypeScript error.
|
|
102
|
-
if (
|
|
102
|
+
if (flags & (ts.TypeFlags.Enum | ts.TypeFlags.EnumLiteral)) {
|
|
103
103
|
out.add('number_zero');
|
|
104
104
|
out.add('number_nan');
|
|
105
|
+
} else if (type.value === 0 || Object.is(type.value, -0)) {
|
|
106
|
+
out.add('number_zero');
|
|
107
|
+
} else if (Number.isNaN(type.value)) {
|
|
108
|
+
out.add('number_nan');
|
|
105
109
|
}
|
|
106
110
|
return out;
|
|
107
111
|
}
|
|
@@ -114,15 +118,26 @@ function collectNonNullishFalsy(ts, checker, type, out = new Set(), seen = new S
|
|
|
114
118
|
return 'any';
|
|
115
119
|
}
|
|
116
120
|
|
|
117
|
-
function
|
|
121
|
+
function falsyLabelsFromSet(falsy) {
|
|
122
|
+
if (falsy === 'any') return null;
|
|
123
|
+
const labels = [];
|
|
124
|
+
if (falsy.has('number_zero')) labels.push('0');
|
|
125
|
+
if (falsy.has('bigint')) labels.push('0n');
|
|
126
|
+
if (falsy.has('string')) labels.push("''");
|
|
127
|
+
if (falsy.has('boolean')) labels.push('false');
|
|
128
|
+
if (falsy.has('number_nan')) labels.push('NaN');
|
|
129
|
+
return labels;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function hasLocalValueBinding(ts, checker, node, name) {
|
|
118
133
|
if (typeof checker.resolveName === 'function') {
|
|
119
|
-
const sym = checker.resolveName(
|
|
134
|
+
const sym = checker.resolveName(name, node, ts.SymbolFlags.Value, false);
|
|
120
135
|
if (sym?.declarations?.some(decl => !decl.getSourceFile().isDeclarationFile)) return true;
|
|
121
136
|
}
|
|
122
137
|
if (typeof checker.getSymbolsInScope === 'function') {
|
|
123
138
|
const inScope = checker.getSymbolsInScope(node, ts.SymbolFlags.Value);
|
|
124
139
|
for (const sym of inScope) {
|
|
125
|
-
if (sym.name ===
|
|
140
|
+
if (sym.name === name && sym.declarations?.some(decl => !decl.getSourceFile().isDeclarationFile)) {
|
|
126
141
|
return true;
|
|
127
142
|
}
|
|
128
143
|
}
|
|
@@ -130,6 +145,10 @@ function hasLocalUndefinedBinding(ts, checker, node) {
|
|
|
130
145
|
return false;
|
|
131
146
|
}
|
|
132
147
|
|
|
148
|
+
function hasLocalUndefinedBinding(ts, checker, node) {
|
|
149
|
+
return hasLocalValueBinding(ts, checker, node, 'undefined');
|
|
150
|
+
}
|
|
151
|
+
|
|
133
152
|
function isUncheckedIndexedRead(ts, checker, node) {
|
|
134
153
|
while (node && ts.isParenthesizedExpression(node)) node = node.expression;
|
|
135
154
|
if (!node) return false;
|
|
@@ -163,44 +182,124 @@ function indexExpressions(ts, sourceFile) {
|
|
|
163
182
|
return nodes;
|
|
164
183
|
}
|
|
165
184
|
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
185
|
+
function isWithinRoot(realRoot, candidate) {
|
|
186
|
+
const rel = relative(realRoot, candidate);
|
|
187
|
+
return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('..' + sep));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function normalizePath(filePath) {
|
|
191
|
+
return existsSync(filePath) ? realpathSync(filePath) : resolve(filePath);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function readParsedConfig(ts, configPath, cache) {
|
|
195
|
+
const key = normalizePath(configPath);
|
|
196
|
+
if (cache.has(key)) return cache.get(key);
|
|
197
|
+
if (!existsSync(key)) {
|
|
198
|
+
const missing = { configPath: key, missing: true, strictNullChecks: false };
|
|
199
|
+
cache.set(key, missing);
|
|
200
|
+
return missing;
|
|
173
201
|
}
|
|
174
|
-
const read = ts.readConfigFile(
|
|
202
|
+
const read = ts.readConfigFile(key, ts.sys.readFile);
|
|
175
203
|
if (read.error || !read.config) {
|
|
176
|
-
|
|
204
|
+
const failed = { configPath: key, error: true, strictNullChecks: false };
|
|
205
|
+
cache.set(key, failed);
|
|
206
|
+
return failed;
|
|
177
207
|
}
|
|
178
|
-
const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(
|
|
208
|
+
const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(key));
|
|
179
209
|
const compilerOptions = parsed.options ?? {};
|
|
180
210
|
const strictNullChecks = compilerOptions.strictNullChecks === true ||
|
|
181
211
|
(compilerOptions.strict === true && compilerOptions.strictNullChecks !== false);
|
|
182
|
-
|
|
183
|
-
|
|
212
|
+
const fileNames = new Set((parsed.fileNames ?? []).map(normalizePath));
|
|
213
|
+
const info = {
|
|
214
|
+
configPath: key,
|
|
215
|
+
parsed,
|
|
216
|
+
compilerOptions,
|
|
217
|
+
strictNullChecks,
|
|
218
|
+
noUncheckedIndexedAccess: compilerOptions.noUncheckedIndexedAccess === true,
|
|
219
|
+
projectReferences: parsed.projectReferences ?? [],
|
|
220
|
+
fileNames,
|
|
221
|
+
};
|
|
222
|
+
cache.set(key, info);
|
|
223
|
+
return info;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function resolveReferenceConfigPath(refPath) {
|
|
227
|
+
const resolved = resolve(refPath);
|
|
228
|
+
const st = statSync(resolved, { throwIfNoEntry: false });
|
|
229
|
+
if (st?.isDirectory()) return resolve(resolved, 'tsconfig.json');
|
|
230
|
+
return resolved;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function findConfigViaReferences(ts, configPath, absFile, cache, visited = new Set()) {
|
|
234
|
+
const key = normalizePath(configPath);
|
|
235
|
+
if (visited.has(key)) return null;
|
|
236
|
+
visited.add(key);
|
|
237
|
+
const info = readParsedConfig(ts, key, cache);
|
|
238
|
+
if (info.missing || info.error) return null;
|
|
239
|
+
for (const ref of info.projectReferences) {
|
|
240
|
+
const refConfigPath = resolveReferenceConfigPath(ref.path);
|
|
241
|
+
if (!existsSync(refConfigPath)) continue;
|
|
242
|
+
const refInfo = readParsedConfig(ts, refConfigPath, cache);
|
|
243
|
+
if (refInfo.missing || refInfo.error) continue;
|
|
244
|
+
if (refInfo.fileNames.has(absFile)) return refInfo.configPath;
|
|
245
|
+
if (refInfo.projectReferences.length) {
|
|
246
|
+
const nested = findConfigViaReferences(ts, refInfo.configPath, absFile, cache, visited);
|
|
247
|
+
if (nested) return nested;
|
|
248
|
+
}
|
|
184
249
|
}
|
|
185
|
-
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
186
252
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
253
|
+
function collectAncestorConfigsInRoot(ts, realRoot, startDir) {
|
|
254
|
+
const configs = [];
|
|
255
|
+
let dir = startDir;
|
|
256
|
+
while (isWithinRoot(realRoot, dir)) {
|
|
257
|
+
const candidate = resolve(dir, 'tsconfig.json');
|
|
258
|
+
if (ts.sys.fileExists(candidate)) configs.push(normalizePath(candidate));
|
|
259
|
+
const parent = dirname(dir);
|
|
260
|
+
if (parent === dir) break;
|
|
261
|
+
dir = parent;
|
|
195
262
|
}
|
|
263
|
+
return configs;
|
|
264
|
+
}
|
|
196
265
|
|
|
266
|
+
function resolveConfigForFile(ts, realRoot, absFile, explicitConfigPath, cache) {
|
|
267
|
+
if (explicitConfigPath) return explicitConfigPath;
|
|
268
|
+
const ancestors = collectAncestorConfigsInRoot(ts, realRoot, dirname(absFile));
|
|
269
|
+
if (!ancestors.length) {
|
|
270
|
+
const fallback = ts.findConfigFile(realRoot, ts.sys.fileExists, 'tsconfig.json');
|
|
271
|
+
if (fallback) ancestors.push(normalizePath(fallback));
|
|
272
|
+
}
|
|
273
|
+
if (!ancestors.length) return null;
|
|
274
|
+
|
|
275
|
+
// Walk from nearest ancestor upward: if a config has projectReferences, prefer an owning
|
|
276
|
+
// referenced config before falling back to an ancestor config that merely includes absFile.
|
|
277
|
+
for (const configPath of ancestors) {
|
|
278
|
+
const info = readParsedConfig(ts, configPath, cache);
|
|
279
|
+
if (info.missing || info.error) continue;
|
|
280
|
+
if (info.projectReferences.length) {
|
|
281
|
+
const fromRef = findConfigViaReferences(ts, configPath, absFile, cache);
|
|
282
|
+
if (fromRef) return fromRef;
|
|
283
|
+
}
|
|
284
|
+
if (info.fileNames.has(absFile)) {
|
|
285
|
+
return configPath;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// Fallback to the nearest ancestor tsconfig so warnings report the actual config checked.
|
|
290
|
+
return ancestors[0];
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function buildGroupContext(ts, info, absTargets) {
|
|
294
|
+
const { compilerOptions, noUncheckedIndexedAccess, parsed } = info;
|
|
295
|
+
const ambientDts = (parsed.fileNames ?? []).filter(file => file.endsWith('.d.ts'));
|
|
296
|
+
const rootNames = [...new Set([...absTargets, ...ambientDts])];
|
|
297
|
+
if (!rootNames.length) return () => null;
|
|
197
298
|
const program = ts.createProgram(rootNames, { ...compilerOptions, noEmit: true });
|
|
198
299
|
const checker = program.getTypeChecker();
|
|
199
300
|
const fileCache = new Map();
|
|
200
301
|
|
|
201
|
-
|
|
202
|
-
const resolved = resolve(realRoot, file);
|
|
203
|
-
const absFile = existsSync(resolved) ? realpathSync(resolved) : resolved;
|
|
302
|
+
return (absFile, resolved) => {
|
|
204
303
|
if (fileCache.has(absFile)) return fileCache.get(absFile);
|
|
205
304
|
const sourceFile = program.getSourceFile(absFile) ?? program.getSourceFile(resolved);
|
|
206
305
|
if (!sourceFile) {
|
|
@@ -236,10 +335,107 @@ export function createTypeContext(root, targetFiles = [], { tsconfig, ts = loadT
|
|
|
236
335
|
}
|
|
237
336
|
return false;
|
|
238
337
|
},
|
|
338
|
+
possibleNullishFallbackFalsy(leftStart, leftEnd) {
|
|
339
|
+
const node = nodes.get(`${leftStart}:${leftEnd}`);
|
|
340
|
+
if (!node) return null;
|
|
341
|
+
const type = checker.getTypeAtLocation(node);
|
|
342
|
+
if (!type) return null;
|
|
343
|
+
return falsyLabelsFromSet(collectNonNullishFalsy(ts, checker, type));
|
|
344
|
+
},
|
|
345
|
+
hasLocalNaNBinding(nodeStart, nodeEnd) {
|
|
346
|
+
const node = nodes.get(`${nodeStart}:${nodeEnd}`);
|
|
347
|
+
return node ? hasLocalValueBinding(ts, checker, node, 'NaN') : false;
|
|
348
|
+
},
|
|
239
349
|
};
|
|
240
350
|
fileCache.set(absFile, helper);
|
|
241
351
|
return helper;
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export function createTypeContext(root, targetFiles = [], { tsconfig, onWarning, ts = loadTypeScript() } = {}) {
|
|
356
|
+
const realRoot = existsSync(root) ? realpathSync(root) : resolve(root);
|
|
357
|
+
const configCache = new Map();
|
|
358
|
+
const warnings = [];
|
|
359
|
+
const seenWarnings = new Set();
|
|
360
|
+
const warn = message => {
|
|
361
|
+
if (seenWarnings.has(message)) return;
|
|
362
|
+
seenWarnings.add(message);
|
|
363
|
+
warnings.push(message);
|
|
364
|
+
onWarning?.(message);
|
|
365
|
+
};
|
|
366
|
+
const labelConfig = configPath => {
|
|
367
|
+
const rel = relative(realRoot, configPath);
|
|
368
|
+
return rel && !isAbsolute(rel) && !rel.startsWith('..' + sep) ? rel : configPath;
|
|
369
|
+
};
|
|
370
|
+
const explicitConfigPath = tsconfig ? resolve(realRoot, tsconfig) : null;
|
|
371
|
+
|
|
372
|
+
if (!targetFiles.length) {
|
|
373
|
+
const configPath = explicitConfigPath ?? ts.findConfigFile(realRoot, ts.sys.fileExists, 'tsconfig.json');
|
|
374
|
+
if (!configPath || !existsSync(configPath)) {
|
|
375
|
+
warn(explicitConfigPath
|
|
376
|
+
? `--type-check: tsconfig file not found (${tsconfig}); skipping type-based suppression.`
|
|
377
|
+
: '--type-check: no tsconfig.json found; skipping type-based suppression.');
|
|
378
|
+
return { strictNullChecks: false, warnings, forFile: () => null };
|
|
379
|
+
}
|
|
380
|
+
const info = readParsedConfig(ts, configPath, configCache);
|
|
381
|
+
if (info.error) {
|
|
382
|
+
warn(`--type-check: failed to read ${labelConfig(configPath)}; skipping type-based suppression.`);
|
|
383
|
+
return { strictNullChecks: false, warnings, forFile: () => null };
|
|
384
|
+
}
|
|
385
|
+
if (!info.strictNullChecks) {
|
|
386
|
+
warn(`--type-check: strictNullChecks is not enabled in ${labelConfig(configPath)}; skipping type-based suppression.`);
|
|
387
|
+
}
|
|
388
|
+
return { strictNullChecks: info.strictNullChecks, warnings, forFile: () => null };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
const grouped = new Map();
|
|
392
|
+
const fileToConfig = new Map();
|
|
393
|
+
for (const file of targetFiles) {
|
|
394
|
+
const resolved = resolve(realRoot, file);
|
|
395
|
+
const absFile = normalizePath(resolved);
|
|
396
|
+
const configPath = resolveConfigForFile(ts, realRoot, absFile, explicitConfigPath, configCache);
|
|
397
|
+
if (!configPath) {
|
|
398
|
+
warn(`--type-check: no tsconfig.json found for ${file}; skipping type-based suppression.`);
|
|
399
|
+
fileToConfig.set(absFile, null);
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
const key = normalizePath(configPath);
|
|
403
|
+
fileToConfig.set(absFile, key);
|
|
404
|
+
if (!grouped.has(key)) grouped.set(key, []);
|
|
405
|
+
grouped.get(key).push(absFile);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const groupLookups = new Map();
|
|
409
|
+
let anyStrictNullChecks = false;
|
|
410
|
+
for (const [configPath, absTargets] of grouped) {
|
|
411
|
+
const info = readParsedConfig(ts, configPath, configCache);
|
|
412
|
+
if (info.missing) {
|
|
413
|
+
warn(`--type-check: tsconfig file not found (${tsconfig ?? labelConfig(configPath)}); skipping type-based suppression.`);
|
|
414
|
+
groupLookups.set(configPath, () => null);
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
if (info.error) {
|
|
418
|
+
warn(`--type-check: failed to read ${labelConfig(configPath)}; skipping type-based suppression.`);
|
|
419
|
+
groupLookups.set(configPath, () => null);
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
if (!info.strictNullChecks) {
|
|
423
|
+
warn(`--type-check: strictNullChecks is not enabled in ${labelConfig(configPath)}; skipping type-based suppression.`);
|
|
424
|
+
groupLookups.set(configPath, () => null);
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
anyStrictNullChecks = true;
|
|
428
|
+
groupLookups.set(configPath, buildGroupContext(ts, info, absTargets));
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function forFile(file) {
|
|
432
|
+
const resolved = resolve(realRoot, file);
|
|
433
|
+
const absFile = normalizePath(resolved);
|
|
434
|
+
const configKey = fileToConfig.get(absFile);
|
|
435
|
+
if (!configKey) return null;
|
|
436
|
+
const lookup = groupLookups.get(configKey);
|
|
437
|
+
return lookup ? lookup(absFile, resolved) : null;
|
|
242
438
|
}
|
|
243
439
|
|
|
244
|
-
return { strictNullChecks:
|
|
440
|
+
return { strictNullChecks: anyStrictNullChecks, warnings, forFile };
|
|
245
441
|
}
|