@blundergoat/gruff-ts 0.4.0 → 0.6.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 +123 -1
- package/CONTRIBUTING.md +32 -25
- package/README.md +55 -46
- package/SECURITY.md +18 -30
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -13
- package/docs/agent-hook.md +33 -24
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +173 -71
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -157
- package/docs/rules.md +140 -106
- package/package.json +10 -8
- package/src/analyser.ts +886 -282
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +85 -55
- package/src/blocks.ts +579 -364
- package/src/changed-regions.ts +414 -65
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +461 -302
- package/src/cli-program.ts +956 -166
- package/src/cli.ts +9 -2
- package/src/comment-rules.ts +277 -414
- package/src/comment-scanner.ts +363 -44
- package/src/complexity-metrics.ts +320 -0
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +778 -210
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +188 -61
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +521 -148
- package/src/doc-rules.ts +592 -147
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +240 -89
- package/src/findings.ts +48 -24
- package/src/fixture-purpose-rules.ts +226 -48
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +336 -106
- package/src/hook-contract.ts +708 -211
- package/src/init-config.ts +169 -114
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -419
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +33 -107
- package/src/parsed-script.ts +1206 -0
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +97 -71
- package/src/project-config-rules.ts +335 -146
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +284 -0
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +864 -195
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +255 -52
- package/src/security-flow-rules.ts +930 -109
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +502 -375
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +380 -148
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +422 -228
- package/src/text-scans.ts +67 -9
- package/src/types.ts +222 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -153
- package/src/test-fixtures.ts +0 -668
package/src/blocks.ts
CHANGED
|
@@ -1,71 +1,98 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
|
|
5
|
-
import {
|
|
1
|
+
// Discovers callable and test blocks and evaluates size, complexity, documentation, and useless-return rules.
|
|
2
|
+
//
|
|
3
|
+
// Reuses the shared syntax tree from `parsed-script.ts` when available and falls back to masked text spans otherwise.
|
|
4
|
+
// Keeps every warning anchored to the declaration line the developer edits in CLI, HTML, and hook reports.
|
|
5
|
+
import { optionBoolean, ruleSeverity, threshold } from "./config.ts";
|
|
6
|
+
import { hasFunctionLeadingCommentBeforeLines } from "./comment-scanner.ts";
|
|
7
|
+
import { baseComplexityMetrics, complexityMetrics as measureComplexity, type ComplexityMetrics } from "./complexity-metrics.ts";
|
|
6
8
|
import { type SourceFile } from "./discovery.ts";
|
|
7
9
|
import { makeFinding } from "./findings.ts";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
+
import { ruleDescriptors } from "./rules.ts";
|
|
11
|
+
import { lineOffset, parameterNames } from "./findings-helpers.ts";
|
|
12
|
+
import { bandedFields, GROUP_PARAMETERS, LOWER_BAND_FUNCTION, LOWER_BAND_PARAMETER, SIMPLIFY_PATH, SPLIT_FUNCTION } from "./limit-band.ts";
|
|
13
|
+
import { callableMatchPoints, codeLineFlags, isCallableReturningValue, isPublicExportedClassMethod, measuredOnlyCallablePoints, type CallableMatchPoint, type ParsedScript } from "./parsed-script.ts";
|
|
10
14
|
import type { Config, Finding, Pillar, Severity } from "./types.ts";
|
|
11
15
|
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
16
|
+
// Describe one callable that block rules can locate in a developer's scan report.
|
|
17
|
+
//
|
|
18
|
+
// Raw and masked bodies let each rule inspect the right text without another parse.
|
|
19
|
+
// Missing optional fields identify legacy text spans rather than shared syntax nodes.
|
|
15
20
|
export interface FunctionBlock {
|
|
16
21
|
name: string;
|
|
17
22
|
params: string;
|
|
23
|
+
// AST parameter count; absent only for legacy regex-derived blocks.
|
|
24
|
+
parameterCount?: number;
|
|
25
|
+
// Shared syntax metric; absent only for legacy regex span probes.
|
|
26
|
+
complexityMetrics?: ComplexityMetrics;
|
|
27
|
+
// AST-known body presence; absent only for legacy regex-derived blocks.
|
|
28
|
+
hasBody?: boolean;
|
|
29
|
+
// Shared callable node for structure checks; legacy text probes leave it absent.
|
|
30
|
+
callableNode?: import("typescript").Node;
|
|
31
|
+
// AST-known `override` modifier; absent for legacy regex-derived blocks, which keep name findings.
|
|
32
|
+
isOverride?: boolean;
|
|
18
33
|
startLine: number;
|
|
34
|
+
// Raw span from the first JSDoc or decorator line to the closing line; it places findings and changed regions.
|
|
19
35
|
lineCount: number;
|
|
36
|
+
// Code lines in that span, with JSDoc, comments, blank lines and decorators free; every length threshold reads this.
|
|
37
|
+
codeLineCount: number;
|
|
20
38
|
body: string;
|
|
21
39
|
codeBody: string;
|
|
22
40
|
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.
|
|
41
|
+
// True for exported/re-exported module APIs; unlike `isPublic`, class modifiers do not qualify.
|
|
42
|
+
// This selects warning-tier API docs while internal helpers remain advisory.
|
|
28
43
|
isExported: boolean;
|
|
29
44
|
isTest: boolean;
|
|
30
45
|
hasLeadingComment: boolean;
|
|
31
46
|
declarationLine: number;
|
|
32
47
|
}
|
|
33
48
|
|
|
34
|
-
//
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
// (the line-local `^export` check alone would miss this common pattern).
|
|
49
|
+
// Carry the lines and export names needed to discover report blocks in one scanned file.
|
|
50
|
+
//
|
|
51
|
+
// Patterns are shared across files so each block uses the same supported callable forms.
|
|
52
|
+
// Re-exported names keep an earlier local declaration on the public-documentation path.
|
|
39
53
|
interface FunctionBlockScan {
|
|
40
54
|
lines: string[];
|
|
41
55
|
codeLines: string[];
|
|
56
|
+
// One flag per line, true where the line carries code (`codeLineFlags` in parsed-script.ts).
|
|
57
|
+
isCodeLine: boolean[];
|
|
42
58
|
patterns: RegExp[];
|
|
43
59
|
reExportedNames: ReadonlySet<string>;
|
|
44
60
|
}
|
|
45
61
|
|
|
46
62
|
const FUNCTION_BLOCK_PATTERNS = functionBlockPatterns();
|
|
47
63
|
|
|
48
|
-
//
|
|
49
|
-
|
|
64
|
+
// Test findings carry the catalogue's advice in JSON as well as hook output.
|
|
65
|
+
const TEST_QUALITY_ADVICE = new Map(ruleDescriptors()
|
|
66
|
+
.filter((descriptor) => descriptor.pillar === "test-quality")
|
|
67
|
+
.map((descriptor) => [descriptor.ruleId, descriptor.remediation]));
|
|
68
|
+
|
|
69
|
+
// Track an opened callable body while discovering the span used by scan rules.
|
|
70
|
+
//
|
|
71
|
+
// Brace depth applies only after an opening brace has been seen.
|
|
72
|
+
// An unopened state cannot end a block or absorb its following declaration.
|
|
50
73
|
interface FunctionBodyScanState {
|
|
51
74
|
depth: number;
|
|
52
75
|
hasSeenOpen: boolean;
|
|
53
76
|
}
|
|
54
77
|
|
|
55
|
-
//
|
|
56
|
-
//
|
|
78
|
+
// Share one callable's body, settings and complexity result across its scan rules.
|
|
79
|
+
//
|
|
80
|
+
// Findings must accumulate in the fixed rule order used by report consumers.
|
|
81
|
+
// Legacy spans use base complexity when no parsed metric is available.
|
|
57
82
|
export interface BlockRuleContext {
|
|
58
83
|
file: SourceFile;
|
|
59
84
|
block: FunctionBlock;
|
|
60
85
|
config: Config;
|
|
61
86
|
findings: Finding[];
|
|
87
|
+
complexityMetrics: ComplexityMetrics;
|
|
88
|
+
// The shared cyclomatic count the cyclomatic finding reports.
|
|
62
89
|
cyclomatic: number;
|
|
63
|
-
functionBody: string;
|
|
64
90
|
}
|
|
65
91
|
|
|
66
|
-
//
|
|
67
|
-
//
|
|
68
|
-
//
|
|
92
|
+
// Carry the rule and callable location needed to construct one scan warning.
|
|
93
|
+
//
|
|
94
|
+
// The block supplies the line and symbol a developer uses to find the declaration.
|
|
95
|
+
// Severity and pillar keep the result in the caller's selected report category.
|
|
69
96
|
export interface BlockFindingArgs {
|
|
70
97
|
ruleId: string;
|
|
71
98
|
message: string;
|
|
@@ -75,26 +102,39 @@ export interface BlockFindingArgs {
|
|
|
75
102
|
pillar: Pillar;
|
|
76
103
|
}
|
|
77
104
|
|
|
78
|
-
//
|
|
79
|
-
//
|
|
80
|
-
// consumers
|
|
105
|
+
// Carry a block warning together with the rule's measurements or other metadata.
|
|
106
|
+
//
|
|
107
|
+
// Use it when consumers need thresholds or measurements alongside the editable source location.
|
|
108
|
+
// Measurements travel with the warning; finding identifiers are computed separately.
|
|
109
|
+
// Contract: metadata and any remediation reach the finding unchanged, so a band's advice and key stay together.
|
|
81
110
|
export interface BlockFindingWithMetadataArgs extends BlockFindingArgs {
|
|
82
111
|
metadata: Record<string, unknown>;
|
|
112
|
+
// The band's advice on a size or complexity finding; other block rules leave it out.
|
|
113
|
+
remediation?: string;
|
|
83
114
|
}
|
|
84
115
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
116
|
+
/**
|
|
117
|
+
* Builds a high-confidence finding from the rule details and severity, omitting remediation when the rule has no advice.
|
|
118
|
+
* Use the metadata variant when the rule needs measurements; analysis then replaces the confidence with the rule's catalogue confidence.
|
|
119
|
+
*
|
|
120
|
+
* @param args - Rule details, severity, pillar, file, and block used for the stable source anchor.
|
|
121
|
+
* @returns High-confidence finding anchored to the block span, with test-quality advice attached when available.
|
|
122
|
+
*/
|
|
89
123
|
export function blockFinding(args: BlockFindingArgs): Finding {
|
|
90
124
|
const endLine = args.block.startLine + args.block.lineCount - 1;
|
|
91
|
-
|
|
125
|
+
const remediation = TEST_QUALITY_ADVICE.get(args.ruleId);
|
|
126
|
+
return makeFinding({ ruleId: args.ruleId, message: args.message, filePath: args.file.displayPath, line: args.block.startLine, endLine, severity: args.severity, pillar: args.pillar, confidence: "high", symbol: args.block.name, ...(remediation === undefined ? {} : { remediation }) });
|
|
92
127
|
}
|
|
93
128
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
129
|
+
/**
|
|
130
|
+
* Builds a medium-confidence finding with attached measurements without changing the fingerprint, and analysis then applies catalogue confidence.
|
|
131
|
+
* Uses explicit remediation and falls back to rule advice, omitting remediation when the override is empty or neither source supplies advice.
|
|
132
|
+
*
|
|
133
|
+
* @param args - Rule details, severity, pillar, metadata, optional remediation, file, and block used for the stable source anchor.
|
|
134
|
+
* @returns Medium-confidence finding anchored to the block span with metadata attached and resolved remediation.
|
|
135
|
+
*/
|
|
97
136
|
export function blockFindingWithMetadata(args: BlockFindingWithMetadataArgs): Finding {
|
|
137
|
+
const remediation = args.remediation ?? TEST_QUALITY_ADVICE.get(args.ruleId);
|
|
98
138
|
return makeFinding({
|
|
99
139
|
ruleId: args.ruleId,
|
|
100
140
|
message: args.message,
|
|
@@ -105,257 +145,204 @@ export function blockFindingWithMetadata(args: BlockFindingWithMetadataArgs): Fi
|
|
|
105
145
|
pillar: args.pillar,
|
|
106
146
|
confidence: "medium",
|
|
107
147
|
symbol: args.block.name,
|
|
148
|
+
...(remediation === undefined ? {} : { remediation }),
|
|
108
149
|
metadata: args.metadata,
|
|
109
150
|
});
|
|
110
151
|
}
|
|
111
152
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
153
|
+
/**
|
|
154
|
+
* Builds the rule context for a callable, using base complexity for legacy spans to preserve the report invariant without another parse.
|
|
155
|
+
*
|
|
156
|
+
* @param file - Source file descriptor providing display paths for source anchors.
|
|
157
|
+
* @param block - Discovered function or test block providing the span and optional syntax metrics.
|
|
158
|
+
* @param config - Active rule configuration supplying thresholds and severities.
|
|
159
|
+
* @param findings - Shared output collector where rules append emitted findings.
|
|
160
|
+
* @returns Rule context bundling the callable, settings, shared findings collector, and resolved complexity metrics.
|
|
161
|
+
*/
|
|
115
162
|
export function blockRuleContext(file: SourceFile, block: FunctionBlock, config: Config, findings: Finding[]): BlockRuleContext {
|
|
163
|
+
// A regex-only caller has no shared syntax node, so it receives the neutral base measurement.
|
|
164
|
+
const sharedComplexityMetrics = block.complexityMetrics ?? baseComplexityMetrics();
|
|
116
165
|
return {
|
|
117
166
|
file,
|
|
118
167
|
block,
|
|
119
168
|
config,
|
|
120
169
|
findings,
|
|
121
|
-
|
|
122
|
-
|
|
170
|
+
complexityMetrics: sharedComplexityMetrics,
|
|
171
|
+
cyclomatic: sharedComplexityMetrics.cyclomatic,
|
|
123
172
|
};
|
|
124
173
|
}
|
|
125
174
|
|
|
126
|
-
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
*
|
|
175
|
+
/**
|
|
176
|
+
* Runs size and complexity checks first, then missing-documentation and useless-return checks for one callable.
|
|
177
|
+
*
|
|
178
|
+
* @param context - Shared block rule context supplying the callable, rule settings, measurements, and findings collector.
|
|
179
|
+
* @returns Nothing. Appends matching findings to context.findings.
|
|
130
180
|
*/
|
|
131
181
|
export function analyseBlockRules(context: BlockRuleContext): void {
|
|
182
|
+
analyseBlockMeasures(context);
|
|
183
|
+
pushMissingFunctionDocFinding(context);
|
|
184
|
+
pushUselessReturnFindings(context);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Runs size and complexity rules in the stable order used by analyseBlockRules for callables measured only by those rules.
|
|
189
|
+
* See FAMILY-CONTRACT.md section 12 under four more function forms for why documentation and useless-return checks are skipped.
|
|
190
|
+
*
|
|
191
|
+
* @param context - Shared block rule context supplying the block measurements, rule config, and findings collector.
|
|
192
|
+
* @returns Nothing. Appends matching size and complexity findings to context.findings.
|
|
193
|
+
*/
|
|
194
|
+
export function analyseBlockMeasures(context: BlockRuleContext): void {
|
|
132
195
|
pushFunctionLengthFinding(context);
|
|
133
196
|
pushParameterCountFinding(context);
|
|
134
197
|
pushCyclomaticFinding(context);
|
|
135
|
-
pushCognitiveFinding(context);
|
|
136
|
-
pushGenericFunctionFinding(context);
|
|
137
|
-
pushMissingFunctionDocFinding(context);
|
|
138
|
-
pushEmptyFunctionFinding(context);
|
|
139
|
-
pushUnusedParameterFindings(context);
|
|
140
|
-
pushRedundantVariableFindings(context);
|
|
141
|
-
pushUselessReturnFindings(context);
|
|
142
198
|
}
|
|
143
199
|
|
|
144
|
-
|
|
145
|
-
|
|
200
|
+
/**
|
|
201
|
+
* Checks whether a callable's codeLineCount exceeds the configured size.function-length limit, which defaults to 200.
|
|
202
|
+
*
|
|
203
|
+
* @param context - Shared block rule context supplying the callable block, source location, rule settings, and findings collector.
|
|
204
|
+
* @returns Nothing. Appends a banded size finding to context.findings when codeLineCount exceeds the limit.
|
|
205
|
+
*/
|
|
146
206
|
function pushFunctionLengthFinding(context: BlockRuleContext): void {
|
|
147
207
|
const functionLengthThreshold = threshold(context.config, "size.function-length", 200);
|
|
148
|
-
|
|
208
|
+
// Lower-band overruns are advisory. The upper band uses the configured severity.
|
|
209
|
+
if (context.block.codeLineCount > functionLengthThreshold) {
|
|
210
|
+
const band = bandedFields(context.block.codeLineCount, functionLengthThreshold, ruleSeverity(context.config, "size.function-length", "warning"), LOWER_BAND_FUNCTION, SPLIT_FUNCTION);
|
|
149
211
|
context.findings.push(blockFindingWithMetadata({
|
|
150
212
|
ruleId: "size.function-length",
|
|
151
|
-
message: `Function \`${context.block.name}\` has ${context.block.
|
|
213
|
+
message: `Function \`${context.block.name}\` has ${context.block.codeLineCount} lines, above the threshold of ${functionLengthThreshold}.`,
|
|
152
214
|
file: context.file,
|
|
153
215
|
block: context.block,
|
|
154
|
-
severity:
|
|
216
|
+
severity: band.severity,
|
|
155
217
|
pillar: "size",
|
|
156
|
-
|
|
218
|
+
remediation: band.remediation,
|
|
219
|
+
metadata: { lines: context.block.codeLineCount, threshold: functionLengthThreshold, limitBand: band.limitBand },
|
|
157
220
|
}));
|
|
158
221
|
}
|
|
159
222
|
}
|
|
160
223
|
|
|
161
|
-
|
|
162
|
-
|
|
224
|
+
/**
|
|
225
|
+
* Checks whether a callable exceeds the configured parameter-count limit, which defaults to seven.
|
|
226
|
+
* Uses the parsed parameterCount when present; otherwise counts nonempty comma-separated entries in parameter text.
|
|
227
|
+
*
|
|
228
|
+
* @param context - Shared block rule context supplying the callable block, source location, rule settings, and findings collector.
|
|
229
|
+
* @returns Nothing. Appends a banded parameter-count finding to context.findings when the count exceeds the limit.
|
|
230
|
+
*/
|
|
163
231
|
function pushParameterCountFinding(context: BlockRuleContext): void {
|
|
164
|
-
const params = context.block.params.split(",").map((value) => value.trim()).filter(Boolean).length;
|
|
232
|
+
const params = context.block.parameterCount ?? context.block.params.split(",").map((value) => value.trim()).filter(Boolean).length;
|
|
165
233
|
const parameterCountThreshold = threshold(context.config, "size.parameter-count", 7);
|
|
234
|
+
// The lower band is advisory. The upper band uses the configured severity for the larger overrun.
|
|
166
235
|
if (params > parameterCountThreshold) {
|
|
236
|
+
const band = bandedFields(params, parameterCountThreshold, ruleSeverity(context.config, "size.parameter-count", "warning"), LOWER_BAND_PARAMETER, GROUP_PARAMETERS);
|
|
167
237
|
context.findings.push(blockFindingWithMetadata({
|
|
168
238
|
ruleId: "size.parameter-count",
|
|
169
239
|
message: `Function \`${context.block.name}\` declares ${params} parameters.`,
|
|
170
240
|
file: context.file,
|
|
171
241
|
block: context.block,
|
|
172
|
-
severity:
|
|
242
|
+
severity: band.severity,
|
|
173
243
|
pillar: "size",
|
|
174
|
-
|
|
244
|
+
remediation: band.remediation,
|
|
245
|
+
metadata: { parameters: params, threshold: parameterCountThreshold, limitBand: band.limitBand },
|
|
175
246
|
}));
|
|
176
247
|
}
|
|
177
248
|
}
|
|
178
249
|
|
|
179
|
-
|
|
180
|
-
|
|
250
|
+
/**
|
|
251
|
+
* Checks whether a callable's shared cyclomatic count exceeds the configured limit, which defaults to 15.
|
|
252
|
+
* Uses context's file, callable, and complexity breakdown to anchor and explain the finding.
|
|
253
|
+
*
|
|
254
|
+
* @param context - Shared block rule context supplying the cyclomatic count, complexity breakdown, settings, and findings collector.
|
|
255
|
+
* @returns Nothing. Appends a banded complexity finding to context.findings when cyclomatic complexity exceeds the limit.
|
|
256
|
+
*/
|
|
181
257
|
function pushCyclomaticFinding(context: BlockRuleContext): void {
|
|
182
258
|
const cyclomaticThreshold = threshold(context.config, "complexity.cyclomatic", 15);
|
|
259
|
+
// The lower band is advisory. The upper band uses the configured severity for the larger overrun.
|
|
183
260
|
if (context.cyclomatic > cyclomaticThreshold) {
|
|
261
|
+
const band = bandedFields(context.cyclomatic, cyclomaticThreshold, ruleSeverity(context.config, "complexity.cyclomatic", "warning"), LOWER_BAND_FUNCTION, SIMPLIFY_PATH);
|
|
184
262
|
context.findings.push(blockFindingWithMetadata({
|
|
185
263
|
ruleId: "complexity.cyclomatic",
|
|
186
264
|
message: `Function \`${context.block.name}\` has cyclomatic complexity ${context.cyclomatic}.`,
|
|
187
265
|
file: context.file,
|
|
188
266
|
block: context.block,
|
|
189
|
-
severity:
|
|
267
|
+
severity: band.severity,
|
|
190
268
|
pillar: "complexity",
|
|
191
|
-
|
|
269
|
+
remediation: band.remediation,
|
|
270
|
+
metadata: { complexity: context.cyclomatic, threshold: cyclomaticThreshold, breakdown: context.complexityMetrics.breakdown, limitBand: band.limitBand },
|
|
192
271
|
}));
|
|
193
272
|
}
|
|
194
273
|
}
|
|
195
274
|
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
context.findings.push(blockFindingWithMetadata({
|
|
203
|
-
ruleId: "complexity.cognitive",
|
|
204
|
-
message: `Function \`${context.block.name}\` has cognitive complexity ${cognitive}.`,
|
|
205
|
-
file: context.file,
|
|
206
|
-
block: context.block,
|
|
207
|
-
severity: ruleSeverity(context.config, "complexity.cognitive", "warning"),
|
|
208
|
-
pillar: "complexity",
|
|
209
|
-
metadata: { complexity: cognitive, threshold: cognitiveThreshold },
|
|
210
|
-
}));
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
// Names like `process`, `handle`, `run` from `config.bannedGenericNames`. The list is user-configurable;
|
|
215
|
-
// the rule body itself just consults the config. Reports `naming.generic-function`.
|
|
216
|
-
function pushGenericFunctionFinding(context: BlockRuleContext): void {
|
|
217
|
-
if (isGenericName(context.block.name, context.config.bannedGenericNames)) {
|
|
218
|
-
context.findings.push(blockFinding({ ruleId: "naming.generic-function", message: `Function \`${context.block.name}\` is too generic to explain intent.`, file: context.file, block: context.block, severity: "advisory", pillar: "naming" }));
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/*
|
|
223
|
-
* Every non-test function must carry a leading comment. Test blocks are exempted because their
|
|
224
|
-
* `test("name", …)` description already documents intent. Reports
|
|
225
|
-
* `docs.missing-exported-function-doc` (warning, higher cost of omission on the public API
|
|
226
|
-
* surface) when `isExported` is true, `docs.missing-internal-function-doc` (advisory) otherwise.
|
|
275
|
+
/**
|
|
276
|
+
* Checks whether a non-test callable lacks a recognized leading comment.
|
|
277
|
+
* Exported APIs receive warnings and internal callables receive advisory findings.
|
|
278
|
+
*
|
|
279
|
+
* @param context - Shared block rule context supplying the callable block, location, rule settings, and findings collector.
|
|
280
|
+
* @returns Nothing. Appends a missing-documentation finding to context.findings when a leading comment is missing.
|
|
227
281
|
*/
|
|
228
282
|
function pushMissingFunctionDocFinding(context: BlockRuleContext): void {
|
|
229
283
|
if (context.block.isTest || context.block.hasLeadingComment) {
|
|
230
284
|
return;
|
|
231
285
|
}
|
|
232
|
-
const
|
|
233
|
-
const
|
|
234
|
-
const
|
|
235
|
-
context.findings.push(blockFinding({ ruleId, message:
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
// Empty bodies are sometimes intentional placeholders, hence the advisory severity rather than
|
|
239
|
-
// warning. Reports `waste.empty-function` when the body strips to whitespace/comments only.
|
|
240
|
-
function pushEmptyFunctionFinding(context: BlockRuleContext): void {
|
|
241
|
-
if (isBodyLessDeclaration(context.block) || isDeclarationFile(context.file)) {
|
|
242
|
-
return;
|
|
243
|
-
}
|
|
244
|
-
if (isEmptyFunctionBody(context.block.codeBody)) {
|
|
245
|
-
if (isDocumentedEmptyTestDouble(context)) {
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
context.findings.push(blockFinding({ ruleId: "waste.empty-function", message: `Function \`${context.block.name}\` has no executable body.`, file: context.file, block: context.block, severity: "advisory", pillar: "maintainability" }));
|
|
249
|
-
}
|
|
286
|
+
const isExportedApi = context.block.isExported || isEveryCallablePublicMethod(context);
|
|
287
|
+
const ruleId = isExportedApi ? "docs.missing-exported-function-doc" : "docs.missing-internal-function-doc";
|
|
288
|
+
const severity = isExportedApi ? "warning" : "advisory";
|
|
289
|
+
context.findings.push(blockFinding({ ruleId, message: missingFunctionDocMessage(context.block, isExportedApi ? "Exported" : "Internal"), file: context.file, block: context.block, severity, pillar: "documentation" }));
|
|
250
290
|
}
|
|
251
291
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
// `_`-prefixed parameters are exempted (the standard "intentionally unused" convention).
|
|
268
|
-
// Reports `waste.unused-parameter` for parameter names that never appear in the callable body.
|
|
269
|
-
function pushUnusedParameterFindings(context: BlockRuleContext): void {
|
|
270
|
-
if (isBodyLessDeclaration(context.block) || isDeclarationFile(context.file)) {
|
|
271
|
-
return;
|
|
272
|
-
}
|
|
273
|
-
for (const parameter of parameterNames(context.block.params)) {
|
|
274
|
-
if (!isUnusedParameter(context, parameter.name)) {
|
|
275
|
-
continue;
|
|
276
|
-
}
|
|
277
|
-
context.findings.push(unusedParameterFinding(context, parameter.name));
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
// Skips interface methods, type-literal methods, function-type aliases, abstract members, and
|
|
282
|
-
// overload signatures - all of which look like a function declaration ending in `;` rather than `{`,
|
|
283
|
-
// and have no real body to check for emptiness or parameter usage.
|
|
284
|
-
function isBodyLessDeclaration(block: FunctionBlock): boolean {
|
|
285
|
-
for (const rawLine of block.codeBody.split("\n")) {
|
|
286
|
-
const trimmed = rawLine.trim();
|
|
287
|
-
if (trimmed === "" || trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
|
|
288
|
-
continue;
|
|
289
|
-
}
|
|
290
|
-
return /\)[^{;]*;\s*$/.test(trimmed);
|
|
292
|
+
/**
|
|
293
|
+
* Formats a missing-documentation message for a callable, requesting descriptions for non-this parameters, return values, and throws.
|
|
294
|
+
* A throw token in the masked body triggers the failure prompt under the docs.missing-error-behavior-doc criterion.
|
|
295
|
+
*
|
|
296
|
+
* @param block - Callable block supplying name, parameter text, masked body, and optional syntax node.
|
|
297
|
+
* @param audience - Label prefix indicating whether the callable is Exported or Internal.
|
|
298
|
+
* @returns Formatted missing-documentation message prefixed by audience, with no suffix when no prompts apply.
|
|
299
|
+
*/
|
|
300
|
+
function missingFunctionDocMessage(block: FunctionBlock, audience: "Exported" | "Internal"): string {
|
|
301
|
+
const asks: string[] = [];
|
|
302
|
+
const names = parameterNames(block.params).map((parameter) => parameter.name).filter((name) => name !== "this");
|
|
303
|
+
if (names.length > 0) {
|
|
304
|
+
asks.push(`describe ${names.length > 1 ? "parameters" : "parameter"} ${names.map((name) => `\`${name}\``).join(", ")}`);
|
|
291
305
|
}
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
// TypeScript `.d.ts` files only declare types; every callable in them is a signature, never an
|
|
296
|
-
// implementation, so the empty/unused-parameter rules are categorically misapplied there.
|
|
297
|
-
function isDeclarationFile(file: SourceFile): boolean {
|
|
298
|
-
return file.displayPath.endsWith(".d.ts");
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
// Word-boundary regex against the masked function body. The body is masked so a parameter mentioned
|
|
302
|
-
// only in a string literal would still count as unused - that matches the intent of the rule. A
|
|
303
|
-
// loose `${...param...}` regex over the raw body catches parameters used only inside template
|
|
304
|
-
// interpolations, which the mask would otherwise hide.
|
|
305
|
-
function isUnusedParameter(context: BlockRuleContext, parameterName: string): boolean {
|
|
306
|
-
if (parameterName.startsWith("_")) {
|
|
307
|
-
return false;
|
|
306
|
+
if (block.callableNode !== undefined && isCallableReturningValue(block.callableNode)) {
|
|
307
|
+
asks.push("describe the return value");
|
|
308
308
|
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
return false;
|
|
309
|
+
if (/\bthrow\b/.test(block.codeBody)) {
|
|
310
|
+
asks.push("say when it throws");
|
|
312
311
|
}
|
|
313
|
-
|
|
312
|
+
const suffix = asks.length > 0 ? `; ${asks.join("; ")}` : "";
|
|
313
|
+
return `${audience} function \`${block.name}\` is missing a leading maintainer comment${suffix}.`;
|
|
314
314
|
}
|
|
315
315
|
|
|
316
|
-
|
|
317
|
-
*
|
|
318
|
-
*
|
|
316
|
+
/**
|
|
317
|
+
* Checks whether context enables either everyCallable tag option and its parsed callable is a public method of a directly exported class.
|
|
318
|
+
*
|
|
319
|
+
* @param context - Shared block rule context supplying the rule config and optional parsed callable node.
|
|
320
|
+
* @returns True when enabled and callableNode is a public method of a directly exported class; false if callableNode is absent.
|
|
319
321
|
*/
|
|
320
|
-
function
|
|
321
|
-
return
|
|
322
|
-
ruleId: "waste.unused-parameter",
|
|
323
|
-
message: `Parameter \`${parameterName}\` does not appear to be used.`,
|
|
324
|
-
filePath: context.file.displayPath,
|
|
325
|
-
line: context.block.startLine,
|
|
326
|
-
severity: "advisory",
|
|
327
|
-
pillar: "maintainability",
|
|
328
|
-
confidence: "medium",
|
|
329
|
-
symbol: context.block.name,
|
|
330
|
-
remediation: "Remove the parameter or prefix it with _ if it is intentionally unused.",
|
|
331
|
-
metadata: { parameter: parameterName },
|
|
332
|
-
});
|
|
322
|
+
function isEveryCallablePublicMethod(context: BlockRuleContext): boolean {
|
|
323
|
+
return isTagRuleEveryCallable(context.config) && context.block.callableNode !== undefined && isPublicExportedClassMethod(context.block.callableNode);
|
|
333
324
|
}
|
|
334
325
|
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
severity: "advisory",
|
|
346
|
-
pillar: "maintainability",
|
|
347
|
-
confidence: "medium",
|
|
348
|
-
symbol: redundant.name,
|
|
349
|
-
remediation: "Return the expression directly.",
|
|
350
|
-
metadata: { variable: redundant.name },
|
|
351
|
-
}),
|
|
352
|
-
);
|
|
353
|
-
}
|
|
326
|
+
/**
|
|
327
|
+
* Checks whether either tag rule's everyCallable switch is enabled; both are on by default.
|
|
328
|
+
* Setting both false keeps a public method of an exported class in the internal tier.
|
|
329
|
+
*
|
|
330
|
+
* @param config - Active rule configuration containing option overrides for tag rules.
|
|
331
|
+
* @returns True if docs.missing-param-tag or docs.missing-return-tag has everyCallable enabled.
|
|
332
|
+
*/
|
|
333
|
+
function isTagRuleEveryCallable(config: Config): boolean {
|
|
334
|
+
return optionBoolean(config, "docs.missing-param-tag", "everyCallable", true)
|
|
335
|
+
|| optionBoolean(config, "docs.missing-return-tag", "everyCallable", true);
|
|
354
336
|
}
|
|
355
337
|
|
|
356
|
-
|
|
357
|
-
|
|
338
|
+
/**
|
|
339
|
+
* Detects terminal bare returns in a callable's masked body and anchors each finding using context.block.startLine.
|
|
340
|
+
*
|
|
341
|
+
* @param context - Shared block rule context supplying the callable block, file path, and findings collector.
|
|
342
|
+
* @returns Nothing. Appends waste.useless-return advisories to context.findings for each detected terminal bare return.
|
|
343
|
+
*/
|
|
358
344
|
function pushUselessReturnFindings(context: BlockRuleContext): void {
|
|
345
|
+
// The line scan skips a return it recognizes as the catch's only handling, so the advice cannot leave that catch empty.
|
|
359
346
|
for (const lineOffset of terminalBareReturnLines(context.block.codeBody)) {
|
|
360
347
|
context.findings.push(
|
|
361
348
|
makeFinding({
|
|
@@ -373,22 +360,16 @@ function pushUselessReturnFindings(context: BlockRuleContext): void {
|
|
|
373
360
|
}
|
|
374
361
|
}
|
|
375
362
|
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
.trim();
|
|
383
|
-
return body === "";
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
// Two shapes: block-body callables return the text between the outermost `{` and `}`; expression
|
|
387
|
-
// arrow functions fall back to the slice after `=>`. The trailing-`;` strip keeps the arrow
|
|
388
|
-
// branch usable for downstream regex tests that anchor on statement boundaries.
|
|
363
|
+
/**
|
|
364
|
+
* Extracts a brace body or expression-arrow body from callable source text for downstream scan checks.
|
|
365
|
+
*
|
|
366
|
+
* @param source - Raw or masked callable source text containing a brace block or arrow expression.
|
|
367
|
+
* @returns Body slice between outer braces or after the first arrow, or an empty string when no inspectable body is found.
|
|
368
|
+
*/
|
|
389
369
|
export function functionBodyContent(source: string): string {
|
|
390
|
-
const start = source
|
|
370
|
+
const start = functionBlockBrace(source);
|
|
391
371
|
const end = source.lastIndexOf("}");
|
|
372
|
+
// Without a complete brace body, use the expression-arrow text; no arrow means there is no body to inspect.
|
|
392
373
|
if (start === -1 || end <= start) {
|
|
393
374
|
const arrow = source.indexOf("=>");
|
|
394
375
|
return arrow === -1 ? "" : source.slice(arrow + 2).replace(/;?\s*$/, "");
|
|
@@ -396,106 +377,233 @@ export function functionBodyContent(source: string): string {
|
|
|
396
377
|
return source.slice(start + 1, end);
|
|
397
378
|
}
|
|
398
379
|
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
380
|
+
/**
|
|
381
|
+
* Finds the callable's opening brace index while skipping template interpolation braces.
|
|
382
|
+
*
|
|
383
|
+
* @param source - Callable source text to scan for an opening body brace.
|
|
384
|
+
* @returns Zero-based index of the first non-interpolation opening brace, or -1 for an expression body so block rules use fallback.
|
|
385
|
+
*/
|
|
386
|
+
function functionBlockBrace(source: string): number {
|
|
387
|
+
// Look for a real body opener so template interpolation cannot shift the warning's block range.
|
|
388
|
+
for (let index = source.indexOf("{"); index !== -1; index = source.indexOf("{", index + 1)) {
|
|
389
|
+
// An interpolation brace does not open the callable body used by block rules.
|
|
390
|
+
if (source[index - 1] !== "$") {
|
|
391
|
+
return index;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
return -1;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Finds a terminal bare return in masked callable source for useless-return findings.
|
|
400
|
+
*
|
|
401
|
+
* @param source - Comment-masked callable body text split by line to inspect trailing statements.
|
|
402
|
+
* @returns One-element array with the zero-based return line index, or empty when absent or when it is the catch block's only statement.
|
|
403
|
+
*/
|
|
402
404
|
function terminalBareReturnLines(source: string): number[] {
|
|
403
405
|
const lines = source.split(/\r?\n/);
|
|
404
406
|
let current = lines.length - 1;
|
|
405
407
|
while (current >= 0) {
|
|
406
408
|
const trimmed = lines[current]?.trim() ?? "";
|
|
409
|
+
// Closing braces and blank lines can follow the last statement without making it nonterminal.
|
|
407
410
|
if (trimmed === "" || trimmed === "}") {
|
|
408
411
|
current -= 1;
|
|
409
412
|
continue;
|
|
410
413
|
}
|
|
411
|
-
return /^return\s*;?$/.test(trimmed) ? [current] : [];
|
|
414
|
+
return /^return\s*;?$/.test(trimmed) && !isOnlyStatementOfCatch(lines, current) ? [current] : [];
|
|
412
415
|
}
|
|
413
416
|
return [];
|
|
414
417
|
}
|
|
415
418
|
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
// Detects the `const x = expr; return x;` pattern. The regex backreference `\1` enforces that the
|
|
433
|
-
// returned identifier matches the declared one - used by `waste.redundant-variable` to surface
|
|
434
|
-
// pointless temporaries with deterministic line offsets.
|
|
435
|
-
function redundantVariableReturns(source: string): Array<{ name: string; lineOffset: number }> {
|
|
436
|
-
const results: Array<{ name: string; lineOffset: number }> = [];
|
|
437
|
-
for (const match of source.matchAll(/\b(?:const|let)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*[^;]+;\s*return\s+\1\s*;/g)) {
|
|
438
|
-
results.push({ name: match[1] ?? "", lineOffset: lineOffset(source, match.index ?? 0) });
|
|
439
|
-
}
|
|
440
|
-
return results.filter((result) => result.name !== "");
|
|
441
|
-
}
|
|
442
|
-
|
|
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);
|
|
419
|
+
/**
|
|
420
|
+
* Guards against waste.useless-return suggesting a removal that would leave a catch empty and eligible for waste.swallowed-catch.
|
|
421
|
+
* Recognizes both same-line (`catch (err) {`) and Allman-style (`catch (err)\n{`) catch headers directly before the bare return.
|
|
422
|
+
*
|
|
423
|
+
* @param lines - Comment-masked lines of the callable body.
|
|
424
|
+
* @param returnIndex - Zero-based line index of the candidate bare return statement.
|
|
425
|
+
* @returns True if the first nonblank header before returnIndex opens a catch block; otherwise false.
|
|
426
|
+
*/
|
|
427
|
+
function isOnlyStatementOfCatch(lines: string[], returnIndex: number): boolean {
|
|
428
|
+
let sawStandaloneBrace = false;
|
|
429
|
+
for (let current = returnIndex - 1; current >= 0; current -= 1) {
|
|
430
|
+
const trimmed = lines[current]?.trim() ?? "";
|
|
431
|
+
if (trimmed === "") {
|
|
432
|
+
continue;
|
|
455
433
|
}
|
|
434
|
+
if (!sawStandaloneBrace && trimmed === "{") {
|
|
435
|
+
sawStandaloneBrace = true;
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
return sawStandaloneBrace
|
|
439
|
+
? /\bcatch\b(?:\s*\([^)]*\))?$/.test(trimmed)
|
|
440
|
+
: /\bcatch\b[^{]*\{$/.test(trimmed);
|
|
456
441
|
}
|
|
457
|
-
return
|
|
442
|
+
return false;
|
|
458
443
|
}
|
|
459
444
|
|
|
460
|
-
|
|
461
|
-
|
|
445
|
+
/**
|
|
446
|
+
* Checks whether a line opens a test or it registration, allowing a discarded void registration result.
|
|
447
|
+
* The block parser uses the result to select the test pattern and mark test blocks.
|
|
448
|
+
*
|
|
449
|
+
* @param line - Source or masked line to check for a leading test or it call.
|
|
450
|
+
* @returns True when the line starts with a test or it invocation; otherwise false.
|
|
451
|
+
*/
|
|
462
452
|
function isTestInvocationLine(line: string): boolean {
|
|
463
|
-
return /^\s*(?:test|it)\s*\(/.test(line);
|
|
453
|
+
return /^\s*(?:void\s+)?(?:test|it)\s*\(/.test(line);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Discovers report blocks from source, reusing a shared syntax tree for discovery and metrics when supplied.
|
|
458
|
+
* Without parsed, falls back to legacy regex discovery and omits syntax metrics.
|
|
459
|
+
*
|
|
460
|
+
* @param source - Raw script text used to slice raw bodies and detect leading comments.
|
|
461
|
+
* @param codeSource - Masked script text used for matching and codeBody fields; defaults to source.
|
|
462
|
+
* @param parsed - Optional shared syntax tree for AST-based discovery and complexity metrics.
|
|
463
|
+
* @returns Extracted function and test blocks in discovery order, or an empty array when no supported callable is found.
|
|
464
|
+
*/
|
|
465
|
+
export function functionBlocks(source: string, codeSource = source, parsed?: ParsedScript): FunctionBlock[] {
|
|
466
|
+
const scan = functionBlockScan(source, codeSource, parsed);
|
|
467
|
+
const matchPoints = matchPointsFor(scan, parsed);
|
|
468
|
+
const ownedCallableNodes = ownedCallables(matchPoints, parsed);
|
|
469
|
+
// Share ownership so enclosing block metrics skip nested callables that have their own blocks.
|
|
470
|
+
return matchPoints.map((point) => functionBlockFromPoint(scan, point, ownedCallableNodes));
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* Builds blocks for size and complexity checks on function expressions and arrows.
|
|
475
|
+
* Covers noncomputed object properties such as key: function, member assignments, var bindings and immediate invocation.
|
|
476
|
+
* Baseline matching also uses their declaration spans so that same-named callables can be ranked separately.
|
|
477
|
+
*
|
|
478
|
+
* @param source - Raw script text used to slice each callable body.
|
|
479
|
+
* @param codeSource - Masked script text used to slice the corresponding code body.
|
|
480
|
+
* @param parsed - Shared syntax tree used to locate the covered callable forms.
|
|
481
|
+
* @returns One block per occurrence of these forms, in source order; empty when the script uses none of them.
|
|
482
|
+
*/
|
|
483
|
+
export function measuredOnlyFunctionBlocks(source: string, codeSource: string, parsed: ParsedScript): FunctionBlock[] {
|
|
484
|
+
const scan = functionBlockScan(source, codeSource, parsed);
|
|
485
|
+
const ownedCallableNodes = ownedCallables(matchPointsFor(scan, parsed), parsed);
|
|
486
|
+
return measuredOnlyCallablePoints(parsed).map((point) => functionBlockFromPoint(scan, blockMatchPoint(point), ownedCallableNodes));
|
|
464
487
|
}
|
|
465
488
|
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
489
|
+
/**
|
|
490
|
+
* Prepares the line arrays, code-line flags, regex patterns, and local export names used by block builders.
|
|
491
|
+
* Without parsed, comments and blank lines are excluded from code-line flags, but decorator lines remain countable.
|
|
492
|
+
*
|
|
493
|
+
* @param source - Raw script text split into lines and inspected for code-line flags.
|
|
494
|
+
* @param codeSource - Masked script text split into code lines and scanned for local re-exports.
|
|
495
|
+
* @param parsed - Optional shared syntax tree enabling decorator exclusion in code-line flags.
|
|
496
|
+
* @returns Scan state holding raw lines, masked lines, code-line flags, callable patterns, and re-exported names.
|
|
497
|
+
*/
|
|
498
|
+
function functionBlockScan(source: string, codeSource: string, parsed: ParsedScript | undefined): FunctionBlockScan {
|
|
499
|
+
return {
|
|
471
500
|
lines: source.split(/\r?\n/),
|
|
472
501
|
codeLines: codeSource.split(/\r?\n/),
|
|
502
|
+
isCodeLine: codeLineFlags(source, parsed),
|
|
473
503
|
patterns: FUNCTION_BLOCK_PATTERNS,
|
|
474
504
|
reExportedNames: collectReExportedNames(codeSource),
|
|
475
505
|
};
|
|
476
|
-
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Collects callable syntax nodes owned by discovered blocks so complexity measurement keeps nested decisions out of enclosing counts.
|
|
510
|
+
* Without parsed, only nodes already present in matchPoints are included; points without callableNode contribute nothing.
|
|
511
|
+
*
|
|
512
|
+
* @param matchPoints - Discovered callable match points whose syntax nodes belong to their own report blocks.
|
|
513
|
+
* @param parsed - Optional shared syntax tree used to include measured-only callable nodes.
|
|
514
|
+
* @returns Set of owned callable syntax nodes excluded from enclosing complexity totals.
|
|
515
|
+
*/
|
|
516
|
+
function ownedCallables(matchPoints: BlockMatchPoint[], parsed: ParsedScript | undefined): Set<import("typescript").Node> {
|
|
517
|
+
const ownedCallableNodes = new Set<import("typescript").Node>();
|
|
518
|
+
for (const point of matchPoints) {
|
|
519
|
+
// A missing node means a caller requested the legacy regex discovery path without reparsing.
|
|
520
|
+
if (point.callableNode) {
|
|
521
|
+
ownedCallableNodes.add(point.callableNode);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
for (const point of parsed ? measuredOnlyCallablePoints(parsed) : []) {
|
|
525
|
+
ownedCallableNodes.add(point.callableNode);
|
|
526
|
+
}
|
|
527
|
+
return ownedCallableNodes;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// One callable hit used to build the block that report rules inspect.
|
|
531
|
+
//
|
|
532
|
+
// Parsed hits carry their node and exact range; legacy span probes carry only text coordinates.
|
|
533
|
+
// Empty optional fields mean the caller deliberately supplied no shared parse.
|
|
534
|
+
interface BlockMatchPoint {
|
|
535
|
+
lineIndex: number;
|
|
536
|
+
// AST-known first line of the declaration; regex points leave it absent and keep the name line.
|
|
537
|
+
declarationLineIndex?: number;
|
|
538
|
+
// AST-known end line; regex points keep the legacy brace walk instead.
|
|
539
|
+
endLineIndex?: number;
|
|
540
|
+
name: string;
|
|
541
|
+
params: string;
|
|
542
|
+
parameterCount?: number;
|
|
543
|
+
// AST-known body presence; regex points leave it absent and fall back to the text heuristic.
|
|
544
|
+
hasBody?: boolean;
|
|
545
|
+
// AST-backed visibility; regex points leave these absent and retain the text fallback.
|
|
546
|
+
isDirectlyExported?: boolean;
|
|
547
|
+
isExplicitlyPublic?: boolean;
|
|
548
|
+
isModuleScoped?: boolean;
|
|
549
|
+
// AST-known `override` modifier; regex points leave it absent, so their names stay reportable.
|
|
550
|
+
isOverride?: boolean;
|
|
551
|
+
callableNode?: import("typescript").Node;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* Collects callable match points for block construction.
|
|
556
|
+
* Reuses the supplied parse so discovery shares one syntax tree; otherwise derives points from scan lines without creating a parse.
|
|
557
|
+
*
|
|
558
|
+
* @param scan - Precomputed scan lines and ordered regex patterns used for legacy line matching.
|
|
559
|
+
* @param parsed - Optional shared syntax tree that must be reused when supplied.
|
|
560
|
+
* @returns Ordered list of callable match points from the syntax tree or legacy line scan.
|
|
561
|
+
*/
|
|
562
|
+
function matchPointsFor(scan: FunctionBlockScan, parsed: ParsedScript | undefined): BlockMatchPoint[] {
|
|
563
|
+
if (parsed) {
|
|
564
|
+
return callableMatchPoints(parsed).map(blockMatchPoint);
|
|
565
|
+
}
|
|
566
|
+
const points: BlockMatchPoint[] = [];
|
|
567
|
+
// Span-only utilities still use the legacy masked-line inventory without triggering a parse.
|
|
477
568
|
scan.codeLines.forEach((line, index) => {
|
|
478
569
|
const match = functionBlockMatch(scan, line, index);
|
|
479
|
-
|
|
480
|
-
|
|
570
|
+
// A legacy hit carries text coordinates, so block construction estimates its end from the source.
|
|
571
|
+
if (match) {
|
|
572
|
+
points.push({ lineIndex: index, name: match[1] ?? "", params: match[2] ?? "" });
|
|
481
573
|
}
|
|
482
|
-
blocks.push(functionBlockFromMatch(scan, match, index));
|
|
483
574
|
});
|
|
484
|
-
return
|
|
575
|
+
return points;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* Converts a parsed callable match point into block builder input, preserving its declaration metadata and syntax node.
|
|
580
|
+
*
|
|
581
|
+
* @param point - Parsed callable match point emitted by the syntax tree walker.
|
|
582
|
+
* @returns Block match point carrying the same coordinates, visibility flags, parameter data, and syntax node.
|
|
583
|
+
*/
|
|
584
|
+
function blockMatchPoint(point: CallableMatchPoint): BlockMatchPoint {
|
|
585
|
+
return {
|
|
586
|
+
lineIndex: point.lineIndex,
|
|
587
|
+
declarationLineIndex: point.declarationLineIndex,
|
|
588
|
+
endLineIndex: point.endLineIndex,
|
|
589
|
+
name: point.name,
|
|
590
|
+
params: point.params,
|
|
591
|
+
parameterCount: point.parameterCount,
|
|
592
|
+
hasBody: point.hasBody,
|
|
593
|
+
isDirectlyExported: point.isDirectlyExported,
|
|
594
|
+
isExplicitlyPublic: point.isExplicitlyPublic,
|
|
595
|
+
isModuleScoped: point.isModuleScoped,
|
|
596
|
+
isOverride: point.isOverride,
|
|
597
|
+
callableNode: point.callableNode,
|
|
598
|
+
};
|
|
485
599
|
}
|
|
486
600
|
|
|
487
|
-
|
|
488
|
-
*
|
|
489
|
-
*
|
|
490
|
-
* (bare-identifier form - `export default function ...` is matched via pattern 2 in
|
|
491
|
-
* functionBlockPatterns instead, then classified exported because the line itself starts with
|
|
492
|
-
* `export`). Re-export-from clauses (`export { foo } from "./other"`) are intentionally skipped
|
|
493
|
-
* via the negative lookahead: those names are not local declarations of this file, so promoting
|
|
494
|
-
* a same-named local to "exported" would emit a false missing-public-doc finding.
|
|
601
|
+
/**
|
|
602
|
+
* Collects local names from export lists or bare default exports for public-documentation checks.
|
|
603
|
+
* Export-from clauses refer to another module and do not add names to this local set.
|
|
495
604
|
*
|
|
496
|
-
*
|
|
497
|
-
*
|
|
498
|
-
* spans whitespace and blanked-comment runs that the masker collapses to spaces.
|
|
605
|
+
* @param codeSource - Comment-masked module source text to scan for local export lists and default exports.
|
|
606
|
+
* @returns Read-only set of locally declared identifiers re-exported by the module.
|
|
499
607
|
*/
|
|
500
608
|
function collectReExportedNames(codeSource: string): ReadonlySet<string> {
|
|
501
609
|
const names = new Set<string>();
|
|
@@ -507,6 +615,7 @@ function collectReExportedNames(codeSource: string): ReadonlySet<string> {
|
|
|
507
615
|
}
|
|
508
616
|
}
|
|
509
617
|
}
|
|
618
|
+
// A bare default export can make an earlier local declaration public.
|
|
510
619
|
for (const match of codeSource.matchAll(/^\s*export\s+default\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*;?\s*$/gm)) {
|
|
511
620
|
if (match[1]) {
|
|
512
621
|
names.add(match[1]);
|
|
@@ -515,32 +624,39 @@ function collectReExportedNames(codeSource: string): ReadonlySet<string> {
|
|
|
515
624
|
return names;
|
|
516
625
|
}
|
|
517
626
|
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
627
|
+
/**
|
|
628
|
+
* Builds the ordered regular expressions used by legacy callable discovery.
|
|
629
|
+
* Test registrations take precedence; named default-export functions remain eligible for public-documentation checks.
|
|
630
|
+
*
|
|
631
|
+
* @returns Ordered array of patterns matching tests, function declarations, methods, and arrow bindings.
|
|
632
|
+
*/
|
|
524
633
|
function functionBlockPatterns(): RegExp[] {
|
|
525
634
|
return [
|
|
526
|
-
/^\s*(?:test|it)\s*\(\s*["'`]([^"'`]+)["'`]\s*,\s*(?:async\s*)?\(([^)]*)\)\s*=>/,
|
|
635
|
+
/^\s*(?:void\s+)?(?:test|it)\s*\(\s*["'`]([^"'`]+)["'`]\s*,\s*(?:async\s*)?\(([^)]*)\)\s*=>/,
|
|
527
636
|
/^\s*(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)/,
|
|
528
637
|
/^\s*(?:public|private|protected)?\s*(?:async\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)\s*[:{]/,
|
|
529
638
|
/^\s*(?:export\s+)?(?:const|let)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*=>/,
|
|
530
639
|
];
|
|
531
640
|
}
|
|
532
641
|
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
642
|
+
/**
|
|
643
|
+
* Tests ordered callable patterns against one masked source line to find the first supported declaration or test opener.
|
|
644
|
+
*
|
|
645
|
+
* @param scan - Scan state supplying the ordered callable patterns and raw source lines.
|
|
646
|
+
* @param line - Comment-masked line at the current scan position.
|
|
647
|
+
* @param index - Zero-based line index used to look up the raw line for recovering test titles.
|
|
648
|
+
* @returns First accepted regex match array, or undefined when no pattern matches the line.
|
|
649
|
+
*/
|
|
536
650
|
function functionBlockMatch(scan: FunctionBlockScan, line: string, index: number): RegExpMatchArray | undefined {
|
|
537
651
|
const rawLine = scan.lines[index] ?? "";
|
|
652
|
+
// Try the supported callable forms in order so test registrations keep their own block role.
|
|
538
653
|
for (let patternIndex = 0; patternIndex < scan.patterns.length; patternIndex += 1) {
|
|
539
654
|
const pattern = scan.patterns[patternIndex];
|
|
540
655
|
if (!pattern) {
|
|
541
656
|
continue;
|
|
542
657
|
}
|
|
543
658
|
const match = functionPatternMatch(pattern, patternIndex, line, rawLine);
|
|
659
|
+
// The first supported match determines the callable shown to block rules.
|
|
544
660
|
if (match) {
|
|
545
661
|
return match;
|
|
546
662
|
}
|
|
@@ -548,51 +664,89 @@ function functionBlockMatch(scan: FunctionBlockScan, line: string, index: number
|
|
|
548
664
|
return undefined;
|
|
549
665
|
}
|
|
550
666
|
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
667
|
+
/**
|
|
668
|
+
* Matches one legacy callable pattern against a line while rejecting missing names and control-flow keywords.
|
|
669
|
+
* Position zero uses rawLine for recognized test openers to preserve their string titles.
|
|
670
|
+
*
|
|
671
|
+
* @param pattern - Regular expression for one callable form.
|
|
672
|
+
* @param patternIndex - Zero-based position of pattern in the ordered pattern list.
|
|
673
|
+
* @param line - Comment-masked line used for all non-test patterns and test recognition.
|
|
674
|
+
* @param rawLine - Unmasked line used when patternIndex is zero and line opens a test invocation.
|
|
675
|
+
* @returns Match array with a non-control callable name, or undefined when rejected.
|
|
676
|
+
*/
|
|
554
677
|
function functionPatternMatch(pattern: RegExp, patternIndex: number, line: string, rawLine: string): RegExpMatchArray | undefined {
|
|
555
678
|
const candidate = patternIndex === 0 && isTestInvocationLine(line) ? rawLine : line;
|
|
556
679
|
const match = candidate.match(pattern);
|
|
680
|
+
// A missing name or control keyword cannot represent a callable in the scan.
|
|
557
681
|
if (!match?.[1] || isControlBlockName(match[1])) {
|
|
558
682
|
return undefined;
|
|
559
683
|
}
|
|
560
684
|
return match;
|
|
561
685
|
}
|
|
562
686
|
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
687
|
+
/**
|
|
688
|
+
* Builds the block inspected by report rules and context documentation, preserving complexity ownership for parsed points.
|
|
689
|
+
* Legacy span-only points omit syntax complexity metrics.
|
|
690
|
+
*
|
|
691
|
+
* @param scan - Scan state supplying raw lines, masked lines, code-line flags, and local re-export names.
|
|
692
|
+
* @param point - Discovered callable match point giving line bounds, visibility, and optional syntax node.
|
|
693
|
+
* @param ownedCallableNodes - Set of owned callable nodes skipped when measuring nested complexity.
|
|
694
|
+
* @returns Constructed FunctionBlock with source spans, code line counts, visibility flags, and optional metrics.
|
|
695
|
+
*/
|
|
696
|
+
function functionBlockFromPoint(scan: FunctionBlockScan, point: BlockMatchPoint, ownedCallableNodes: ReadonlySet<import("typescript").Node>): FunctionBlock {
|
|
697
|
+
const index = point.lineIndex;
|
|
698
|
+
// Keep `startLine` anchored at the name line (plus attached JSDoc/decorators) for fingerprint stability,
|
|
699
|
+
// while counting split modifier lines (`export\nasync function`) in `codeLineCount`.
|
|
567
700
|
const start = functionStartIndex(scan.lines, index);
|
|
568
|
-
const
|
|
701
|
+
const codeStart = Math.min(start, point.declarationLineIndex ?? start);
|
|
702
|
+
const end = point.endLineIndex ?? functionEndIndex(scan, index);
|
|
569
703
|
const body = scan.lines.slice(start, end + 1).join("\n");
|
|
570
704
|
const codeBody = scan.codeLines.slice(start, end + 1).join("\n");
|
|
705
|
+
// A missing callable node identifies a legacy range probe, where base metrics are chosen later.
|
|
706
|
+
const sharedComplexityMetrics = point.callableNode ? measureComplexity(point.callableNode, ownedCallableNodes) : undefined;
|
|
707
|
+
// Parsed blocks expose metrics to both consumers; absent values stay omitted for exact optionals.
|
|
571
708
|
return {
|
|
572
|
-
name:
|
|
573
|
-
params:
|
|
709
|
+
name: point.name,
|
|
710
|
+
params: point.params,
|
|
711
|
+
...(point.parameterCount === undefined ? {} : { parameterCount: point.parameterCount }),
|
|
712
|
+
...(point.hasBody === undefined ? {} : { hasBody: point.hasBody }),
|
|
713
|
+
...(point.callableNode === undefined ? {} : { callableNode: point.callableNode }),
|
|
714
|
+
...(point.isOverride === undefined ? {} : { isOverride: point.isOverride }),
|
|
715
|
+
...(sharedComplexityMetrics === undefined ? {} : { complexityMetrics: sharedComplexityMetrics }),
|
|
574
716
|
startLine: start + 1,
|
|
575
717
|
lineCount: end - start + 1,
|
|
718
|
+
codeLineCount: scan.isCodeLine.slice(codeStart, end + 1).filter(Boolean).length,
|
|
576
719
|
body,
|
|
577
720
|
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] ?? "")
|
|
721
|
+
isPublic: point.isExplicitlyPublic ?? /\bexport\b|\bpublic\b/.test(scan.codeLines.slice(start, index + 1).join("\n")),
|
|
722
|
+
isExported: (point.isDirectlyExported ?? /^\s*export\b/.test(scan.codeLines[index] ?? ""))
|
|
723
|
+
|| point.isModuleScoped !== false && scan.reExportedNames.has(point.name),
|
|
580
724
|
isTest: isTestInvocationLine(scan.codeLines[index] ?? ""),
|
|
581
|
-
|
|
725
|
+
// Look upward from the declaration, not the name: a split-line `export async function` header would otherwise hide the declaration's own docblock
|
|
726
|
+
// behind its modifier line. A divider or the file's overview above it is not its comment.
|
|
727
|
+
hasLeadingComment: hasFunctionLeadingCommentBeforeLines(scan.lines, (point.declarationLineIndex ?? index) + 1),
|
|
582
728
|
declarationLine: index + 1,
|
|
583
729
|
};
|
|
584
730
|
}
|
|
585
731
|
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
732
|
+
/**
|
|
733
|
+
* Determines the zero-based end line for a callable starting at index, preferring expression-arrow termination over brace scanning.
|
|
734
|
+
*
|
|
735
|
+
* @param scan - Scan state supplying raw and masked source lines.
|
|
736
|
+
* @param index - Zero-based declaration line index where the callable begins.
|
|
737
|
+
* @returns Zero-based closing line index from expression-arrow termination or the brace scan fallback.
|
|
738
|
+
*/
|
|
589
739
|
function functionEndIndex(scan: FunctionBlockScan, index: number): number {
|
|
590
740
|
return expressionArrowEndIndex(scan.codeLines, index) ?? blockFunctionEndIndex(scan, index);
|
|
591
741
|
}
|
|
592
742
|
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
743
|
+
/**
|
|
744
|
+
* Walks brace depth across masked code lines to locate the closing line of a brace-delimited callable.
|
|
745
|
+
*
|
|
746
|
+
* @param scan - Scan state supplying raw lines for length bounds and masked code lines for brace counting.
|
|
747
|
+
* @param index - Zero-based line index where the callable header starts.
|
|
748
|
+
* @returns Zero-based closing line index, or the last visited line (or index if none visited) when an opened body never closes.
|
|
749
|
+
*/
|
|
596
750
|
function blockFunctionEndIndex(scan: FunctionBlockScan, index: number): number {
|
|
597
751
|
const state: FunctionBodyScanState = { depth: 0, hasSeenOpen: false };
|
|
598
752
|
let end = index;
|
|
@@ -601,6 +755,7 @@ function blockFunctionEndIndex(scan: FunctionBlockScan, index: number): number {
|
|
|
601
755
|
applyFunctionBodyCharacter(state, character);
|
|
602
756
|
}
|
|
603
757
|
end = current;
|
|
758
|
+
// Stop once the opened body closes so later functions cannot enter this block's findings.
|
|
604
759
|
if (isFunctionBodyClosed(state)) {
|
|
605
760
|
break;
|
|
606
761
|
}
|
|
@@ -608,9 +763,13 @@ function blockFunctionEndIndex(scan: FunctionBlockScan, index: number): number {
|
|
|
608
763
|
return end;
|
|
609
764
|
}
|
|
610
765
|
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
766
|
+
/**
|
|
767
|
+
* Advances brace-depth tracking for one character from a masked code line.
|
|
768
|
+
*
|
|
769
|
+
* @param state - Mutable brace scan state recording current depth and whether an opening brace was seen.
|
|
770
|
+
* @param character - Single character from the masked code line being scanned.
|
|
771
|
+
* @returns Nothing. Increments or decrements state.depth and marks state.hasSeenOpen on an opening brace.
|
|
772
|
+
*/
|
|
614
773
|
function applyFunctionBodyCharacter(state: FunctionBodyScanState, character: string): void {
|
|
615
774
|
if (character === "{") {
|
|
616
775
|
state.depth += 1;
|
|
@@ -620,24 +779,33 @@ function applyFunctionBodyCharacter(state: FunctionBodyScanState, character: str
|
|
|
620
779
|
}
|
|
621
780
|
}
|
|
622
781
|
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
782
|
+
/**
|
|
783
|
+
* Checks whether the brace scanner has seen an opening brace and returned to zero depth or below.
|
|
784
|
+
*
|
|
785
|
+
* @param state - Current brace scan state for the callable body walk.
|
|
786
|
+
* @returns True when an opening brace was observed and brace depth is zero or less; otherwise false.
|
|
787
|
+
*/
|
|
626
788
|
function isFunctionBodyClosed(state: FunctionBodyScanState): boolean {
|
|
627
789
|
return state.hasSeenOpen && state.depth <= 0;
|
|
628
790
|
}
|
|
629
791
|
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
792
|
+
/**
|
|
793
|
+
* Estimates the zero-based end line for an expression-bodied arrow function starting at index.
|
|
794
|
+
*
|
|
795
|
+
* @param codeLines - Comment-masked source lines for the file.
|
|
796
|
+
* @param index - Zero-based line index where the arrow declaration begins.
|
|
797
|
+
* @returns Zero-based end line index (defaulting to index if unterminated), or undefined if not an expression arrow.
|
|
798
|
+
*/
|
|
633
799
|
function expressionArrowEndIndex(codeLines: string[], index: number): number | undefined {
|
|
634
800
|
const line = codeLines[index] ?? "";
|
|
635
801
|
const arrowIndex = line.indexOf("=>");
|
|
802
|
+
// These lines fall through to the caller's brace scan for a span estimate.
|
|
636
803
|
if (!isExpressionArrowLine(line, arrowIndex)) {
|
|
637
804
|
return undefined;
|
|
638
805
|
}
|
|
639
806
|
for (let current = index; current < codeLines.length; current += 1) {
|
|
640
807
|
const endIndex = expressionArrowEndStep(codeLines, line, arrowIndex, index, current);
|
|
808
|
+
// A terminator or following blank line sets the reported end; otherwise keep looking.
|
|
641
809
|
if (endIndex !== undefined) {
|
|
642
810
|
return endIndex;
|
|
643
811
|
}
|
|
@@ -645,17 +813,30 @@ function expressionArrowEndIndex(codeLines: string[], index: number): number | u
|
|
|
645
813
|
return index;
|
|
646
814
|
}
|
|
647
815
|
|
|
648
|
-
|
|
649
|
-
|
|
816
|
+
/**
|
|
817
|
+
* Distinguishes single-expression arrow headers from brace-bodied functions so scan rules receive the right span.
|
|
818
|
+
*
|
|
819
|
+
* @param line - Comment-masked line containing the callable header.
|
|
820
|
+
* @param arrowIndex - Zero-based character offset of the first arrow token, or -1 if absent.
|
|
821
|
+
* @returns True when an arrow is present and no opening brace follows it on the same line.
|
|
822
|
+
*/
|
|
650
823
|
function isExpressionArrowLine(line: string, arrowIndex: number): boolean {
|
|
651
824
|
return arrowIndex !== -1 && !line.slice(arrowIndex + 2).includes("{");
|
|
652
825
|
}
|
|
653
826
|
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
827
|
+
/**
|
|
828
|
+
* Evaluates one line in an expression-arrow scan, stopping on a trailing semicolon or a blank continuation line.
|
|
829
|
+
*
|
|
830
|
+
* @param codeLines - Comment-masked source lines for the file.
|
|
831
|
+
* @param line - Masked declaration line text containing the arrow token.
|
|
832
|
+
* @param arrowIndex - Character offset of the arrow token within line.
|
|
833
|
+
* @param start - Zero-based line index of the arrow declaration.
|
|
834
|
+
* @param current - Zero-based line index currently inspected by the forward scan.
|
|
835
|
+
* @returns Estimated end line index (current on semicolon, current - 1 on blank continuation), or undefined when scan must continue.
|
|
836
|
+
*/
|
|
657
837
|
function expressionArrowEndStep(codeLines: string[], line: string, arrowIndex: number, start: number, current: number): number | undefined {
|
|
658
838
|
const trimmed = (codeLines[current] ?? "").trim();
|
|
839
|
+
// Only the text after the arrow can end the span on the declaration line.
|
|
659
840
|
if (current === start) {
|
|
660
841
|
return line.slice(arrowIndex + 2).trim().endsWith(";") ? current : undefined;
|
|
661
842
|
}
|
|
@@ -665,16 +846,23 @@ function expressionArrowEndStep(codeLines: string[], line: string, arrowIndex: n
|
|
|
665
846
|
return trimmed.endsWith(";") ? current : undefined;
|
|
666
847
|
}
|
|
667
848
|
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
849
|
+
/**
|
|
850
|
+
* Checks whether a candidate identifier is a control-flow keyword excluded by legacy callable discovery.
|
|
851
|
+
*
|
|
852
|
+
* @param name - Identifier matched before an opening parenthesis by a legacy method pattern.
|
|
853
|
+
* @returns True when name is if, for, while, switch, or catch; otherwise false.
|
|
854
|
+
*/
|
|
671
855
|
function isControlBlockName(name: string): boolean {
|
|
672
856
|
return ["if", "for", "while", "switch", "catch"].includes(name);
|
|
673
857
|
}
|
|
674
858
|
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
859
|
+
/**
|
|
860
|
+
* Finds the zero-based scan start for a declaration, extending upward over attached docblock or decorator prefix lines.
|
|
861
|
+
*
|
|
862
|
+
* @param lines - Raw source lines of the file.
|
|
863
|
+
* @param index - Zero-based line index of the callable declaration header.
|
|
864
|
+
* @returns Zero-based index of the first attached prefix line, or index when no docblock or decorator precedes it.
|
|
865
|
+
*/
|
|
678
866
|
function functionStartIndex(lines: string[], index: number): number {
|
|
679
867
|
let start = index;
|
|
680
868
|
while (start > 0) {
|
|
@@ -685,47 +873,70 @@ function functionStartIndex(lines: string[], index: number): number {
|
|
|
685
873
|
}
|
|
686
874
|
break;
|
|
687
875
|
}
|
|
876
|
+
// Skip leading blanks so the range starts at the first attached prefix line or at the declaration itself.
|
|
877
|
+
while (start < index && (lines[start]?.trim() ?? "") === "") {
|
|
878
|
+
start += 1;
|
|
879
|
+
}
|
|
688
880
|
return start;
|
|
689
881
|
}
|
|
690
882
|
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
883
|
+
/**
|
|
884
|
+
* Checks whether a preceding line looks like a decorator, JSDoc line, or blank separator attached to a callable.
|
|
885
|
+
*
|
|
886
|
+
* @param trimmedLine - Trimmed source line preceding the current start position.
|
|
887
|
+
* @returns True when the line is blank or starts with an at-sign, JSDoc opener, or asterisk so the block scan includes it.
|
|
888
|
+
*/
|
|
694
889
|
function isFunctionPrefixLine(trimmedLine: string): boolean {
|
|
695
890
|
return trimmedLine.startsWith("@") || trimmedLine.startsWith("/**") || trimmedLine.startsWith("*") || trimmedLine === "";
|
|
696
891
|
}
|
|
697
892
|
|
|
698
|
-
//
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
893
|
+
// Checks a masked test body before Gruff warns that the test makes no assertion.
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* Checks whether a masked test body contains a recognized assertion-like call or matcher marker for test-quality checks.
|
|
897
|
+
* For should.be chains, only calls to eql, equal, greaterThan, or instanceOf count.
|
|
898
|
+
*
|
|
899
|
+
* @param maskedTestBody - Comment-masked body text of a test block.
|
|
900
|
+
* @returns True if an assert, expect, Check helper, promise matcher, or supported should.be call is found.
|
|
901
|
+
*/
|
|
902
|
+
export function hasAssertion(maskedTestBody: string): boolean {
|
|
903
|
+
if (/\bassert(?:\.[A-Za-z]+|[A-Z][A-Za-z0-9_$]*)?\s*\(/.test(maskedTestBody)) {
|
|
904
|
+
return true;
|
|
905
|
+
}
|
|
906
|
+
// A typed expect call can verify a result even with generic arguments, while comparisons like `expect < high && high > (low)` stay excluded.
|
|
907
|
+
if (/\bexpect(?:\.(?:assertions|hasAssertions)|[A-Z][A-Za-z0-9_$]*)?\s*(?:<(?!\s)(?:(?!&&|\|\|)[^;\r\n])+>\s*)?\(/.test(maskedTestBody)) {
|
|
705
908
|
return true;
|
|
706
909
|
}
|
|
707
|
-
|
|
910
|
+
// A project Check helper can be the test's assertion even without an assert import.
|
|
911
|
+
if (/\b[A-Za-z_$][A-Za-z0-9_$]*Check\s*\(/.test(maskedTestBody)) {
|
|
708
912
|
return true;
|
|
709
913
|
}
|
|
710
|
-
|
|
914
|
+
// Promise matcher properties count as assertion markers even without a following matcher call.
|
|
915
|
+
if (/\.(?:rejects|resolves)\b/.test(maskedTestBody) || /\b(?:doesNotReject|rejects)\s*\(/.test(maskedTestBody)) {
|
|
711
916
|
return true;
|
|
712
917
|
}
|
|
713
|
-
if (
|
|
918
|
+
if (/\.\s*should\s*\.\s*be\s*\.\s*(?:eql|equal|greaterThan|instanceOf)\s*\(/.test(maskedTestBody)) {
|
|
714
919
|
return true;
|
|
715
920
|
}
|
|
716
921
|
return false;
|
|
717
922
|
}
|
|
718
923
|
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
924
|
+
/**
|
|
925
|
+
* Counts eligible setup lines in a masked test body up to the first assertion marker, or all eligible lines when no marker exists.
|
|
926
|
+
* Excludes blank lines and lines containing only } or });; an uninspectable body counts as zero.
|
|
927
|
+
*
|
|
928
|
+
* @param source - Comment-masked test block source text.
|
|
929
|
+
* @returns Number of fixture-purpose setup lines before the first recognized assertion marker.
|
|
930
|
+
*/
|
|
722
931
|
export function setupLineCount(source: string): number {
|
|
723
932
|
let count = 0;
|
|
724
933
|
for (const line of functionBodyContent(source).split(/\r?\n/)) {
|
|
725
934
|
const trimmed = line.trim();
|
|
935
|
+
// Standalone block and callback closers add no setup work in the two recognized forms.
|
|
726
936
|
if (isIgnorableSetupLine(trimmed)) {
|
|
727
937
|
continue;
|
|
728
938
|
}
|
|
939
|
+
// The first recognized assertion marker ends this count, so later test work cannot inflate it.
|
|
729
940
|
if (hasAssertion(trimmed)) {
|
|
730
941
|
break;
|
|
731
942
|
}
|
|
@@ -734,8 +945,12 @@ export function setupLineCount(source: string): number {
|
|
|
734
945
|
return count;
|
|
735
946
|
}
|
|
736
947
|
|
|
737
|
-
|
|
738
|
-
|
|
948
|
+
/**
|
|
949
|
+
* Checks whether a trimmed line is empty or a standalone closer, excluding it from the test's setup line count.
|
|
950
|
+
*
|
|
951
|
+
* @param trimmedLine - Already trimmed line from the callable body.
|
|
952
|
+
* @returns True when trimmedLine is empty or contains only } or });; otherwise false.
|
|
953
|
+
*/
|
|
739
954
|
function isIgnorableSetupLine(trimmedLine: string): boolean {
|
|
740
955
|
return trimmedLine.length === 0 || trimmedLine === "});" || trimmedLine === "}";
|
|
741
956
|
}
|