reading-stone 0.0.0-stage → 0.2.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.
Files changed (72) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +11 -0
  3. package/README.md +301 -2
  4. package/dist/analysis.d.ts +341 -0
  5. package/dist/analysis.js +392 -0
  6. package/dist/cognitive.d.ts +163 -0
  7. package/dist/cognitive.js +380 -0
  8. package/dist/complexity.d.ts +102 -0
  9. package/dist/complexity.js +163 -0
  10. package/dist/coverage.d.ts +78 -0
  11. package/dist/coverage.js +635 -0
  12. package/dist/detector.d.ts +41 -0
  13. package/dist/detector.js +2134 -0
  14. package/dist/discovery.d.ts +330 -0
  15. package/dist/discovery.js +930 -0
  16. package/dist/doc-coverage.d.ts +155 -0
  17. package/dist/doc-coverage.js +543 -0
  18. package/dist/extract.d.ts +209 -0
  19. package/dist/extract.js +498 -0
  20. package/dist/index.d.ts +64 -0
  21. package/dist/index.js +63 -0
  22. package/dist/internal.d.ts +75 -0
  23. package/dist/internal.js +63 -0
  24. package/dist/main.d.ts +8 -0
  25. package/dist/main.js +39 -0
  26. package/dist/models.d.ts +185 -0
  27. package/dist/models.js +170 -0
  28. package/dist/program.d.ts +207 -0
  29. package/dist/program.js +662 -0
  30. package/dist/protocol.d.ts +88 -0
  31. package/dist/protocol.js +74 -0
  32. package/dist/quality/assertions.d.ts +81 -0
  33. package/dist/quality/assertions.js +425 -0
  34. package/dist/quality/collect.d.ts +66 -0
  35. package/dist/quality/collect.js +412 -0
  36. package/dist/quality/inference.d.ts +86 -0
  37. package/dist/quality/inference.js +603 -0
  38. package/dist/quality/matchers.d.ts +129 -0
  39. package/dist/quality/matchers.js +220 -0
  40. package/dist/quality/pairing.d.ts +133 -0
  41. package/dist/quality/pairing.js +770 -0
  42. package/dist/quality/pipeline.d.ts +59 -0
  43. package/dist/quality/pipeline.js +202 -0
  44. package/dist/quality/types.d.ts +127 -0
  45. package/dist/quality/types.js +92 -0
  46. package/dist/safeio.d.ts +107 -0
  47. package/dist/safeio.js +314 -0
  48. package/dist/server.d.ts +19 -0
  49. package/dist/server.js +451 -0
  50. package/dist/signals/adapter.d.ts +103 -0
  51. package/dist/signals/adapter.js +323 -0
  52. package/dist/signals/caller-index.d.ts +117 -0
  53. package/dist/signals/caller-index.js +147 -0
  54. package/dist/signals/caller.d.ts +76 -0
  55. package/dist/signals/caller.js +108 -0
  56. package/dist/signals/evidence.d.ts +233 -0
  57. package/dist/signals/evidence.js +578 -0
  58. package/dist/signals/interface.d.ts +68 -0
  59. package/dist/signals/interface.js +87 -0
  60. package/dist/signals/jsdoc.d.ts +27 -0
  61. package/dist/signals/jsdoc.js +233 -0
  62. package/dist/signals/naming.d.ts +26 -0
  63. package/dist/signals/naming.js +160 -0
  64. package/dist/signals/routing.d.ts +163 -0
  65. package/dist/signals/routing.js +416 -0
  66. package/dist/signals/types.d.ts +146 -0
  67. package/dist/signals/types.js +99 -0
  68. package/dist/signals/visibility.d.ts +23 -0
  69. package/dist/signals/visibility.js +82 -0
  70. package/dist/taxonomy.d.ts +89 -0
  71. package/dist/taxonomy.js +217 -0
  72. package/package.json +61 -4
@@ -0,0 +1,380 @@
1
+ import { isArrowFunction, isBinaryExpression, isBreakOrContinueStatement, isCallExpression, isCaseClause, isConditionalExpression, isDecorator, isDoStatement, isForInStatement, isForOfStatement, isForStatement, isFunctionExpression, isIdentifier, isIfStatement, isParenthesizedExpression, isPropertyAccessExpression, isSwitchStatement, isThisExpression, isTryStatement, isWhileStatement, SyntaxKind, } from "typescript/unstable/ast";
2
+ import { prepareAnalysis } from "./analysis.js";
3
+ import { isExtractedFunctionLike } from "./extract.js";
4
+ import { compareFileLineName } from "./internal.js";
5
+ import { derivePackage } from "./models.js";
6
+ /**
7
+ * The `cognitive_complexity` method's entry (FR-005, FR-009; the
8
+ * analyze-shaped surface T018 established): the serialized `CognitiveRow[]`
9
+ * payload — one row per extraction record, assembled in the `(file, line,
10
+ * name)` total order, and mapped through `serializeCognitiveRow` so every
11
+ * row on the returned array is already wire-shaped.
12
+ *
13
+ * The returned array — not a `{functions: [...]}` wrapper — follows the
14
+ * computeComplexity split: the T017 server handler wraps the array into the
15
+ * cognitive_complexity result shape, exactly as it wraps the complexity
16
+ * entries. Both this entry and its payload are deterministic pure functions
17
+ * of the analyzed tree (Constitution Principle I: byte-identical repeat
18
+ * responses).
19
+ *
20
+ * The program-mode context's lifetime is this handler's: the native
21
+ * compiler server behind it is closed in the `finally` whatever the scoring
22
+ * outcome, so no subprocess outlives one analysis. A parse-only context
23
+ * owns nothing to dispose.
24
+ *
25
+ * @param rootPath Absolute or relative project root; validated and
26
+ * realpath-resolved by `prepareAnalysis` (an invalid root throws
27
+ * `InvalidRootPathError`, the server maps to `-32602`).
28
+ * @param patterns The raw `patterns` parameter value; shape-validated by
29
+ * the server (`-32602`) before analysis runs, normalized here.
30
+ * @param stderr Injected diagnostic sink (Testability principle); defaults
31
+ * to `process.stderr`. Stdout is never touched.
32
+ * @returns The serialized cognitive rows, `(file, line, name)`-sorted.
33
+ */
34
+ export async function cognitiveComplexity(rootPath, patterns, stderr = process.stderr) {
35
+ const prepared = await prepareAnalysis(rootPath, patterns, stderr);
36
+ try {
37
+ const rows = prepared.records.map((record) => ({
38
+ package: derivePackage(record.relPath),
39
+ function: record.name,
40
+ file: record.relPath,
41
+ line: record.line,
42
+ cognitive_complexity: cognitiveScoreOf(record),
43
+ }));
44
+ rows.sort(compareCognitiveRows);
45
+ return rows.map(serializeCognitiveRow);
46
+ }
47
+ finally {
48
+ if (prepared.context.mode === "program") {
49
+ prepared.context.dispose();
50
+ }
51
+ }
52
+ }
53
+ /**
54
+ * Serializes a `CognitiveRow` to its wire shape (FR-005): exactly the five
55
+ * fields, emitted in the canonical sorted-key order the protocol layer's
56
+ * sorted-key serializer produces — so the server's `serialize` pass
57
+ * re-orders these keys as a structural no-op and each row is wire-final in
58
+ * the form that serializer defines.
59
+ *
60
+ * A pure projection, deliberately without the fail-loud field validation
61
+ * `models.ts`'s record serializers apply (the serializeComplexityEntry
62
+ * argument): every `CognitiveRow` is constructed at this module's single
63
+ * site from fields whose validity is structural — `ExtractionRecord`'s
64
+ * string `name`/`relPath`, a 1-based `line`, and `cognitive_complexity` as
65
+ * the walk's non-negative sum. The wire shape itself — exactly these five
66
+ * keys, integer `cognitive_complexity` ≥ 0 — is pinned by
67
+ * `tests/cognitive.test.ts`'s wire-invariant assertions.
68
+ *
69
+ * @param row The cognitive row to serialize.
70
+ * @returns A JSON-ready object with `cognitive_complexity`, `file`,
71
+ * `function`, `line`, and `package`.
72
+ */
73
+ export function serializeCognitiveRow(row) {
74
+ return {
75
+ cognitive_complexity: row.cognitive_complexity,
76
+ file: row.file,
77
+ function: row.function,
78
+ line: row.line,
79
+ package: row.package,
80
+ };
81
+ }
82
+ /**
83
+ * The FR-005 total order over cognitive rows: `(file, line, name)` via the
84
+ * shared record comparator (src/internal.ts), with the row's `function` key
85
+ * adapted to the comparator's `name` — the identity key and the ORDER key
86
+ * are spelled differently (Assumption 6), the same shape adaptation
87
+ * `extract.ts`'s comparator makes for `ExtractionRecord.relPath`. Codepoint
88
+ * comparison for the string keys, numeric line ordering between them.
89
+ *
90
+ * @param a Left row.
91
+ * @param b Right row.
92
+ * @returns The three-key comparison result.
93
+ */
94
+ function compareCognitiveRows(a, b) {
95
+ return compareFileLineName({ file: a.file, line: a.line, name: a.function }, { file: b.file, line: b.line, name: b.function });
96
+ }
97
+ /**
98
+ * Whether a binary operator token kind is one of FR-008's sequence
99
+ * operators — the logical `&&`, `||`, and `??` tokens whose chains score
100
+ * per maximal same-operator run (research R7).
101
+ *
102
+ * @param kind The binary operator token kind to test.
103
+ * @returns True for `&&`, `||`, or `??`; false for every other operator
104
+ * (`+`, `<=`, `instanceof`, …), which never forms a sequence.
105
+ */
106
+ function isLogicalSequenceOperator(kind) {
107
+ return (kind === SyntaxKind.AmpersandAmpersandToken ||
108
+ kind === SyntaxKind.BarBarToken ||
109
+ kind === SyntaxKind.QuestionQuestionToken);
110
+ }
111
+ /**
112
+ * Flattens a logical operator sequence (FR-008, research R7): collects
113
+ * the chain's operators and operand leaves in source order, descending
114
+ * through nested sequence-operator binaries and unwrapping parenthesized
115
+ * subexpressions — parens are transparent to the flattening, never scored
116
+ * as leaves. A child that unwraps to anything other than a
117
+ * sequence-operator binary is an operand leaf.
118
+ *
119
+ * A pure recursive projection over the compiler's AST; its depth is
120
+ * bounded by the subtree the walk already entered — extraction discarded
121
+ * any out-of-budget file before a record existed (the research R12
122
+ * argument `complexity.ts` records for its own walk).
123
+ *
124
+ * @param node The chain's root node (a sequence-operator binary, per the
125
+ * visit dispatch that calls this).
126
+ * @returns The flattened operator sequence and operand leaves, in source
127
+ * order — `operators.length === operands.length - 1` for the chain.
128
+ */
129
+ function flattenLogicalSequence(node) {
130
+ const operators = [];
131
+ const operands = [];
132
+ const descend = (current) => {
133
+ let unwrapped = current;
134
+ while (isParenthesizedExpression(unwrapped)) {
135
+ unwrapped = unwrapped.expression;
136
+ }
137
+ if (isBinaryExpression(unwrapped) &&
138
+ isLogicalSequenceOperator(unwrapped.operatorToken.kind)) {
139
+ descend(unwrapped.left);
140
+ operators.push(unwrapped.operatorToken.kind);
141
+ descend(unwrapped.right);
142
+ return;
143
+ }
144
+ operands.push(unwrapped);
145
+ };
146
+ descend(node);
147
+ return { operators, operands };
148
+ }
149
+ /**
150
+ * Counts the maximal same-operator runs in a flattened operator sequence
151
+ * (FR-008): a single operator is a run of one, and each operator change
152
+ * starts a new run — `a && b` is 1, `a && b || c` is 2, and
153
+ * `a && b || c && d` is 3.
154
+ *
155
+ * @param operators The flattened operator sequence, in source order.
156
+ * @returns The run count (0 for an empty sequence).
157
+ */
158
+ function countOperatorRuns(operators) {
159
+ let runs = 0;
160
+ let previous;
161
+ for (const operator of operators) {
162
+ if (operator !== previous) {
163
+ runs += 1;
164
+ previous = operator;
165
+ }
166
+ }
167
+ return runs;
168
+ }
169
+ /**
170
+ * Scores one extraction record's body with the cognitive complexity
171
+ * rules (FR-006 structural, flow-break, and recursion clauses; FR-007;
172
+ * FR-008; FR-009; research R7-R10).
173
+ *
174
+ * The walk starts at the record's body node — a block body's statements, an
175
+ * expression-bodied arrow's expression — the countDecisionPoints
176
+ * start-at-body discipline: the record's own node is never treated as a
177
+ * boundary, so its decorators and parameter lists are structurally outside
178
+ * the walk (decorator transparency for the record's own spelling). It stops
179
+ * at nested extracted function-likes (each owns its own record, so its
180
+ * constructs belong to its own row — the `isExtractedFunctionLike`
181
+ * boundary, never a re-derivation) and continues through anonymous
182
+ * function-likes with the nesting level reset to 0 at the boundary, whose
183
+ * constructs attribute to this record per FR-009. Conditions and clause
184
+ * labels are walked at their construct's own nesting level — only the
185
+ * FR-007 region interiors deepen — and decorators are transparent wherever
186
+ * they appear (class, member, and parameter positions alike).
187
+ *
188
+ * @param record The extraction record whose body is scored.
189
+ * @returns The SonarSource cognitive complexity score (an integer ≥ 0).
190
+ */
191
+ function cognitiveScoreOf(record) {
192
+ if (!isExtractedFunctionLike(record.node)) {
193
+ throw new Error("extraction record node is not an extracted function-like: " +
194
+ `${record.node.constructor.name}`);
195
+ }
196
+ let score = 0;
197
+ // One node, one dispatch: each structural construct takes its FR-006
198
+ // increment and walks its FR-007 region interiors one level deeper; the
199
+ // flat rules (FR-006 flow-break and recursion clauses, FR-008
200
+ // sequences) add theirs with no nesting term; everything else
201
+ // descends unchanged.
202
+ const visit = (node, nesting) => {
203
+ // FR-009: a nested extracted function-like stops the walk — its own
204
+ // record owns its constructs.
205
+ if (isExtractedFunctionLike(node)) {
206
+ return;
207
+ }
208
+ // FR-009: an anonymous function-like owns no record; the walk continues
209
+ // through it with the nesting level reset to 0 at the boundary.
210
+ if (isArrowFunction(node) || isFunctionExpression(node)) {
211
+ visitChildren(node, 0);
212
+ return;
213
+ }
214
+ if (isIfStatement(node)) {
215
+ score += 1 + nesting;
216
+ visit(node.expression, nesting);
217
+ visit(node.thenStatement, nesting + 1);
218
+ visitElseChain(node.elseStatement, nesting);
219
+ return;
220
+ }
221
+ if (isForStatement(node)) {
222
+ score += 1 + nesting;
223
+ if (node.initializer !== undefined) {
224
+ visit(node.initializer, nesting);
225
+ }
226
+ if (node.condition !== undefined) {
227
+ visit(node.condition, nesting);
228
+ }
229
+ if (node.incrementor !== undefined) {
230
+ visit(node.incrementor, nesting);
231
+ }
232
+ visit(node.statement, nesting + 1);
233
+ return;
234
+ }
235
+ if (isForOfStatement(node) || isForInStatement(node)) {
236
+ score += 1 + nesting;
237
+ visit(node.initializer, nesting);
238
+ visit(node.expression, nesting);
239
+ visit(node.statement, nesting + 1);
240
+ return;
241
+ }
242
+ if (isWhileStatement(node)) {
243
+ score += 1 + nesting;
244
+ visit(node.expression, nesting);
245
+ visit(node.statement, nesting + 1);
246
+ return;
247
+ }
248
+ if (isDoStatement(node)) {
249
+ score += 1 + nesting;
250
+ visit(node.statement, nesting + 1);
251
+ visit(node.expression, nesting);
252
+ return;
253
+ }
254
+ if (isSwitchStatement(node)) {
255
+ score += 1 + nesting;
256
+ visit(node.expression, nesting);
257
+ // Case clauses never increment (the switch above took the single
258
+ // increment) and each clause's statement list is a region one level
259
+ // deeper; the clause's own label expression is walked at the
260
+ // switch's level — the region's own spelling, the same flat
261
+ // treatment an `else` gets inside the `if`'s region.
262
+ for (const clause of node.caseBlock.clauses) {
263
+ if (isCaseClause(clause)) {
264
+ visit(clause.expression, nesting);
265
+ }
266
+ for (const statement of clause.statements) {
267
+ visit(statement, nesting + 1);
268
+ }
269
+ }
270
+ return;
271
+ }
272
+ if (isTryStatement(node)) {
273
+ // `try` and `finally` add nothing and are not nesting regions
274
+ // (FR-006/FR-007); only `catch` increments, and its block is a
275
+ // region one level deeper.
276
+ visit(node.tryBlock, nesting);
277
+ if (node.catchClause !== undefined) {
278
+ score += 1 + nesting;
279
+ visit(node.catchClause.block, nesting + 1);
280
+ }
281
+ if (node.finallyBlock !== undefined) {
282
+ visit(node.finallyBlock, nesting);
283
+ }
284
+ return;
285
+ }
286
+ if (isConditionalExpression(node)) {
287
+ score += 1 + nesting;
288
+ visit(node.condition, nesting);
289
+ visit(node.whenTrue, nesting + 1);
290
+ visit(node.whenFalse, nesting + 1);
291
+ return;
292
+ }
293
+ // FR-008 (research R7): a logical operator sequence — `&&`, `||`,
294
+ // `??` — adds 1 per maximal run of the same operator in the
295
+ // flattened chain: a single operator is a run of one, and each
296
+ // operator change starts a new run. The increment is FLAT — no
297
+ // nesting term, unlike the structural constructs above — and a
298
+ // sequence counts anywhere the walk reaches it,
299
+ // control-structure conditions included (they are walked at their
300
+ // construct's own level, so nothing extra is wired here). Each
301
+ // operand leaf is re-visited below so nested ternaries, calls, and
302
+ // separate chains inside operands still score; a sequence nested
303
+ // inside a non-logical binary (e.g. `a + (b && c)`) reaches this
304
+ // case by the default descent and scores as its own chain.
305
+ if (isBinaryExpression(node) &&
306
+ isLogicalSequenceOperator(node.operatorToken.kind)) {
307
+ const { operators, operands } = flattenLogicalSequence(node);
308
+ score += countOperatorRuns(operators);
309
+ for (const operand of operands) {
310
+ visit(operand, nesting);
311
+ }
312
+ return;
313
+ }
314
+ // FR-006 flow-break clause (research R8): only a `break` or
315
+ // `continue` that REFERENCES A LABEL increments — flat, +1, no
316
+ // nesting term — while the plain forms add nothing. The increment
317
+ // falls through to the default descent below, which walks the
318
+ // statement's children: the label identifier itself scores nothing.
319
+ // A labeled statement's own label needs no case here — the default
320
+ // descent enters its statement unchanged.
321
+ if (isBreakOrContinueStatement(node) && node.label !== undefined) {
322
+ score += 1;
323
+ }
324
+ // FR-006 recursion clause (research R10): direct recursion — a call
325
+ // to the enclosing record's own name — adds 1 per call site, flat,
326
+ // bare (`f(...)`) or via `this` (`this.m(...)` inside method `m`).
327
+ // The match is binding-blind text comparison against the record's
328
+ // declared name: no type-checker dependency, so program and
329
+ // parse-only modes score identically (mode parity). Mutual
330
+ // recursion — calls to any other name — adds nothing. The fall
331
+ // through to the default descent below still walks the call's
332
+ // arguments, where nested constructs and further calls score.
333
+ if (isCallExpression(node)) {
334
+ const callee = node.expression;
335
+ if ((isIdentifier(callee) && callee.text === record.name) ||
336
+ (isPropertyAccessExpression(callee) &&
337
+ callee.name.text === record.name &&
338
+ isThisExpression(callee.expression))) {
339
+ score += 1;
340
+ }
341
+ }
342
+ visitChildren(node, nesting);
343
+ };
344
+ // The flat else family (FR-006): an `else` and each `else if` add 1 with
345
+ // no nesting penalty, while their interiors are regions one level deeper
346
+ // than the chain's `if` (FR-007) — the else-if consequent and the else
347
+ // body both deepen relative to the original if's level, never
348
+ // cumulatively down the chain.
349
+ const visitElseChain = (elseBranch, chainNesting) => {
350
+ let current = elseBranch;
351
+ while (current !== undefined) {
352
+ if (!isIfStatement(current)) {
353
+ score += 1;
354
+ visit(current, chainNesting + 1);
355
+ return;
356
+ }
357
+ score += 1;
358
+ visit(current.expression, chainNesting);
359
+ visit(current.thenStatement, chainNesting + 1);
360
+ current = current.elseStatement;
361
+ }
362
+ };
363
+ // The default descent: every child in source order at the same nesting,
364
+ // with decorators skipped wherever they appear — a decorator's argument
365
+ // subtree is never entered, so decorator transparency holds for nested
366
+ // classes, members, and parameters alike, not just the record's own
367
+ // spelling.
368
+ const visitChildren = (node, nesting) => {
369
+ node.forEachChild((child) => {
370
+ if (isDecorator(child)) {
371
+ return undefined;
372
+ }
373
+ visit(child, nesting);
374
+ return undefined;
375
+ });
376
+ };
377
+ visit(record.node.body, 0);
378
+ return score;
379
+ }
380
+ //# sourceMappingURL=cognitive.js.map
@@ -0,0 +1,102 @@
1
+ import type { Writable } from "node:stream";
2
+ /**
3
+ * The cyclomatic complexity engine (FR-021, FR-022; research R9;
4
+ * data-model.md's ComplexityEntry/ComplexityResult; Constitution
5
+ * Principles I and IV). `computeComplexity` (T023) closes the shared
6
+ * `prepareAnalysis` pipeline (T014) over the decision-point count — the
7
+ * SAME extraction set, scope, and ordering `analyze` reports, so FR-022's
8
+ * parity guarantee is structural (no second extraction path to drift) —
9
+ * with the program-mode context's lifetime owned by this handler and
10
+ * closed in a `finally` exactly as `analyze` closes its own.
11
+ *
12
+ * The counting rule (FR-021 / contracts/complexity.md / research R9):
13
+ * complexity = 1 + the count of `if` (each `else if` is a nested `if` and
14
+ * counts naturally), `for`, `for-of`, `for-in`, `while`, `do`, each
15
+ * `case` clause (`default` excluded), `catch`, conditional (ternary)
16
+ * expressions, and the binary logical operators `&&`, `||`, `??` — in the
17
+ * function's OWN body, so the per-record walk starts at the body node (an
18
+ * expression-bodied arrow's expression included). The list is closed:
19
+ * logical-assignment operators (`&&=`, `||=`, `??=`) are never counted
20
+ * (Assumption 10). An empty body scores exactly 1.
21
+ *
22
+ * Attribution (FR-009, the same boundary the detector walks): the
23
+ * per-record walk stops at nested extracted function-likes — the R4 form
24
+ * conditions `extract.ts` exports as `isExtractedFunctionLike`, so the
25
+ * boundary is the extractor's own, never a re-derivation — because each
26
+ * nested form's record owns its body; anonymous (unassigned) function
27
+ * expressions are not in the record set, so the walk continues through
28
+ * them and their constructs count toward the innermost enclosing record.
29
+ *
30
+ * No second AST depth budget: extraction already discarded any file whose
31
+ * AST could exceed its budget (a record exists only for an in-budget
32
+ * file), and this walk revisits exactly those materialized subtrees —
33
+ * the argument `detector.ts` records for its own walk.
34
+ */
35
+ /**
36
+ * One complexity entry (data-model.md's ComplexityEntry; FR-022): the
37
+ * extraction identity plus the computed score. Field names mirror the
38
+ * wire payload exactly — no snake_case exception applies to this record —
39
+ * and the entity is an immutable value record (convention pack AP-004).
40
+ */
41
+ export interface ComplexityEntry {
42
+ /** The function's declared name (extraction identity, FR-008). */
43
+ readonly name: string;
44
+ /** Dotted module path derived by `derivePackage` from `file`. */
45
+ readonly package: string;
46
+ /** Root-relative POSIX path of the declaring file. */
47
+ readonly file: string;
48
+ /** 1-based line of the function declaration. */
49
+ readonly line: number;
50
+ /** 1 + the counted decision points (an integer ≥ 1). */
51
+ readonly complexity: number;
52
+ }
53
+ /**
54
+ * The `complexity` method's entry (FR-021, FR-022; the analyze-shaped
55
+ * surface T018 established): the serialized `ComplexityEntry[]` payload —
56
+ * one entry per extraction record, assembled in the `(file, line, name)`
57
+ * total order, and mapped through `serializeComplexityEntry` so every
58
+ * entry on the returned array is already wire-shaped.
59
+ *
60
+ * The returned array — not a `{functions: [...]}` wrapper — is the
61
+ * documented result shape the server wraps into its JSON-RPC success
62
+ * response (T024); both this entry and the payload are deterministic
63
+ * pure functions of the analyzed tree (Constitution Principle I:
64
+ * byte-identical repeat responses).
65
+ *
66
+ * The program-mode context's lifetime is this handler's: the native
67
+ * compiler server behind it is closed in the `finally` whatever the
68
+ * counting outcome, so no subprocess outlives one analysis. A parse-only
69
+ * context owns nothing to dispose.
70
+ *
71
+ * @param rootPath Absolute or relative project root; validated and
72
+ * realpath-resolved by `prepareAnalysis` (an invalid root throws
73
+ * `InvalidRootPathError`, the server maps to `-32602`).
74
+ * @param patterns The raw `patterns` parameter value; shape-validated by
75
+ * the server (`-32602`, T019) before analysis runs, normalized here.
76
+ * @param stderr Injected diagnostic sink (Testability principle); defaults
77
+ * to `process.stderr`. Stdout is never touched.
78
+ * @returns The serialized complexity entries, `(file, line, name)`-sorted.
79
+ */
80
+ export declare function computeComplexity(rootPath: string, patterns: unknown, stderr?: Writable): Promise<readonly Record<string, unknown>[]>;
81
+ /**
82
+ * Serializes a `ComplexityEntry` to its wire shape (FR-022): exactly the
83
+ * five fields, emitted in the canonical sorted-key order the protocol
84
+ * layer's sorted-key serializer produces — so the server's `serialize`
85
+ * pass re-orders these keys as a structural no-op and each entry is
86
+ * wire-final in the form that serializer defines.
87
+ *
88
+ * A pure projection, deliberately without the fail-loud field validation
89
+ * `models.ts`'s record serializers apply: those guard records assembled
90
+ * from many detector construction sites (and `tests/models.test.ts`
91
+ * covers the guards), while every `ComplexityEntry` is constructed at
92
+ * this module's single site from fields whose validity is structural —
93
+ * `ExtractionRecord`'s string `name`/`relPath`, a 1-based `line`, and
94
+ * `complexity` as `1 + countDecisionPoints` (≥ 1 by construction). The
95
+ * wire shape itself — exactly these five keys, integer `complexity` ≥ 1 —
96
+ * is pinned by `tests/complexity.test.ts`'s wire-invariant assertions.
97
+ *
98
+ * @param entry The complexity entry to serialize.
99
+ * @returns A JSON-ready object with `complexity`, `file`, `line`, `name`,
100
+ * and `package`.
101
+ */
102
+ export declare function serializeComplexityEntry(entry: ComplexityEntry): Record<string, unknown>;
@@ -0,0 +1,163 @@
1
+ import { isBinaryExpression, SyntaxKind } from "typescript/unstable/ast";
2
+ import { prepareAnalysis } from "./analysis.js";
3
+ import { isExtractedFunctionLike } from "./extract.js";
4
+ import { compareFileLineName } from "./internal.js";
5
+ import { derivePackage } from "./models.js";
6
+ /**
7
+ * The `complexity` method's entry (FR-021, FR-022; the analyze-shaped
8
+ * surface T018 established): the serialized `ComplexityEntry[]` payload —
9
+ * one entry per extraction record, assembled in the `(file, line, name)`
10
+ * total order, and mapped through `serializeComplexityEntry` so every
11
+ * entry on the returned array is already wire-shaped.
12
+ *
13
+ * The returned array — not a `{functions: [...]}` wrapper — is the
14
+ * documented result shape the server wraps into its JSON-RPC success
15
+ * response (T024); both this entry and the payload are deterministic
16
+ * pure functions of the analyzed tree (Constitution Principle I:
17
+ * byte-identical repeat responses).
18
+ *
19
+ * The program-mode context's lifetime is this handler's: the native
20
+ * compiler server behind it is closed in the `finally` whatever the
21
+ * counting outcome, so no subprocess outlives one analysis. A parse-only
22
+ * context owns nothing to dispose.
23
+ *
24
+ * @param rootPath Absolute or relative project root; validated and
25
+ * realpath-resolved by `prepareAnalysis` (an invalid root throws
26
+ * `InvalidRootPathError`, the server maps to `-32602`).
27
+ * @param patterns The raw `patterns` parameter value; shape-validated by
28
+ * the server (`-32602`, T019) before analysis runs, normalized here.
29
+ * @param stderr Injected diagnostic sink (Testability principle); defaults
30
+ * to `process.stderr`. Stdout is never touched.
31
+ * @returns The serialized complexity entries, `(file, line, name)`-sorted.
32
+ */
33
+ export async function computeComplexity(rootPath, patterns, stderr = process.stderr) {
34
+ const prepared = await prepareAnalysis(rootPath, patterns, stderr);
35
+ try {
36
+ const entries = prepared.records.map((record) => ({
37
+ name: record.name,
38
+ package: derivePackage(record.relPath),
39
+ file: record.relPath,
40
+ line: record.line,
41
+ complexity: 1 + countDecisionPoints(record),
42
+ }));
43
+ entries.sort(compareFileLineName);
44
+ return entries.map(serializeComplexityEntry);
45
+ }
46
+ finally {
47
+ if (prepared.context.mode === "program") {
48
+ prepared.context.dispose();
49
+ }
50
+ }
51
+ }
52
+ /**
53
+ * Serializes a `ComplexityEntry` to its wire shape (FR-022): exactly the
54
+ * five fields, emitted in the canonical sorted-key order the protocol
55
+ * layer's sorted-key serializer produces — so the server's `serialize`
56
+ * pass re-orders these keys as a structural no-op and each entry is
57
+ * wire-final in the form that serializer defines.
58
+ *
59
+ * A pure projection, deliberately without the fail-loud field validation
60
+ * `models.ts`'s record serializers apply: those guard records assembled
61
+ * from many detector construction sites (and `tests/models.test.ts`
62
+ * covers the guards), while every `ComplexityEntry` is constructed at
63
+ * this module's single site from fields whose validity is structural —
64
+ * `ExtractionRecord`'s string `name`/`relPath`, a 1-based `line`, and
65
+ * `complexity` as `1 + countDecisionPoints` (≥ 1 by construction). The
66
+ * wire shape itself — exactly these five keys, integer `complexity` ≥ 1 —
67
+ * is pinned by `tests/complexity.test.ts`'s wire-invariant assertions.
68
+ *
69
+ * @param entry The complexity entry to serialize.
70
+ * @returns A JSON-ready object with `complexity`, `file`, `line`, `name`,
71
+ * and `package`.
72
+ */
73
+ export function serializeComplexityEntry(entry) {
74
+ return {
75
+ complexity: entry.complexity,
76
+ file: entry.file,
77
+ line: entry.line,
78
+ name: entry.name,
79
+ package: entry.package,
80
+ };
81
+ }
82
+ /**
83
+ * Counts the closed decision-point list (FR-021; research R9) inside one
84
+ * record's own body.
85
+ *
86
+ * The walk starts at the record's body node — a block body's statements,
87
+ * an expression-bodied arrow's expression — because FR-021 counts what is
88
+ * in the function's own body. It stops at nested extracted
89
+ * function-likes (each owns its own record, so its decision points belong
90
+ * to its own entry) and continues through anonymous function-likes, whose
91
+ * constructs attribute to this record per FR-009. Each occurrence counts
92
+ * exactly once: an `else if` is a nested `if` statement and counts
93
+ * naturally, and a `default` clause never matches the case-clause kind.
94
+ *
95
+ * @param record The extraction record whose body is counted.
96
+ * @returns The decision-point count (an integer ≥ 0).
97
+ */
98
+ function countDecisionPoints(record) {
99
+ if (!isExtractedFunctionLike(record.node)) {
100
+ throw new Error("extraction record node is not an extracted function-like: " +
101
+ `${record.node.constructor.name}`);
102
+ }
103
+ let count = 0;
104
+ const visit = (node) => {
105
+ if (isExtractedFunctionLike(node)) {
106
+ return;
107
+ }
108
+ if (isDecisionPoint(node)) {
109
+ count += 1;
110
+ }
111
+ node.forEachChild((child) => {
112
+ visit(child);
113
+ return undefined;
114
+ });
115
+ };
116
+ visit(record.node.body);
117
+ return count;
118
+ }
119
+ /**
120
+ * The closed decision-point kind set (FR-021; research R9): the statement,
121
+ * clause, and conditional-expression kinds that each count once.
122
+ * `DefaultClause` is a distinct kind and is deliberately absent — `default`
123
+ * never counts.
124
+ */
125
+ const DECISION_POINT_KINDS = new Set([
126
+ SyntaxKind.IfStatement,
127
+ SyntaxKind.ForStatement,
128
+ SyntaxKind.ForOfStatement,
129
+ SyntaxKind.ForInStatement,
130
+ SyntaxKind.WhileStatement,
131
+ SyntaxKind.DoStatement,
132
+ SyntaxKind.CaseClause,
133
+ SyntaxKind.CatchClause,
134
+ SyntaxKind.ConditionalExpression,
135
+ ]);
136
+ /**
137
+ * The counted binary logical operator tokens (FR-021; research R9): `&&`,
138
+ * `||`, and `??` only. The logical-assignment operators (`&&=`, `||=`,
139
+ * `??=`) are distinct token kinds and are deliberately absent — the
140
+ * documented exclusion (Assumption 10).
141
+ */
142
+ const LOGICAL_OPERATOR_KINDS = new Set([
143
+ SyntaxKind.AmpersandAmpersandToken,
144
+ SyntaxKind.BarBarToken,
145
+ SyntaxKind.QuestionQuestionToken,
146
+ ]);
147
+ /**
148
+ * Whether a node is one counted decision point: a member of the closed
149
+ * kind set, or a binary expression whose operator token is one of the
150
+ * three counted logical operators. The operator is read from
151
+ * `operatorToken.kind` — the binary property; every other binary
152
+ * operator, comparison and assignment alike, counts nothing.
153
+ *
154
+ * @param node The node to test.
155
+ * @returns Whether the node counts one decision point.
156
+ */
157
+ function isDecisionPoint(node) {
158
+ if (DECISION_POINT_KINDS.has(node.kind)) {
159
+ return true;
160
+ }
161
+ return (isBinaryExpression(node) && LOGICAL_OPERATOR_KINDS.has(node.operatorToken.kind));
162
+ }
163
+ //# sourceMappingURL=complexity.js.map