reading-stone 0.0.0-stage → 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.
- package/LICENSE +201 -0
- package/NOTICE +11 -0
- package/README.md +274 -2
- package/dist/analysis.d.ts +341 -0
- package/dist/analysis.js +392 -0
- package/dist/cognitive.d.ts +163 -0
- package/dist/cognitive.js +380 -0
- package/dist/complexity.d.ts +102 -0
- package/dist/complexity.js +163 -0
- package/dist/coverage.d.ts +78 -0
- package/dist/coverage.js +635 -0
- package/dist/detector.d.ts +41 -0
- package/dist/detector.js +2134 -0
- package/dist/discovery.d.ts +330 -0
- package/dist/discovery.js +930 -0
- package/dist/doc-coverage.d.ts +155 -0
- package/dist/doc-coverage.js +543 -0
- package/dist/extract.d.ts +209 -0
- package/dist/extract.js +498 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +54 -0
- package/dist/internal.d.ts +75 -0
- package/dist/internal.js +63 -0
- package/dist/main.d.ts +8 -0
- package/dist/main.js +39 -0
- package/dist/models.d.ts +185 -0
- package/dist/models.js +170 -0
- package/dist/program.d.ts +207 -0
- package/dist/program.js +662 -0
- package/dist/protocol.d.ts +88 -0
- package/dist/protocol.js +74 -0
- package/dist/quality/assertions.d.ts +81 -0
- package/dist/quality/assertions.js +425 -0
- package/dist/quality/collect.d.ts +66 -0
- package/dist/quality/collect.js +412 -0
- package/dist/quality/inference.d.ts +86 -0
- package/dist/quality/inference.js +603 -0
- package/dist/quality/matchers.d.ts +129 -0
- package/dist/quality/matchers.js +220 -0
- package/dist/quality/pairing.d.ts +133 -0
- package/dist/quality/pairing.js +770 -0
- package/dist/quality/pipeline.d.ts +59 -0
- package/dist/quality/pipeline.js +202 -0
- package/dist/quality/types.d.ts +127 -0
- package/dist/quality/types.js +92 -0
- package/dist/safeio.d.ts +107 -0
- package/dist/safeio.js +314 -0
- package/dist/server.d.ts +19 -0
- package/dist/server.js +451 -0
- package/dist/signals/adapter.d.ts +103 -0
- package/dist/signals/adapter.js +323 -0
- package/dist/signals/caller-index.d.ts +117 -0
- package/dist/signals/caller-index.js +147 -0
- package/dist/signals/caller.d.ts +76 -0
- package/dist/signals/caller.js +108 -0
- package/dist/signals/evidence.d.ts +233 -0
- package/dist/signals/evidence.js +578 -0
- package/dist/signals/interface.d.ts +68 -0
- package/dist/signals/interface.js +87 -0
- package/dist/signals/jsdoc.d.ts +27 -0
- package/dist/signals/jsdoc.js +233 -0
- package/dist/signals/naming.d.ts +26 -0
- package/dist/signals/naming.js +160 -0
- package/dist/signals/routing.d.ts +163 -0
- package/dist/signals/routing.js +416 -0
- package/dist/signals/types.d.ts +146 -0
- package/dist/signals/types.js +99 -0
- package/dist/signals/visibility.d.ts +23 -0
- package/dist/signals/visibility.js +82 -0
- package/dist/taxonomy.d.ts +89 -0
- package/dist/taxonomy.js +217 -0
- package/package.json +61 -4
package/dist/coverage.js
ADDED
|
@@ -0,0 +1,635 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { normalizePatterns, pathInScope } from "./analysis.js";
|
|
3
|
+
import { resolveRoot } from "./discovery.js";
|
|
4
|
+
import { relativeUnderBase } from "./internal.js";
|
|
5
|
+
import { MAX_FILE_BYTES, readBounded } from "./safeio.js";
|
|
6
|
+
/**
|
|
7
|
+
* The Istanbul coverage artifact parser (FR-023–FR-026; research R10;
|
|
8
|
+
* data-model.md's Istanbul document model; Constitution Principles I, II,
|
|
9
|
+
* and V). `parseCoverage` (T028) reads the pre-existing
|
|
10
|
+
* `<root>/coverage/coverage-final.json` — the conventional output location
|
|
11
|
+
* for both vitest's and jest's Istanbul JSON reporters — and attributes
|
|
12
|
+
* each statement to its innermost enclosing function.
|
|
13
|
+
*
|
|
14
|
+
* **Consumption, never production** (FR-025 — the constitution's required
|
|
15
|
+
* conflict-resolution record): the analyzer never runs the analyzed
|
|
16
|
+
* project's tests and never collects coverage itself. The artifact is the
|
|
17
|
+
* pre-existing output of the project's own test run, read through the
|
|
18
|
+
* bounded safe reader at the full 16 MiB budget — JSON cannot parse from a
|
|
19
|
+
* truncated prefix, the `package.json` precedent — so analyzed code is
|
|
20
|
+
* never executed (Principle V) and no single artifact can dominate memory.
|
|
21
|
+
* The `coverage/` directory is pruned from WALKING only; the artifact is
|
|
22
|
+
* read directly by its conventional path and the tree is never walked for
|
|
23
|
+
* coverage. Root validation is unchanged: `resolveRoot` →
|
|
24
|
+
* `InvalidRootPathError` → the server's `-32602` (contracts/coverage.md).
|
|
25
|
+
*
|
|
26
|
+
* **Degradation ladder** (FR-025): an absent artifact, a skipped read, a
|
|
27
|
+
* JSON parse failure, or a non-object top level each yield the empty entry
|
|
28
|
+
* list — never a JSON-RPC error. A skipped read has already written its
|
|
29
|
+
* one stderr diagnostic line inside `readBounded`; the parse-failure and
|
|
30
|
+
* non-object rungs stay silent because there is nothing to report and
|
|
31
|
+
* nothing wrong with the request. One further rung is deliberately NOT
|
|
32
|
+
* silent: a parseable object document in which no file entry holds the
|
|
33
|
+
* referenced shape writes exactly one diagnostic line — `reading-stone:
|
|
34
|
+
* skipping coverage document: no conforming file entries` — because a
|
|
35
|
+
* document that parses yet conforms nowhere is the signature of an
|
|
36
|
+
* emitter-shape mismatch, and reporting empty there silently was a false
|
|
37
|
+
* negative (Principle II). An empty `{}` document has no keys and stays
|
|
38
|
+
* silent: nothing conformed, but nothing failed to either.
|
|
39
|
+
*
|
|
40
|
+
* **Per-entry tolerance** (FR-026): within a parseable document, a file
|
|
41
|
+
* entry whose `statementMap`, `fnMap`, or `s` — or the shapes they
|
|
42
|
+
* reference — do not hold is skipped deterministically while conforming
|
|
43
|
+
* entries report; the document is never rejected wholesale. The file entry
|
|
44
|
+
* is the unit of conformance (data-model.md), so one malformed record
|
|
45
|
+
* anywhere in a file entry skips that whole entry: partial reads of a
|
|
46
|
+
* half-conforming entry would report counts the document never asserted.
|
|
47
|
+
* `branchMap`/`b`/`f` may be present and are ignored — `s` is the only
|
|
48
|
+
* execution-count source (the fixtures plant `f` values that contradict
|
|
49
|
+
* `s` precisely to pin this).
|
|
50
|
+
*
|
|
51
|
+
* **Null end columns** (the vitest v8 emitter's real shape): Istanbul's
|
|
52
|
+
* v8 coverage pipeline writes `"column": null` on END positions whenever
|
|
53
|
+
* the sourcemap carries no column information — the motivating artifact
|
|
54
|
+
* had null end columns on 1542 of 1558 statementMap records and in the
|
|
55
|
+
* fnMap decl/loc ranges of 272 positions across its 250 records — so
|
|
56
|
+
* requiring a numeric end column rejected every entry of a real document.
|
|
57
|
+
* The conformance check therefore requires a numeric `line` on both
|
|
58
|
+
* positions and a numeric START column, accepts a null or absent end
|
|
59
|
+
* column, and normalizes it to the end-of-line sentinel
|
|
60
|
+
* (`UNBOUNDED_END_COLUMN`): the range then deterministically contains
|
|
61
|
+
* every position on its end line.
|
|
62
|
+
*
|
|
63
|
+
* **Resource bounds** (Principle V — the artifact is untrusted input):
|
|
64
|
+
* attribution is O(statements × functions) per file entry, which the
|
|
65
|
+
* 16 MiB read bound alone does not bound. Two budgets mirror extract.ts's
|
|
66
|
+
* AST depth budget: a file entry over either per-entry record cap
|
|
67
|
+
* (`MAX_STATEMENTS_PER_FILE_ENTRY` / `MAX_FUNCTIONS_PER_FILE_ENTRY`) is
|
|
68
|
+
* skipped with one diagnostic line, and a document-level attribution work
|
|
69
|
+
* budget (`MAX_ATTRIBUTION_WORK`, the running sum of statements ×
|
|
70
|
+
* functions) skips any entry that would exceed its remainder, likewise
|
|
71
|
+
* one line per skip. Skips are deterministic — JSON key enumeration order
|
|
72
|
+
* is spec-defined — and never throw or become a JSON-RPC error.
|
|
73
|
+
*/
|
|
74
|
+
/**
|
|
75
|
+
* The conventional artifact location (FR-023; contracts/coverage.md): the
|
|
76
|
+
* only path read — root-relative, so `readBounded`'s containment check
|
|
77
|
+
* accepts it — and not configurable via params in v1 (projects writing
|
|
78
|
+
* coverage elsewhere report empty coverage; documented limitation).
|
|
79
|
+
*/
|
|
80
|
+
const COVERAGE_ARTIFACT_PATH = "coverage/coverage-final.json";
|
|
81
|
+
/**
|
|
82
|
+
* The end-of-line sentinel a null or absent END column normalizes to (the
|
|
83
|
+
* vitest v8 emitter's real shape — see the module header): Istanbul's v8
|
|
84
|
+
* pipeline writes `"column": null` when a sourcemap position carries no
|
|
85
|
+
* column information, meaning "no column bound on this line", so the
|
|
86
|
+
* normalized range contains every position on its end line. A real column
|
|
87
|
+
* can never reach it, and the spans it inflates (end-minus-start) only
|
|
88
|
+
* lose "smallest span" attribution contests to precisely bounded ranges —
|
|
89
|
+
* the deterministic, conservative direction.
|
|
90
|
+
*/
|
|
91
|
+
const UNBOUNDED_END_COLUMN = Number.MAX_SAFE_INTEGER;
|
|
92
|
+
/**
|
|
93
|
+
* The per-file-entry record caps (Principle V; the extract.ts
|
|
94
|
+
* AST-depth-budget precedent): a file entry whose statementMap or fnMap
|
|
95
|
+
* holds more records than these caps is skipped with one stderr
|
|
96
|
+
* diagnostic line. Real entries sit orders of magnitude below (the
|
|
97
|
+
* motivating artifact's largest file entry: 618 statements, 90
|
|
98
|
+
* functions), while a 16 MiB document can carry far more — and
|
|
99
|
+
* attribution cost grows with the product, not the sum, of the two
|
|
100
|
+
* counts.
|
|
101
|
+
*/
|
|
102
|
+
const MAX_STATEMENTS_PER_FILE_ENTRY = 50_000;
|
|
103
|
+
const MAX_FUNCTIONS_PER_FILE_ENTRY = 5_000;
|
|
104
|
+
/**
|
|
105
|
+
* The document-level attribution work budget: the cumulative sum of
|
|
106
|
+
* statements × functions across admitted file entries never exceeds this
|
|
107
|
+
* many containment comparisons (tens of milliseconds at V8 speed), and an
|
|
108
|
+
* entry that would exceed the remainder is skipped with one stderr
|
|
109
|
+
* diagnostic line. Sized to clear real projects with room to spare (the
|
|
110
|
+
* motivating artifact needs 74,536 work units total) while capping the
|
|
111
|
+
* multiplicatively adversarial document the 16 MiB read bound alone
|
|
112
|
+
* permits.
|
|
113
|
+
*/
|
|
114
|
+
const MAX_ATTRIBUTION_WORK = 25_000_000;
|
|
115
|
+
/**
|
|
116
|
+
* The `coverage` method's entry (FR-023–FR-026; the analyze-shaped surface
|
|
117
|
+
* T018 established): the serialized `CoverageEntry[]` payload — one entry
|
|
118
|
+
* per fnMap function of every conforming, contained, in-scope file entry,
|
|
119
|
+
* assembled in the `(file, start_line, function)` total order, and mapped
|
|
120
|
+
* through `serializeCoverageEntry` so every entry on the returned array is
|
|
121
|
+
* already wire-shaped.
|
|
122
|
+
*
|
|
123
|
+
* The returned array — not a `{functions: [...]}` wrapper — is the
|
|
124
|
+
* documented result shape the server wraps into its JSON-RPC success
|
|
125
|
+
* response (T029); both this entry and the payload are deterministic pure
|
|
126
|
+
* functions of the analyzed tree and artifact (Constitution Principle I:
|
|
127
|
+
* byte-identical repeat responses). The full degradation ladder (FR-025)
|
|
128
|
+
* resolves to the empty array, never a thrown error: only `resolveRoot`'s
|
|
129
|
+
* `InvalidRootPathError` escapes, for the server to map to `-32602`.
|
|
130
|
+
*
|
|
131
|
+
* Unlike `analyze`/`computeComplexity` there is no pipeline to prepare and
|
|
132
|
+
* no compiler context to own: the tree is never walked (discovery
|
|
133
|
+
* confinement is deliberately absent — FR-024 pins root containment and
|
|
134
|
+
* `patterns` only, so a document entry with no on-disk source still
|
|
135
|
+
* reports, research R10), and no native resource outlives the call.
|
|
136
|
+
*
|
|
137
|
+
* @param rootPath Absolute or relative project root; validated and
|
|
138
|
+
* realpath-resolved by `resolveRoot` (an invalid root throws
|
|
139
|
+
* `InvalidRootPathError`, the server maps to `-32602`). Document keys
|
|
140
|
+
* are contained against both this request's cwd-resolved spelling and
|
|
141
|
+
* the realpath form (see `containedRelativePath`).
|
|
142
|
+
* @param patterns The raw `patterns` parameter value; shape-validated by
|
|
143
|
+
* the server (`-32602`, T019) before analysis runs, normalized here
|
|
144
|
+
* through the same FR-001 helpers `analyze` filters with.
|
|
145
|
+
* @param stderr Injected diagnostic sink (Testability principle); defaults
|
|
146
|
+
* to `process.stderr`. Stdout is never touched.
|
|
147
|
+
* @returns The serialized coverage entries, `(file, start_line,
|
|
148
|
+
* function)`-sorted; empty on every degradation-ladder rung.
|
|
149
|
+
*/
|
|
150
|
+
export async function parseCoverage(rootPath, patterns, stderr = process.stderr) {
|
|
151
|
+
const realRoot = await resolveRoot(rootPath);
|
|
152
|
+
// The request's cwd-resolved root spelling — resolveRoot's step-1
|
|
153
|
+
// arithmetic, before its step-2 realpath. Document keys are contained
|
|
154
|
+
// against it alongside the canonical form (see containedRelativePath).
|
|
155
|
+
const logicalRoot = resolve(rootPath);
|
|
156
|
+
// The artifact is read through the bounded safe reader at the full 16 MiB
|
|
157
|
+
// budget: JSON cannot parse from a truncated prefix, so a smaller marker
|
|
158
|
+
// budget (the generated-marker precedent) is useless here — the package.json
|
|
159
|
+
// precedent (research R10). A skip resolves null after readBounded's own
|
|
160
|
+
// one-diagnostic line (absent, unreadable, symlink, oversized).
|
|
161
|
+
const text = await readBounded(realRoot, COVERAGE_ARTIFACT_PATH, MAX_FILE_BYTES, stderr);
|
|
162
|
+
if (text === null) {
|
|
163
|
+
return [];
|
|
164
|
+
}
|
|
165
|
+
let document;
|
|
166
|
+
try {
|
|
167
|
+
document = JSON.parse(text);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return []; // Unparseable document (FR-025) — empty coverage, not an error.
|
|
171
|
+
}
|
|
172
|
+
if (!isRecord(document)) {
|
|
173
|
+
return []; // Non-object top level — array, scalar, or null (FR-025).
|
|
174
|
+
}
|
|
175
|
+
// The same normalize-then-test pair every pattern-filtered method applies
|
|
176
|
+
// (FR-024; R11): the helpers are shared with analyze/complexity, so "the
|
|
177
|
+
// same path-prefix rules" is structural, never re-derived here.
|
|
178
|
+
const patternSet = normalizePatterns(patterns);
|
|
179
|
+
const entries = [];
|
|
180
|
+
// Conformance is counted over the WHOLE document, not the contained,
|
|
181
|
+
// in-scope subset: the zero-conformance diagnostic below reports a
|
|
182
|
+
// document whose every entry fails the referenced shape — an
|
|
183
|
+
// emitter-mismatch signature — while a request whose patterns match
|
|
184
|
+
// nothing, or a document keyed entirely outside the root, is a
|
|
185
|
+
// legitimate empty result over a conforming document and must stay
|
|
186
|
+
// silent. Conformance therefore runs before the key-string rejections;
|
|
187
|
+
// parseFileCoverage is linear in the already-16-MiB-bound document, so
|
|
188
|
+
// validating a key this request will filter out costs nothing the read
|
|
189
|
+
// has not already paid.
|
|
190
|
+
let fileEntryCount = 0;
|
|
191
|
+
let conformingFileEntries = 0;
|
|
192
|
+
// The document-level attribution work budget (Principle V): admission
|
|
193
|
+
// consumes statements × functions, and an entry that would exceed the
|
|
194
|
+
// remainder is skipped below.
|
|
195
|
+
let attributionWorkRemaining = MAX_ATTRIBUTION_WORK;
|
|
196
|
+
for (const [key, value] of Object.entries(document)) {
|
|
197
|
+
fileEntryCount += 1;
|
|
198
|
+
const fileCoverage = parseFileCoverage(value);
|
|
199
|
+
if (fileCoverage === null) {
|
|
200
|
+
continue; // Non-conforming file entry (FR-026).
|
|
201
|
+
}
|
|
202
|
+
conformingFileEntries += 1;
|
|
203
|
+
// Containment (FR-024): a key that does not resolve under either
|
|
204
|
+
// spelling of the root is skipped whatever its payload. Then the
|
|
205
|
+
// pattern filter — cheap key-string rejections.
|
|
206
|
+
const relPath = containedRelativePath(realRoot, logicalRoot, key);
|
|
207
|
+
if (relPath === null) {
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (!pathInScope(relPath, patternSet)) {
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
// The per-entry record caps (Principle V): a file entry this large is
|
|
214
|
+
// pathological, and attribution cost grows with the product of the
|
|
215
|
+
// two counts — skip it with one diagnostic line, never an error.
|
|
216
|
+
const statementCount = Object.keys(fileCoverage.statementMap).length;
|
|
217
|
+
const functionCount = Object.keys(fileCoverage.fnMap).length;
|
|
218
|
+
if (statementCount > MAX_STATEMENTS_PER_FILE_ENTRY ||
|
|
219
|
+
functionCount > MAX_FUNCTIONS_PER_FILE_ENTRY) {
|
|
220
|
+
stderr.write(`reading-stone: skipping ${relPath}: coverage record budget exceeded\n`);
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
// The document-level work budget: an entry that would exhaust the
|
|
224
|
+
// remainder is skipped with one diagnostic line. Later, smaller
|
|
225
|
+
// entries can still fit what remains; the JSON key enumeration order
|
|
226
|
+
// that decides admission is spec-defined, so the skip set is
|
|
227
|
+
// deterministic.
|
|
228
|
+
const attributionWork = statementCount * functionCount;
|
|
229
|
+
if (attributionWork > attributionWorkRemaining) {
|
|
230
|
+
stderr.write(`reading-stone: skipping ${relPath}: attribution work budget exceeded\n`);
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
attributionWorkRemaining -= attributionWork;
|
|
234
|
+
// A bounded push, never a spread: near the 16 MiB read bound a
|
|
235
|
+
// document's file entries can together emit more entries than a
|
|
236
|
+
// single spread call's argument limit allows (RangeError around 10^5
|
|
237
|
+
// arguments), while the entries array itself stays far below any
|
|
238
|
+
// engine limit.
|
|
239
|
+
for (const entry of coverageEntriesFor(relPath, fileCoverage)) {
|
|
240
|
+
entries.push(entry);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
// The zero-conformance diagnostic (see the module header): fire only
|
|
244
|
+
// when the document had keys at all — an empty {} document conformed
|
|
245
|
+
// nowhere but also failed nowhere.
|
|
246
|
+
if (fileEntryCount > 0 && conformingFileEntries === 0) {
|
|
247
|
+
stderr.write("reading-stone: skipping coverage document: no conforming file entries\n");
|
|
248
|
+
}
|
|
249
|
+
entries.sort(compareEntries);
|
|
250
|
+
return entries.map(serializeCoverageEntry);
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Whether `value` is a plain object — the document model's "object"
|
|
254
|
+
* (FR-026): `typeof` object, not null, and not an array. Istanbul's maps
|
|
255
|
+
* are keyed by string ids, so an array is as non-conforming as a scalar;
|
|
256
|
+
* rejecting both keeps the check total where `typeof` alone is not.
|
|
257
|
+
*
|
|
258
|
+
* @param value The parsed JSON value to test.
|
|
259
|
+
* @returns Whether the value is a non-array, non-null object.
|
|
260
|
+
*/
|
|
261
|
+
function isRecord(value) {
|
|
262
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Whether `value` holds the referenced START `Pos` shape: an object whose
|
|
266
|
+
* `line` and `column` are both numbers. JSON.parse cannot produce NaN or
|
|
267
|
+
* Infinity, so `typeof` is the whole finiteness story for parsed input;
|
|
268
|
+
* deeper range checks (integer, 1-based) are not pinned by the document
|
|
269
|
+
* model and would risk dropping entries FR-024 requires reporting.
|
|
270
|
+
*
|
|
271
|
+
* @param value The parsed JSON value to test.
|
|
272
|
+
* @returns Whether the value is a start position of the referenced shape.
|
|
273
|
+
*/
|
|
274
|
+
function isStartPosition(value) {
|
|
275
|
+
return (isRecord(value) &&
|
|
276
|
+
typeof value.line === "number" &&
|
|
277
|
+
typeof value.column === "number");
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Whether `value` holds the referenced END `Pos` shape: a numeric `line`,
|
|
281
|
+
* and a `column` that is a number or null/absent. Istanbul's v8 emitters
|
|
282
|
+
* (vitest's coverage pipeline) write `"column": null` on end positions
|
|
283
|
+
* when the sourcemap carries no column information — the motivating
|
|
284
|
+
* real-world artifact had null end columns on 1542 of 1558 statementMap
|
|
285
|
+
* records — so a conformance check demanding a numeric end column
|
|
286
|
+
* rejected every entry of a real document (a silent false negative,
|
|
287
|
+
* Principle II). A null or absent end column normalizes to the
|
|
288
|
+
* end-of-line sentinel in `parseSourceRange`.
|
|
289
|
+
*
|
|
290
|
+
* @param value The parsed JSON value to test.
|
|
291
|
+
* @returns Whether the value is an end position of the referenced shape.
|
|
292
|
+
*/
|
|
293
|
+
function isEndPosition(value) {
|
|
294
|
+
return (isRecord(value) &&
|
|
295
|
+
typeof value.line === "number" &&
|
|
296
|
+
(typeof value.column === "number" ||
|
|
297
|
+
value.column === null ||
|
|
298
|
+
value.column === undefined));
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Validates one referenced `Loc` shape and returns it NORMALIZED: a fresh
|
|
302
|
+
* range whose null or absent end column (see `isEndPosition`) is replaced
|
|
303
|
+
* by the end-of-line sentinel, so every position downstream
|
|
304
|
+
* (`comparePositions`, `rangeContains`, span math) sees numeric columns
|
|
305
|
+
* and the rules stay total. Both positions are copied fresh, so the types
|
|
306
|
+
* rest on validation rather than casts and the normalized range never
|
|
307
|
+
* aliases the parsed document.
|
|
308
|
+
*
|
|
309
|
+
* @param value The parsed JSON range to validate.
|
|
310
|
+
* @returns The normalized range, or null when the referenced shape does
|
|
311
|
+
* not hold.
|
|
312
|
+
*/
|
|
313
|
+
function parseSourceRange(value) {
|
|
314
|
+
if (!isRecord(value) || !isStartPosition(value.start) || !isEndPosition(value.end)) {
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
const end = value.end;
|
|
318
|
+
const endColumn = typeof end.column === "number" ? end.column : UNBOUNDED_END_COLUMN;
|
|
319
|
+
return {
|
|
320
|
+
start: { line: value.start.line, column: value.start.column },
|
|
321
|
+
end: { line: end.line, column: endColumn },
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Validates one referenced fnMap record shape and returns it with its
|
|
326
|
+
* `decl`/`loc` ranges normalized (see `parseSourceRange`): an object with
|
|
327
|
+
* a string `name` and two conforming ranges. A record missing any of the
|
|
328
|
+
* three (the SHAPELESS_FN fixture: `decl` present, `loc` absent) is
|
|
329
|
+
* non-conforming — the referenced shape does not hold, so FR-026 skips
|
|
330
|
+
* the file entry. Extra fields (real Istanbul records carry them) are not
|
|
331
|
+
* violations: the conformance check verifies the required shape, never
|
|
332
|
+
* forbids additions.
|
|
333
|
+
*
|
|
334
|
+
* @param value The parsed JSON value to validate.
|
|
335
|
+
* @returns The normalized fnMap record, or null when non-conforming.
|
|
336
|
+
*/
|
|
337
|
+
function parseFnMapRecord(value) {
|
|
338
|
+
if (!isRecord(value) || typeof value.name !== "string") {
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
const decl = parseSourceRange(value.decl);
|
|
342
|
+
const loc = parseSourceRange(value.loc);
|
|
343
|
+
if (decl === null || loc === null) {
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
return { name: value.name, decl, loc };
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Validates one file entry against the conformance check (FR-026) and
|
|
350
|
+
* returns it with its three maps narrowed to typed records — fresh,
|
|
351
|
+
* normalized copies (a null or absent end column becomes the end-of-line
|
|
352
|
+
* sentinel; see `parseSourceRange`), so the types rest on validation
|
|
353
|
+
* rather than casts.
|
|
354
|
+
*
|
|
355
|
+
* The unit of conformance is the whole file entry: `statementMap`, `fnMap`,
|
|
356
|
+
* and `s` must be objects AND every value they reference must hold its
|
|
357
|
+
* shape, or the entry is skipped. A statement id missing from `s` is not a
|
|
358
|
+
* shape violation — `s`'s referenced shape is "statementId → number" for
|
|
359
|
+
* the ids it carries — so such a statement counts toward `total_stmts`
|
|
360
|
+
* uncovered (the pinned `s[id] > 0` formula reads absence as not-executed).
|
|
361
|
+
*
|
|
362
|
+
* @param value The parsed file-entry value.
|
|
363
|
+
* @returns The validated file coverage, or null when non-conforming.
|
|
364
|
+
*/
|
|
365
|
+
function parseFileCoverage(value) {
|
|
366
|
+
if (!isRecord(value)) {
|
|
367
|
+
return null; // A scalar or array file entry (FR-026).
|
|
368
|
+
}
|
|
369
|
+
const { statementMap, fnMap, s } = value;
|
|
370
|
+
if (!isRecord(statementMap) || !isRecord(fnMap) || !isRecord(s)) {
|
|
371
|
+
return null; // A missing or non-object map (FR-026).
|
|
372
|
+
}
|
|
373
|
+
const statements = {};
|
|
374
|
+
for (const [id, range] of Object.entries(statementMap)) {
|
|
375
|
+
const parsed = parseSourceRange(range);
|
|
376
|
+
if (parsed === null) {
|
|
377
|
+
return null;
|
|
378
|
+
}
|
|
379
|
+
statements[id] = parsed;
|
|
380
|
+
}
|
|
381
|
+
const functions = {};
|
|
382
|
+
for (const [id, record] of Object.entries(fnMap)) {
|
|
383
|
+
const parsed = parseFnMapRecord(record);
|
|
384
|
+
if (parsed === null) {
|
|
385
|
+
return null;
|
|
386
|
+
}
|
|
387
|
+
functions[id] = parsed;
|
|
388
|
+
}
|
|
389
|
+
const counts = {};
|
|
390
|
+
for (const [id, count] of Object.entries(s)) {
|
|
391
|
+
if (typeof count !== "number") {
|
|
392
|
+
return null;
|
|
393
|
+
}
|
|
394
|
+
counts[id] = count;
|
|
395
|
+
}
|
|
396
|
+
return { statementMap: statements, fnMap: functions, s: counts };
|
|
397
|
+
}
|
|
398
|
+
// ---------------------------------------------------------------------------
|
|
399
|
+
// Attribution (FR-023; contracts/coverage.md; research R10)
|
|
400
|
+
// ---------------------------------------------------------------------------
|
|
401
|
+
/**
|
|
402
|
+
* Compares two positions as `(line, column)` — line first, then column
|
|
403
|
+
* (FR-023's pinned comparison).
|
|
404
|
+
*
|
|
405
|
+
* @param a Left position.
|
|
406
|
+
* @param b Right position.
|
|
407
|
+
* @returns Negative, zero, or positive as `a` sorts before, equal, or after.
|
|
408
|
+
*/
|
|
409
|
+
function comparePositions(a, b) {
|
|
410
|
+
if (a.line !== b.line) {
|
|
411
|
+
return a.line - b.line;
|
|
412
|
+
}
|
|
413
|
+
return a.column - b.column;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Whether `range` contains `position` inclusively: the position sorts on or
|
|
417
|
+
* after the range's start and on or before its end (both compared as
|
|
418
|
+
* `(line, column)`).
|
|
419
|
+
*
|
|
420
|
+
* @param range The candidate containing range.
|
|
421
|
+
* @param position The statement's start position.
|
|
422
|
+
* @returns Whether the position lies within the range.
|
|
423
|
+
*/
|
|
424
|
+
function rangeContains(range, position) {
|
|
425
|
+
return (comparePositions(position, range.start) >= 0 &&
|
|
426
|
+
comparePositions(position, range.end) <= 0);
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Compares two spans as `(lineCount, columnExtent)`, lines primary.
|
|
430
|
+
*
|
|
431
|
+
* @param a Left span.
|
|
432
|
+
* @param b Right span.
|
|
433
|
+
* @returns Negative, zero, or positive as `a` is smaller, equal, or larger.
|
|
434
|
+
*/
|
|
435
|
+
function compareSpans(a, b) {
|
|
436
|
+
if (a[0] !== b[0]) {
|
|
437
|
+
return a[0] - b[0];
|
|
438
|
+
}
|
|
439
|
+
return a[1] - b[1];
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Attributes one statement start to its innermost containing fnMap function
|
|
443
|
+
* (FR-023): among the functions whose `loc` range contains the position,
|
|
444
|
+
* the smallest span wins; equal spans fall to the lexicographically
|
|
445
|
+
* smallest fnMap key, so the rule is total (the tie fixture's keys "2" and
|
|
446
|
+
* "10" name identical ranges — "10" < "2" decides, discriminated from
|
|
447
|
+
* insertion order). A start contained by no range attributes to nothing.
|
|
448
|
+
*
|
|
449
|
+
* @param fnMap The file entry's validated fnMap.
|
|
450
|
+
* @param start The statement's start position.
|
|
451
|
+
* @returns The owning fnMap key, or null when no range contains the start.
|
|
452
|
+
*/
|
|
453
|
+
function attributeStatement(fnMap, start) {
|
|
454
|
+
let bestKey = null;
|
|
455
|
+
let bestSpan = null;
|
|
456
|
+
for (const [key, record] of Object.entries(fnMap)) {
|
|
457
|
+
if (!rangeContains(record.loc, start)) {
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
const span = [
|
|
461
|
+
record.loc.end.line - record.loc.start.line,
|
|
462
|
+
record.loc.end.column - record.loc.start.column,
|
|
463
|
+
];
|
|
464
|
+
// Smallest span wins; an equal span falls to the smaller fnMap key.
|
|
465
|
+
const versusBest = bestSpan === null ? -1 : compareSpans(span, bestSpan);
|
|
466
|
+
if (versusBest < 0 || (versusBest === 0 && bestKey !== null && key < bestKey)) {
|
|
467
|
+
bestKey = key;
|
|
468
|
+
bestSpan = span;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
return bestKey;
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Builds one file entry's coverage entries: attribute every statementMap
|
|
475
|
+
* statement to its innermost function, count per function, then emit one
|
|
476
|
+
* entry per fnMap function — functions with no attributed statements
|
|
477
|
+
* included, reporting `total_stmts` 0 and exactly `percentage` 0 (FR-023's
|
|
478
|
+
* no-division-error rule; the empty-body fixture).
|
|
479
|
+
*
|
|
480
|
+
* Statements inside a nested function's range count toward the innermost
|
|
481
|
+
* enclosing function only (US4 scenario 7): attribution assigns each
|
|
482
|
+
* statement to exactly one owner, so the enclosing function's totals never
|
|
483
|
+
* include the nested statement. Entries are constructed in lexicographic
|
|
484
|
+
* fnMap-key order, so full `(file, start_line, function)` ties keep a
|
|
485
|
+
* deterministic relative order through the stable final sort.
|
|
486
|
+
*
|
|
487
|
+
* @param relPath The file entry's root-relative POSIX path.
|
|
488
|
+
* @param fileCoverage The file entry's validated maps.
|
|
489
|
+
* @returns One coverage entry per fnMap function, fnMap-key-ordered.
|
|
490
|
+
*/
|
|
491
|
+
function coverageEntriesFor(relPath, fileCoverage) {
|
|
492
|
+
const coveredCounts = new Map();
|
|
493
|
+
const totalCounts = new Map();
|
|
494
|
+
for (const [id, range] of Object.entries(fileCoverage.statementMap)) {
|
|
495
|
+
const owner = attributeStatement(fileCoverage.fnMap, range.start);
|
|
496
|
+
if (owner === null) {
|
|
497
|
+
continue; // No fnMap range contains the start: unattributed.
|
|
498
|
+
}
|
|
499
|
+
totalCounts.set(owner, (totalCounts.get(owner) ?? 0) + 1);
|
|
500
|
+
const count = fileCoverage.s[id];
|
|
501
|
+
if (count !== undefined && count > 0) {
|
|
502
|
+
coveredCounts.set(owner, (coveredCounts.get(owner) ?? 0) + 1);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
const entries = [];
|
|
506
|
+
for (const [key, record] of Object.entries(fileCoverage.fnMap).sort(compareFnMapKeys)) {
|
|
507
|
+
const totalStmts = totalCounts.get(key) ?? 0;
|
|
508
|
+
const coveredStmts = coveredCounts.get(key) ?? 0;
|
|
509
|
+
entries.push({
|
|
510
|
+
file: relPath,
|
|
511
|
+
function: record.name,
|
|
512
|
+
start_line: record.decl.start.line,
|
|
513
|
+
end_line: record.loc.end.line,
|
|
514
|
+
covered_stmts: coveredStmts,
|
|
515
|
+
total_stmts: totalStmts,
|
|
516
|
+
// Multiply-first association: (covered * 100) / total reproduces the
|
|
517
|
+
// pinned double 66.66666666666667 for 2-of-3; the division-first
|
|
518
|
+
// (covered / total) * 100 is one ulp lower. Total 0 is exactly 0.0 —
|
|
519
|
+
// never a division error (FR-023).
|
|
520
|
+
percentage: totalStmts === 0 ? 0 : (coveredStmts * 100) / totalStmts,
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
return entries;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Compares fnMap entry pairs by key — code-unit comparison (not
|
|
527
|
+
* `localeCompare`, which is locale-dependent) — for the canonical
|
|
528
|
+
* construction order inside one file entry.
|
|
529
|
+
*
|
|
530
|
+
* @param a Left [key, record] pair.
|
|
531
|
+
* @param b Right [key, record] pair.
|
|
532
|
+
* @returns The key comparison result.
|
|
533
|
+
*/
|
|
534
|
+
function compareFnMapKeys(a, b) {
|
|
535
|
+
if (a[0] !== b[0]) {
|
|
536
|
+
return a[0] < b[0] ? -1 : 1;
|
|
537
|
+
}
|
|
538
|
+
return 0;
|
|
539
|
+
}
|
|
540
|
+
// ---------------------------------------------------------------------------
|
|
541
|
+
// Containment, ordering, and serialization (FR-024)
|
|
542
|
+
// ---------------------------------------------------------------------------
|
|
543
|
+
/**
|
|
544
|
+
* Normalizes one document file key against ONE spelling of the analysis
|
|
545
|
+
* root. Both emitter shapes key files — vitest root-relatively, jest
|
|
546
|
+
* absolutely — so every key resolves against that root before the shared
|
|
547
|
+
* containment helper reduces it: an absolute key passes `resolve`
|
|
548
|
+
* unchanged, and a relative key joins the root. Containment itself is
|
|
549
|
+
* `relativeUnderBase` (src/internal.ts) — lexical, with the deliberately
|
|
550
|
+
* literal `..` defense — and its separator normalization to POSIX
|
|
551
|
+
* mirrors the wire contract every other root-relative path honors.
|
|
552
|
+
*
|
|
553
|
+
* @param root One spelling of the absolute analysis root.
|
|
554
|
+
* @param key The document's file key (relative or absolute).
|
|
555
|
+
* @returns The root-relative POSIX path, or null when not under this root.
|
|
556
|
+
*/
|
|
557
|
+
function relativeUnderRoot(root, key) {
|
|
558
|
+
return relativeUnderBase(root, resolve(root, key));
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Normalizes one document file key to its root-relative POSIX path, or
|
|
562
|
+
* rejects it (FR-024's spec edge case), trying BOTH spellings of the
|
|
563
|
+
* analysis root: the realpath form `resolveRoot` canonicalized to, and
|
|
564
|
+
* the request's cwd-resolved `root_path` it canonicalized FROM. An
|
|
565
|
+
* Istanbul document keys files by whatever spelling the emitting test
|
|
566
|
+
* run saw — jest keys absolutely, and a `root_path` spelled through a
|
|
567
|
+
* symlink (macOS's `/var` → `/private/var`, a linked workspace)
|
|
568
|
+
* realpaths to a different lexical form, so a document keyed by the
|
|
569
|
+
* request's own spelling would be silently dropped — a false negative
|
|
570
|
+
* Principle II forbids. Both spellings denote the same directory
|
|
571
|
+
* (`resolveRoot` derived the one from the other), so neither admits an
|
|
572
|
+
* escape the other would not; at most one can contain an absolute key,
|
|
573
|
+
* so the outcome stays a deterministic function of the request and
|
|
574
|
+
* document (Principle I). A key under neither is skipped.
|
|
575
|
+
*
|
|
576
|
+
* @param realRoot The realpath-resolved analysis root.
|
|
577
|
+
* @param logicalRoot The request's cwd-resolved root spelling.
|
|
578
|
+
* @param key The document's file key (relative or absolute).
|
|
579
|
+
* @returns The root-relative POSIX path, or null when not under the root.
|
|
580
|
+
*/
|
|
581
|
+
function containedRelativePath(realRoot, logicalRoot, key) {
|
|
582
|
+
return relativeUnderRoot(realRoot, key) ?? relativeUnderRoot(logicalRoot, key);
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* The FR-024 total order over entries: `(file, start_line, function)`,
|
|
586
|
+
* code-unit comparison for the string keys, numeric line ordering between
|
|
587
|
+
* them, and `0` on full-key ties — applied whatever order the document's
|
|
588
|
+
* keys and fnMaps arrive in, so the wire guarantee holds structurally.
|
|
589
|
+
*
|
|
590
|
+
* @param a Left entry.
|
|
591
|
+
* @param b Right entry.
|
|
592
|
+
* @returns The three-key comparison result.
|
|
593
|
+
*/
|
|
594
|
+
function compareEntries(a, b) {
|
|
595
|
+
if (a.file !== b.file) {
|
|
596
|
+
return a.file < b.file ? -1 : 1;
|
|
597
|
+
}
|
|
598
|
+
if (a.start_line !== b.start_line) {
|
|
599
|
+
return a.start_line - b.start_line;
|
|
600
|
+
}
|
|
601
|
+
if (a.function !== b.function) {
|
|
602
|
+
return a.function < b.function ? -1 : 1;
|
|
603
|
+
}
|
|
604
|
+
return 0;
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Serializes a `CoverageEntry` to its wire shape (FR-024): exactly the
|
|
608
|
+
* seven fields, emitted in the canonical sorted-key order the protocol
|
|
609
|
+
* layer's sorted-key serializer produces — so the server's `serialize`
|
|
610
|
+
* pass re-orders these keys as a structural no-op and each entry is
|
|
611
|
+
* wire-final in the form that serializer defines.
|
|
612
|
+
*
|
|
613
|
+
* A pure projection, deliberately without the fail-loud field validation
|
|
614
|
+
* `models.ts`'s record serializers apply (the `serializeComplexityEntry`
|
|
615
|
+
* precedent): every `CoverageEntry` is constructed at this module's single
|
|
616
|
+
* site from fields whose validity is structural — validated document
|
|
617
|
+
* strings and numbers — and the wire shape itself (exactly these seven
|
|
618
|
+
* keys) is pinned by `tests/coverage.test.ts`'s wire-invariant assertions.
|
|
619
|
+
*
|
|
620
|
+
* @param entry The coverage entry to serialize.
|
|
621
|
+
* @returns A JSON-ready object with `covered_stmts`, `end_line`, `file`,
|
|
622
|
+
* `function`, `percentage`, `start_line`, and `total_stmts`.
|
|
623
|
+
*/
|
|
624
|
+
export function serializeCoverageEntry(entry) {
|
|
625
|
+
return {
|
|
626
|
+
covered_stmts: entry.covered_stmts,
|
|
627
|
+
end_line: entry.end_line,
|
|
628
|
+
file: entry.file,
|
|
629
|
+
function: entry.function,
|
|
630
|
+
percentage: entry.percentage,
|
|
631
|
+
start_line: entry.start_line,
|
|
632
|
+
total_stmts: entry.total_stmts,
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
//# sourceMappingURL=coverage.js.map
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type ExtractionRecord } from "./extract.js";
|
|
2
|
+
import { type Effect, type FunctionRecord } from "./models.js";
|
|
3
|
+
import type { ProgramContext } from "./program.js";
|
|
4
|
+
/**
|
|
5
|
+
* Detects the P0 and P1 side effects of every extraction record
|
|
6
|
+
* (FR-011 through FR-017; research R6).
|
|
7
|
+
*
|
|
8
|
+
* Each record is walked exactly once by a fresh `RecordWalker` (no
|
|
9
|
+
* cross-record state), then `SentinelError` declarations attach per
|
|
10
|
+
* file, then every record's effects are sorted into FR-020's documented
|
|
11
|
+
* `(line, column, canonical type name)` order — dual emissions at one
|
|
12
|
+
* construct and sentinel attachments make emission order alone
|
|
13
|
+
* under-specified, so the total order is applied here where every
|
|
14
|
+
* record's list is complete.
|
|
15
|
+
*
|
|
16
|
+
* @param records The extraction records (any order; the result map
|
|
17
|
+
* preserves the given record order).
|
|
18
|
+
* @param context The analysis context the records came from: its mode
|
|
19
|
+
* decides the typed splits' behavior — program mode consults the live
|
|
20
|
+
* checker, parse-only takes each split's documented type-blind default.
|
|
21
|
+
* @returns Each record's effects, sorted by `(line, column, type)` —
|
|
22
|
+
* empty for a record whose body contains no pinned constructs.
|
|
23
|
+
*/
|
|
24
|
+
export declare function detectEffects(records: readonly ExtractionRecord[], context: ProgramContext): ReadonlyMap<ExtractionRecord, readonly Effect[]>;
|
|
25
|
+
/**
|
|
26
|
+
* FR-020's response assembly: turns the detection result into the
|
|
27
|
+
* `(file, line, name)`-sorted `FunctionRecord[]` — the analyze method's
|
|
28
|
+
* record payload (research R8's record-level total order). Extraction
|
|
29
|
+
* already emits in that order; sorting here makes the order structural
|
|
30
|
+
* rather than inherited, so the wire guarantee holds whatever order the
|
|
31
|
+
* records arrive in.
|
|
32
|
+
*
|
|
33
|
+
* Each record's `package` is derived through `derivePackage` and its
|
|
34
|
+
* `side_effects` are the detector's attribution for that record (empty
|
|
35
|
+
* for records the detection walk left clean — never fabricated).
|
|
36
|
+
*
|
|
37
|
+
* @param records The extraction records, any order.
|
|
38
|
+
* @param effects The detection result — `detectEffects`' per-record map.
|
|
39
|
+
* @returns The assembled records, sorted by `(file, line, name)`.
|
|
40
|
+
*/
|
|
41
|
+
export declare function assembleFunctionRecords(records: readonly ExtractionRecord[], effects: ReadonlyMap<ExtractionRecord, readonly Effect[]>): readonly FunctionRecord[];
|