@blundergoat/gruff-ts 0.3.2 → 0.5.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/CHANGELOG.md +54 -1
- package/README.md +16 -6
- package/SECURITY.md +2 -1
- package/docs/README.md +1 -4
- package/docs/agent-hook.md +15 -3
- package/docs/configuration.md +47 -1
- package/docs/dashboard.md +3 -3
- package/docs/reports-and-ci.md +36 -0
- package/docs/rules.md +52 -37
- package/package.json +1 -1
- package/src/analyser.ts +540 -154
- package/src/baseline-options.ts +90 -0
- package/src/baseline.ts +39 -3
- package/src/blocks.ts +116 -77
- package/src/changed-regions.ts +80 -11
- package/src/class-rules.ts +226 -76
- package/src/cli-program.ts +65 -15
- package/src/cli.ts +4 -2
- package/src/comment-rules.ts +58 -13
- package/src/comment-scanner.ts +27 -0
- package/src/complexity-metrics.ts +244 -0
- package/src/config.ts +56 -16
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +9 -10
- package/src/dead-code-rules.ts +10 -3
- package/src/discovery.ts +66 -22
- package/src/doc-rules.ts +22 -53
- package/src/findings-helpers.ts +127 -1
- package/src/findings.ts +4 -0
- package/src/fixture-purpose-rules.ts +39 -5
- package/src/github-actions-rules.ts +24 -1
- package/src/hook-contract.ts +120 -27
- package/src/init-config.ts +15 -5
- package/src/line-rules.ts +175 -19
- package/src/naming-pushers.ts +26 -5
- package/src/parsed-script.ts +652 -0
- package/src/process-exec-metadata.ts +163 -0
- package/src/profiles.ts +14 -0
- package/src/project-config-rules.ts +36 -18
- package/src/project-rules.ts +159 -42
- package/src/public-exports.ts +220 -0
- package/src/report-renderers.ts +58 -4
- package/src/rules.ts +15 -15
- package/src/scoring.ts +13 -4
- package/src/security-flow-rules.ts +169 -24
- package/src/sensitive-data-rules.ts +256 -80
- package/src/source-text.ts +9 -26
- package/src/static-analysis-redundant-rules.ts +46 -2
- package/src/test-block-rules.ts +118 -14
- package/src/test-fixtures.ts +4 -1
- package/src/text-scans.ts +8 -1
- package/src/types.ts +17 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Baseline option handling for `analyse`: chooses explicit/default baselines, applies
|
|
2
|
+
// suppression, and writes generated baselines while preserving the report metadata shape.
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { applyBaseline, DEFAULT_BASELINE, writeBaseline } from "./baseline.ts";
|
|
6
|
+
import { absolutize, displayPath } from "./discovery.ts";
|
|
7
|
+
import type { AnalysisOptions, AnalysisReport, Finding } from "./types.ts";
|
|
8
|
+
|
|
9
|
+
/*
|
|
10
|
+
* Result of applying a baseline (suppression) or generating a new one. The optional `baseline`
|
|
11
|
+
* matches the `gruff.analysis.v2` schema's baseline metadata - present only when a baseline file
|
|
12
|
+
* was actually used or generated, so the report stays stable across baseline-disabled runs.
|
|
13
|
+
*/
|
|
14
|
+
export interface BaselineApplication {
|
|
15
|
+
findings: Finding[];
|
|
16
|
+
baseline?: NonNullable<AnalysisReport["baseline"]>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Resolved baseline path plus the provenance string emitted in the report. `source` distinguishes
|
|
20
|
+
// "explicit" (--baseline flag) from "default" (auto-discovered gruff-baseline.json).
|
|
21
|
+
interface BaselineSelection {
|
|
22
|
+
path: string;
|
|
23
|
+
source: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/*
|
|
27
|
+
* Three-way baseline dispatcher. `--generate-baseline` wins (writes a new file, returns findings
|
|
28
|
+
* unchanged); `--no-baseline` skips entirely; otherwise look for an explicit or default baseline.
|
|
29
|
+
* The stable identity tuple (fingerprint, ruleId, filePath) drives suppression matching.
|
|
30
|
+
*/
|
|
31
|
+
export function applyBaselineOptions(projectRoot: string, options: AnalysisOptions, findings: Finding[]): BaselineApplication {
|
|
32
|
+
if (options.generateBaseline) {
|
|
33
|
+
return generateBaselineResult(projectRoot, options.generateBaseline, findings);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (options.shouldSkipBaseline) {
|
|
37
|
+
return { findings };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const selected = selectedBaseline(projectRoot, options);
|
|
41
|
+
if (!selected) {
|
|
42
|
+
return { findings };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return applySelectedBaseline(projectRoot, selected, findings);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/*
|
|
49
|
+
* Writes the baseline file via writeBaseline and returns the report-shaped metadata. `suppressed: 0`
|
|
50
|
+
* because generation does not filter findings - every current finding is captured in the stable baseline.
|
|
51
|
+
*/
|
|
52
|
+
function generateBaselineResult(projectRoot: string, baselineFile: string, findings: Finding[]): BaselineApplication {
|
|
53
|
+
const baselinePath = absolutize(projectRoot, baselineFile);
|
|
54
|
+
writeBaseline(baselinePath, findings);
|
|
55
|
+
return {
|
|
56
|
+
findings,
|
|
57
|
+
baseline: {
|
|
58
|
+
path: displayPath(projectRoot, baselinePath),
|
|
59
|
+
source: "generated",
|
|
60
|
+
suppressed: 0,
|
|
61
|
+
generated: true,
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Loads the baseline file and filters findings whose identity tuple matches. `suppressed` is
|
|
67
|
+
// computed from the size delta so the stable baseline report metadata stays accurate.
|
|
68
|
+
function applySelectedBaseline(projectRoot: string, selected: BaselineSelection, findings: Finding[]): BaselineApplication {
|
|
69
|
+
const before = findings.length;
|
|
70
|
+
const filteredFindings = applyBaseline(selected.path, findings);
|
|
71
|
+
return {
|
|
72
|
+
findings: filteredFindings,
|
|
73
|
+
baseline: {
|
|
74
|
+
path: displayPath(projectRoot, selected.path),
|
|
75
|
+
source: selected.source,
|
|
76
|
+
suppressed: before - filteredFindings.length,
|
|
77
|
+
generated: false,
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Picks an explicit `--baseline` path first, then the conventional `gruff-baseline.json` at the
|
|
83
|
+
// project root. Returning undefined means "no baseline" - the stable contract preserves report shape.
|
|
84
|
+
function selectedBaseline(projectRoot: string, options: AnalysisOptions): BaselineSelection | undefined {
|
|
85
|
+
if (options.baseline) {
|
|
86
|
+
return { path: absolutize(projectRoot, options.baseline), source: "explicit" };
|
|
87
|
+
}
|
|
88
|
+
const defaultBaseline = join(projectRoot, DEFAULT_BASELINE);
|
|
89
|
+
return existsSync(defaultBaseline) ? { path: defaultBaseline, source: "default" } : undefined;
|
|
90
|
+
}
|
package/src/baseline.ts
CHANGED
|
@@ -74,11 +74,14 @@ function recordHistory(projectRoot: string, historyFile: string, findings: Findi
|
|
|
74
74
|
|
|
75
75
|
// `docs.missing-public-doc` is keyed by (ruleId, filePath, symbol) instead of fingerprint because one
|
|
76
76
|
// file can legitimately surface multiple undocumented public symbols and they must each survive dedupe.
|
|
77
|
-
// All other rules collapse on their fingerprint,
|
|
77
|
+
// All other rules collapse on their fingerprint, extended by the match column when one is present
|
|
78
|
+
// (ADR-017): two distinct secrets on one line share a line-keyed fingerprint, and without the column
|
|
79
|
+
// discriminator the second occurrence would be silently dropped from every report and the hook.
|
|
80
|
+
// The extended key is in-memory only - fingerprint values and `gruff.baseline.v1` matching are unchanged.
|
|
78
81
|
function dedupeFindings(findings: Finding[]): Finding[] {
|
|
79
82
|
const seen = new Set<string>();
|
|
80
83
|
return findings.filter((finding) => {
|
|
81
|
-
const key = finding
|
|
84
|
+
const key = dedupeKey(finding);
|
|
82
85
|
if (seen.has(key)) {
|
|
83
86
|
return false;
|
|
84
87
|
}
|
|
@@ -87,4 +90,37 @@ function dedupeFindings(findings: Finding[]): Finding[] {
|
|
|
87
90
|
});
|
|
88
91
|
}
|
|
89
92
|
|
|
90
|
-
|
|
93
|
+
// Derives the in-memory dedupe key for one finding, so same-line occurrences with distinct
|
|
94
|
+
// columns survive dedupe as separate findings (ADR-017). Invariant: the key is never serialized
|
|
95
|
+
// and never feeds `applyBaseline` - fingerprint values and baseline matching stay byte-identical.
|
|
96
|
+
function dedupeKey(finding: Finding): string {
|
|
97
|
+
// One file legitimately surfaces many undocumented public symbols; keep each per-symbol entry.
|
|
98
|
+
if (finding.ruleId === "docs.missing-public-doc" && finding.symbol) {
|
|
99
|
+
return [finding.ruleId, finding.filePath, finding.symbol].join("\0");
|
|
100
|
+
}
|
|
101
|
+
// Casing drift is scoped to a lexical owner. Preserve owner-distinct diagnostics in memory
|
|
102
|
+
// without changing their public line-keyed fingerprints or baseline matching contract.
|
|
103
|
+
if (finding.ruleId === "naming.inconsistent-casing" && typeof finding.metadata.ownerId === "string") {
|
|
104
|
+
return [finding.fingerprint, finding.metadata.ownerId].join("\0");
|
|
105
|
+
}
|
|
106
|
+
// A column means the scanner pinpointed the occurrence; same-line occurrences stay distinct.
|
|
107
|
+
if (finding.column !== undefined) {
|
|
108
|
+
return [finding.fingerprint, String(finding.column)].join("\0");
|
|
109
|
+
}
|
|
110
|
+
return finding.fingerprint;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Canonical finding ordering: (filePath, line, ruleId, message). The same tuple is part of the
|
|
114
|
+
// stable baseline matching contract, so changing the comparator would churn every existing baseline.
|
|
115
|
+
function sortedUniqueFindings(findings: Finding[]): Finding[] {
|
|
116
|
+
findings.sort(
|
|
117
|
+
(left, right) =>
|
|
118
|
+
left.filePath.localeCompare(right.filePath) ||
|
|
119
|
+
(left.line ?? 0) - (right.line ?? 0) ||
|
|
120
|
+
left.ruleId.localeCompare(right.ruleId) ||
|
|
121
|
+
left.message.localeCompare(right.message),
|
|
122
|
+
);
|
|
123
|
+
return dedupeFindings(findings);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export { DEFAULT_BASELINE, writeBaseline, applyBaseline, recordHistory, dedupeFindings, sortedUniqueFindings };
|
package/src/blocks.ts
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
// finding factories. Pulls the parser and the rules that operate on parsed blocks out of cli.ts.
|
|
4
4
|
import { ruleSeverity, threshold } from "./config.ts";
|
|
5
5
|
import { hasLeadingCommentBeforeLines } from "./comment-scanner.ts";
|
|
6
|
+
import { baseComplexityMetrics, complexityMetrics as measureComplexity, type ComplexityMetrics } from "./complexity-metrics.ts";
|
|
6
7
|
import { type SourceFile } from "./discovery.ts";
|
|
7
8
|
import { makeFinding } from "./findings.ts";
|
|
8
|
-
import { escapeRegex, isGenericName, lineOffset } from "./findings-helpers.ts";
|
|
9
|
-
import {
|
|
9
|
+
import { escapeRegex, isGenericName, lineOffset, parameterNames } from "./findings-helpers.ts";
|
|
10
|
+
import { callableMatchPoints, type ParsedScript } from "./parsed-script.ts";
|
|
10
11
|
import type { Config, Finding, Pillar, Severity } from "./types.ts";
|
|
11
12
|
|
|
12
13
|
// Parsed callable body shared by every block-level rule (size, complexity, naming, docs). The
|
|
@@ -15,27 +16,28 @@ import type { Config, Finding, Pillar, Severity } from "./types.ts";
|
|
|
15
16
|
export interface FunctionBlock {
|
|
16
17
|
name: string;
|
|
17
18
|
params: string;
|
|
19
|
+
// AST parameter count; absent only for legacy regex-derived blocks.
|
|
20
|
+
parameterCount?: number;
|
|
21
|
+
// Shared syntax metric; absent only for legacy regex span probes.
|
|
22
|
+
complexityMetrics?: ComplexityMetrics;
|
|
23
|
+
// AST-known body presence; absent only for legacy regex-derived blocks.
|
|
24
|
+
hasBody?: boolean;
|
|
18
25
|
startLine: number;
|
|
19
26
|
lineCount: number;
|
|
20
27
|
body: string;
|
|
21
28
|
codeBody: string;
|
|
22
29
|
isPublic: boolean;
|
|
23
|
-
// True
|
|
24
|
-
//
|
|
25
|
-
// public class method is internal to an exported (or unexported) class. The doc rule splits
|
|
26
|
-
// severity on this distinction: exported functions warrant warning-tier doc requirements,
|
|
27
|
-
// internal helpers stay advisory.
|
|
30
|
+
// True for exported/re-exported module APIs; unlike `isPublic`, class modifiers do not qualify.
|
|
31
|
+
// This selects warning-tier API docs while internal helpers remain advisory.
|
|
28
32
|
isExported: boolean;
|
|
29
33
|
isTest: boolean;
|
|
30
34
|
hasLeadingComment: boolean;
|
|
31
35
|
declarationLine: number;
|
|
32
36
|
}
|
|
33
37
|
|
|
34
|
-
// Working state for
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
// `function foo() {}` later re-exported via `export { foo }` is still classified as exported
|
|
38
|
-
// (the line-local `^export` check alone would miss this common pattern).
|
|
38
|
+
// Working state for one file's block discovery. Patterns are precompiled once, while
|
|
39
|
+
// `reExportedNames` carries the file-level module API classification that a declaration-line
|
|
40
|
+
// check would miss. CLI users reach this state whenever script block rules run.
|
|
39
41
|
interface FunctionBlockScan {
|
|
40
42
|
lines: string[];
|
|
41
43
|
codeLines: string[];
|
|
@@ -59,6 +61,8 @@ export interface BlockRuleContext {
|
|
|
59
61
|
block: FunctionBlock;
|
|
60
62
|
config: Config;
|
|
61
63
|
findings: Finding[];
|
|
64
|
+
complexityMetrics: ComplexityMetrics;
|
|
65
|
+
// Retained alias used by the generic-parameter naming gate.
|
|
62
66
|
cyclomatic: number;
|
|
63
67
|
functionBody: string;
|
|
64
68
|
}
|
|
@@ -109,16 +113,18 @@ export function blockFindingWithMetadata(args: BlockFindingWithMetadataArgs): Fi
|
|
|
109
113
|
});
|
|
110
114
|
}
|
|
111
115
|
|
|
112
|
-
//
|
|
113
|
-
//
|
|
114
|
-
// resulting struct is part of the stable rule-context contract every per-block helper consumes.
|
|
116
|
+
// Threads one parsed complexity result and body through each block rule. Legacy span-only callers
|
|
117
|
+
// receive base complexity because no extra parse is allowed; this preserves the report invariant.
|
|
115
118
|
export function blockRuleContext(file: SourceFile, block: FunctionBlock, config: Config, findings: Finding[]): BlockRuleContext {
|
|
119
|
+
// A regex-only caller has no shared syntax node, so it receives the neutral base measurement.
|
|
120
|
+
const sharedComplexityMetrics = block.complexityMetrics ?? baseComplexityMetrics();
|
|
116
121
|
return {
|
|
117
122
|
file,
|
|
118
123
|
block,
|
|
119
124
|
config,
|
|
120
125
|
findings,
|
|
121
|
-
|
|
126
|
+
complexityMetrics: sharedComplexityMetrics,
|
|
127
|
+
cyclomatic: sharedComplexityMetrics.cyclomatic,
|
|
122
128
|
functionBody: functionBodyContent(block.codeBody),
|
|
123
129
|
};
|
|
124
130
|
}
|
|
@@ -158,10 +164,11 @@ function pushFunctionLengthFinding(context: BlockRuleContext): void {
|
|
|
158
164
|
}
|
|
159
165
|
}
|
|
160
166
|
|
|
161
|
-
// Default threshold 7.
|
|
162
|
-
//
|
|
167
|
+
// Default threshold 7. Uses the actual AST parameter count from the shared parse; the comma split
|
|
168
|
+
// only remains as the fallback for regex-discovered blocks in non-script text, where commas inside
|
|
169
|
+
// generics, tuples, or defaults cannot occur. Reports `size.parameter-count` when exceeded.
|
|
163
170
|
function pushParameterCountFinding(context: BlockRuleContext): void {
|
|
164
|
-
const params = context.block.params.split(",").map((value) => value.trim()).filter(Boolean).length;
|
|
171
|
+
const params = context.block.parameterCount ?? context.block.params.split(",").map((value) => value.trim()).filter(Boolean).length;
|
|
165
172
|
const parameterCountThreshold = threshold(context.config, "size.parameter-count", 7);
|
|
166
173
|
if (params > parameterCountThreshold) {
|
|
167
174
|
context.findings.push(blockFindingWithMetadata({
|
|
@@ -176,8 +183,7 @@ function pushParameterCountFinding(context: BlockRuleContext): void {
|
|
|
176
183
|
}
|
|
177
184
|
}
|
|
178
185
|
|
|
179
|
-
// Default threshold 15.
|
|
180
|
-
// `blockRuleContext` for the pre-computed value. Reports `complexity.cyclomatic` when exceeded.
|
|
186
|
+
// Default threshold 15. Reports the shared syntax-node decision count to CLI and JSON users.
|
|
181
187
|
function pushCyclomaticFinding(context: BlockRuleContext): void {
|
|
182
188
|
const cyclomaticThreshold = threshold(context.config, "complexity.cyclomatic", 15);
|
|
183
189
|
if (context.cyclomatic > cyclomaticThreshold) {
|
|
@@ -188,15 +194,14 @@ function pushCyclomaticFinding(context: BlockRuleContext): void {
|
|
|
188
194
|
block: context.block,
|
|
189
195
|
severity: ruleSeverity(context.config, "complexity.cyclomatic", "warning"),
|
|
190
196
|
pillar: "complexity",
|
|
191
|
-
metadata: { complexity: context.cyclomatic, threshold: cyclomaticThreshold },
|
|
197
|
+
metadata: { complexity: context.cyclomatic, threshold: cyclomaticThreshold, breakdown: context.complexityMetrics.breakdown },
|
|
192
198
|
}));
|
|
193
199
|
}
|
|
194
200
|
}
|
|
195
201
|
|
|
196
|
-
// Default threshold 15.
|
|
197
|
-
// "deeply nested" intuition pure cyclomatic misses. Reports `complexity.cognitive` when exceeded.
|
|
202
|
+
// Default threshold 15. Reports decisions plus shared control-flow nesting to CLI and JSON users.
|
|
198
203
|
function pushCognitiveFinding(context: BlockRuleContext): void {
|
|
199
|
-
const cognitive = context.
|
|
204
|
+
const cognitive = context.complexityMetrics.cognitive;
|
|
200
205
|
const cognitiveThreshold = threshold(context.config, "complexity.cognitive", 15);
|
|
201
206
|
if (cognitive > cognitiveThreshold) {
|
|
202
207
|
context.findings.push(blockFindingWithMetadata({
|
|
@@ -206,7 +211,7 @@ function pushCognitiveFinding(context: BlockRuleContext): void {
|
|
|
206
211
|
block: context.block,
|
|
207
212
|
severity: ruleSeverity(context.config, "complexity.cognitive", "warning"),
|
|
208
213
|
pillar: "complexity",
|
|
209
|
-
metadata: { complexity: cognitive, threshold: cognitiveThreshold },
|
|
214
|
+
metadata: { complexity: cognitive, threshold: cognitiveThreshold, breakdown: context.complexityMetrics.breakdown },
|
|
210
215
|
}));
|
|
211
216
|
}
|
|
212
217
|
}
|
|
@@ -282,6 +287,11 @@ function pushUnusedParameterFindings(context: BlockRuleContext): void {
|
|
|
282
287
|
// overload signatures - all of which look like a function declaration ending in `;` rather than `{`,
|
|
283
288
|
// and have no real body to check for emptiness or parameter usage.
|
|
284
289
|
function isBodyLessDeclaration(block: FunctionBlock): boolean {
|
|
290
|
+
// The shared parse already knows; the text walk below only covers legacy regex-derived blocks,
|
|
291
|
+
// and it misreads a multi-line signature whose first line stops at the open paren.
|
|
292
|
+
if (block.hasBody !== undefined) {
|
|
293
|
+
return !block.hasBody;
|
|
294
|
+
}
|
|
285
295
|
for (const rawLine of block.codeBody.split("\n")) {
|
|
286
296
|
const trimmed = rawLine.trim();
|
|
287
297
|
if (trimmed === "" || trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
|
|
@@ -413,21 +423,6 @@ function terminalBareReturnLines(source: string): number[] {
|
|
|
413
423
|
return [];
|
|
414
424
|
}
|
|
415
425
|
|
|
416
|
-
// Splits on `,` then strips visibility modifiers, `...rest`, default values, and type annotations
|
|
417
|
-
// in that order. Final filter rejects entries whose name isn't a plain identifier - destructured
|
|
418
|
-
// parameters land in that bucket and are intentionally invisible to per-parameter rules.
|
|
419
|
-
export function parameterNames(params: string): Array<{ name: string; raw: string }> {
|
|
420
|
-
return params
|
|
421
|
-
.split(",")
|
|
422
|
-
.map((parameter) => parameter.trim())
|
|
423
|
-
.filter(Boolean)
|
|
424
|
-
.map((raw) => {
|
|
425
|
-
const stripped = raw.replace(/^(?:public|private|protected|readonly)\s+/, "").replace(/^\.\.\./, "");
|
|
426
|
-
const name = stripped.split(/[?:=]/)[0]?.trim() ?? "";
|
|
427
|
-
return { name, raw: stripped };
|
|
428
|
-
})
|
|
429
|
-
.filter((parameter) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(parameter.name));
|
|
430
|
-
}
|
|
431
426
|
|
|
432
427
|
// Detects the `const x = expr; return x;` pattern. The regex backreference `\1` enforces that the
|
|
433
428
|
// returned identifier matches the declared one - used by `waste.redundant-variable` to surface
|
|
@@ -440,48 +435,83 @@ function redundantVariableReturns(source: string): Array<{ name: string; lineOff
|
|
|
440
435
|
return results.filter((result) => result.name !== "");
|
|
441
436
|
}
|
|
442
437
|
|
|
443
|
-
// Deepest `{` / `}` nesting reached across the body, minus one so the body's own outer braces
|
|
444
|
-
// don't count. The `Math.max(0, …)` clamp protects against unbalanced inputs - feeds the nesting
|
|
445
|
-
// component of `complexity.cognitive` and must stay deterministic across runs.
|
|
446
|
-
export function maxNestingDepth(source: string): number {
|
|
447
|
-
let depth = 0;
|
|
448
|
-
let maxDepth = 0;
|
|
449
|
-
for (const character of source) {
|
|
450
|
-
if (character === "{") {
|
|
451
|
-
depth += 1;
|
|
452
|
-
maxDepth = Math.max(maxDepth, depth);
|
|
453
|
-
} else if (character === "}") {
|
|
454
|
-
depth = Math.max(0, depth - 1);
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
return Math.max(0, maxDepth - 1);
|
|
458
|
-
}
|
|
459
|
-
|
|
460
438
|
// Matches `test("…", …)` and `it("…", …)` openers. Used both by the function-block parser to
|
|
461
439
|
// pick the right pattern and by setup detection to skip the test wrapper line itself.
|
|
462
440
|
function isTestInvocationLine(line: string): boolean {
|
|
463
441
|
return /^\s*(?:test|it)\s*\(/.test(line);
|
|
464
442
|
}
|
|
465
443
|
|
|
466
|
-
//
|
|
467
|
-
//
|
|
468
|
-
|
|
469
|
-
export function functionBlocks(source: string, codeSource = source): FunctionBlock[] {
|
|
444
|
+
// Builds report blocks from the shared syntax tree while preserving anchors and fingerprints.
|
|
445
|
+
// Span-only utilities without a parse retain the legacy regex walk.
|
|
446
|
+
export function functionBlocks(source: string, codeSource = source, parsed?: ParsedScript): FunctionBlock[] {
|
|
470
447
|
const scan: FunctionBlockScan = {
|
|
471
448
|
lines: source.split(/\r?\n/),
|
|
472
449
|
codeLines: codeSource.split(/\r?\n/),
|
|
473
450
|
patterns: FUNCTION_BLOCK_PATTERNS,
|
|
474
451
|
reExportedNames: collectReExportedNames(codeSource),
|
|
475
452
|
};
|
|
476
|
-
const
|
|
453
|
+
const matchPoints = matchPointsFor(scan, parsed);
|
|
454
|
+
const ownedCallableNodes = new Set<import("typescript").Node>();
|
|
455
|
+
// Every AST-backed block owns one callable body; regex-only span probes have no syntax node.
|
|
456
|
+
for (const point of matchPoints) {
|
|
457
|
+
// A missing node means a caller requested the legacy regex discovery path without reparsing.
|
|
458
|
+
if (point.callableNode) {
|
|
459
|
+
ownedCallableNodes.add(point.callableNode);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
// Each stable block receives one metric result based on the final one-block-per-line ownership set.
|
|
463
|
+
return matchPoints.map((point) => functionBlockFromPoint(scan, point, ownedCallableNodes));
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// One callable hit used to build the block that report rules inspect.
|
|
467
|
+
// Parsed hits carry their node and exact range; legacy span probes carry only text coordinates.
|
|
468
|
+
// Empty optional fields mean the caller deliberately supplied no shared parse.
|
|
469
|
+
interface BlockMatchPoint {
|
|
470
|
+
lineIndex: number;
|
|
471
|
+
// AST-known first line of the declaration; regex points leave it absent and keep the name line.
|
|
472
|
+
declarationLineIndex?: number;
|
|
473
|
+
// AST-known end line; regex points keep the legacy brace walk instead.
|
|
474
|
+
endLineIndex?: number;
|
|
475
|
+
name: string;
|
|
476
|
+
params: string;
|
|
477
|
+
parameterCount?: number;
|
|
478
|
+
// AST-known body presence; regex points leave it absent and fall back to the text heuristic.
|
|
479
|
+
hasBody?: boolean;
|
|
480
|
+
// AST-backed visibility; regex points leave these absent and retain the text fallback.
|
|
481
|
+
isDirectlyExported?: boolean;
|
|
482
|
+
isExplicitlyPublic?: boolean;
|
|
483
|
+
isModuleScoped?: boolean;
|
|
484
|
+
callableNode?: import("typescript").Node;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// Chooses the discovery mode: AST points from the shared parse, or the legacy regex line walk.
|
|
488
|
+
function matchPointsFor(scan: FunctionBlockScan, parsed: ParsedScript | undefined): BlockMatchPoint[] {
|
|
489
|
+
// A normal script scan already owns one ParsedScript and must reuse its callable points here.
|
|
490
|
+
if (parsed) {
|
|
491
|
+
return callableMatchPoints(parsed).map((point) => ({
|
|
492
|
+
lineIndex: point.lineIndex,
|
|
493
|
+
declarationLineIndex: point.declarationLineIndex,
|
|
494
|
+
endLineIndex: point.endLineIndex,
|
|
495
|
+
name: point.name,
|
|
496
|
+
params: point.params,
|
|
497
|
+
parameterCount: point.parameterCount,
|
|
498
|
+
hasBody: point.hasBody,
|
|
499
|
+
isDirectlyExported: point.isDirectlyExported,
|
|
500
|
+
isExplicitlyPublic: point.isExplicitlyPublic,
|
|
501
|
+
isModuleScoped: point.isModuleScoped,
|
|
502
|
+
callableNode: point.callableNode,
|
|
503
|
+
}));
|
|
504
|
+
}
|
|
505
|
+
const points: BlockMatchPoint[] = [];
|
|
506
|
+
// Span-only utilities still use the legacy masked-line inventory without triggering a parse.
|
|
477
507
|
scan.codeLines.forEach((line, index) => {
|
|
478
508
|
const match = functionBlockMatch(scan, line, index);
|
|
479
|
-
|
|
480
|
-
|
|
509
|
+
// Only lines that contain a supported callable shape become legacy block points.
|
|
510
|
+
if (match) {
|
|
511
|
+
points.push({ lineIndex: index, name: match[1] ?? "", params: match[2] ?? "" });
|
|
481
512
|
}
|
|
482
|
-
blocks.push(functionBlockFromMatch(scan, match, index));
|
|
483
513
|
});
|
|
484
|
-
return
|
|
514
|
+
return points;
|
|
485
515
|
}
|
|
486
516
|
|
|
487
517
|
/*
|
|
@@ -560,25 +590,34 @@ function functionPatternMatch(pattern: RegExp, patternIndex: number, line: strin
|
|
|
560
590
|
return match;
|
|
561
591
|
}
|
|
562
592
|
|
|
563
|
-
// Promotes a
|
|
564
|
-
//
|
|
565
|
-
|
|
566
|
-
|
|
593
|
+
// Promotes a discovery point into the shared block used by report rules and context documentation.
|
|
594
|
+
// Parsed points receive one syntax metric; legacy span-only points keep that field absent.
|
|
595
|
+
function functionBlockFromPoint(scan: FunctionBlockScan, point: BlockMatchPoint, ownedCallableNodes: ReadonlySet<import("typescript").Node>): FunctionBlock {
|
|
596
|
+
const index = point.lineIndex;
|
|
567
597
|
const start = functionStartIndex(scan.lines, index);
|
|
568
|
-
const end = functionEndIndex(scan, index);
|
|
598
|
+
const end = point.endLineIndex ?? functionEndIndex(scan, index);
|
|
569
599
|
const body = scan.lines.slice(start, end + 1).join("\n");
|
|
570
600
|
const codeBody = scan.codeLines.slice(start, end + 1).join("\n");
|
|
601
|
+
// A missing callable node identifies a legacy range probe, where base metrics are chosen later.
|
|
602
|
+
const sharedComplexityMetrics = point.callableNode ? measureComplexity(point.callableNode, ownedCallableNodes) : undefined;
|
|
603
|
+
// Parsed blocks expose metrics to both consumers; absent values stay omitted for exact optionals.
|
|
571
604
|
return {
|
|
572
|
-
name:
|
|
573
|
-
params:
|
|
605
|
+
name: point.name,
|
|
606
|
+
params: point.params,
|
|
607
|
+
...(point.parameterCount === undefined ? {} : { parameterCount: point.parameterCount }),
|
|
608
|
+
...(point.hasBody === undefined ? {} : { hasBody: point.hasBody }),
|
|
609
|
+
...(sharedComplexityMetrics === undefined ? {} : { complexityMetrics: sharedComplexityMetrics }),
|
|
574
610
|
startLine: start + 1,
|
|
575
611
|
lineCount: end - start + 1,
|
|
576
612
|
body,
|
|
577
613
|
codeBody,
|
|
578
|
-
isPublic: /\bexport\b|\bpublic\b/.test(scan.codeLines.slice(start, index + 1).join("\n")),
|
|
579
|
-
isExported: /^\s*export\b/.test(scan.codeLines[index] ?? "")
|
|
614
|
+
isPublic: point.isExplicitlyPublic ?? /\bexport\b|\bpublic\b/.test(scan.codeLines.slice(start, index + 1).join("\n")),
|
|
615
|
+
isExported: (point.isDirectlyExported ?? /^\s*export\b/.test(scan.codeLines[index] ?? ""))
|
|
616
|
+
|| point.isModuleScoped !== false && scan.reExportedNames.has(point.name),
|
|
580
617
|
isTest: isTestInvocationLine(scan.codeLines[index] ?? ""),
|
|
581
|
-
|
|
618
|
+
// Look upward from the declaration, not the name: a split-line `export async function` header
|
|
619
|
+
// would otherwise hide the declaration's own docblock behind its modifier line.
|
|
620
|
+
hasLeadingComment: hasLeadingCommentBeforeLines(scan.lines, (point.declarationLineIndex ?? index) + 1),
|
|
582
621
|
declarationLine: index + 1,
|
|
583
622
|
};
|
|
584
623
|
}
|