@blundergoat/gruff-ts 0.5.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 +82 -0
- package/CONTRIBUTING.md +32 -25
- package/README.md +49 -50
- package/SECURITY.md +18 -31
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -10
- package/docs/agent-hook.md +32 -35
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +160 -89
- 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 -172
- package/docs/rules.md +126 -98
- package/package.json +10 -8
- package/src/analyser.ts +817 -323
- 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 +62 -68
- package/src/blocks.ts +512 -336
- package/src/changed-regions.ts +380 -79
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +445 -436
- package/src/cli-program.ts +915 -172
- package/src/cli.ts +9 -3
- package/src/comment-rules.ts +236 -418
- package/src/comment-scanner.ts +339 -47
- package/src/complexity-metrics.ts +111 -35
- 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 +751 -223
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +182 -54
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +493 -140
- package/src/doc-rules.ts +602 -126
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +134 -109
- package/src/findings.ts +47 -27
- package/src/fixture-purpose-rules.ts +194 -50
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +328 -121
- package/src/hook-contract.ts +681 -255
- package/src/init-config.ts +163 -118
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -468
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +32 -127
- package/src/parsed-script.ts +868 -314
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +86 -74
- package/src/project-config-rules.ts +324 -140
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +102 -38
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +821 -203
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +249 -55
- package/src/security-flow-rules.ts +791 -115
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +460 -387
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +378 -104
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +343 -253
- package/src/text-scans.ts +62 -11
- package/src/types.ts +220 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -163
- package/src/test-fixtures.ts +0 -671
package/src/blocks.ts
CHANGED
|
@@ -1,18 +1,22 @@
|
|
|
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";
|
|
6
7
|
import { baseComplexityMetrics, complexityMetrics as measureComplexity, type ComplexityMetrics } from "./complexity-metrics.ts";
|
|
7
8
|
import { type SourceFile } from "./discovery.ts";
|
|
8
9
|
import { makeFinding } from "./findings.ts";
|
|
9
|
-
import {
|
|
10
|
-
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";
|
|
11
14
|
import type { Config, Finding, Pillar, Severity } from "./types.ts";
|
|
12
15
|
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
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.
|
|
16
20
|
export interface FunctionBlock {
|
|
17
21
|
name: string;
|
|
18
22
|
params: string;
|
|
@@ -22,8 +26,15 @@ export interface FunctionBlock {
|
|
|
22
26
|
complexityMetrics?: ComplexityMetrics;
|
|
23
27
|
// AST-known body presence; absent only for legacy regex-derived blocks.
|
|
24
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;
|
|
25
33
|
startLine: number;
|
|
34
|
+
// Raw span from the first JSDoc or decorator line to the closing line; it places findings and changed regions.
|
|
26
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;
|
|
27
38
|
body: string;
|
|
28
39
|
codeBody: string;
|
|
29
40
|
isPublic: boolean;
|
|
@@ -35,41 +46,53 @@ export interface FunctionBlock {
|
|
|
35
46
|
declarationLine: number;
|
|
36
47
|
}
|
|
37
48
|
|
|
38
|
-
//
|
|
39
|
-
//
|
|
40
|
-
//
|
|
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.
|
|
41
53
|
interface FunctionBlockScan {
|
|
42
54
|
lines: string[];
|
|
43
55
|
codeLines: string[];
|
|
56
|
+
// One flag per line, true where the line carries code (`codeLineFlags` in parsed-script.ts).
|
|
57
|
+
isCodeLine: boolean[];
|
|
44
58
|
patterns: RegExp[];
|
|
45
59
|
reExportedNames: ReadonlySet<string>;
|
|
46
60
|
}
|
|
47
61
|
|
|
48
62
|
const FUNCTION_BLOCK_PATTERNS = functionBlockPatterns();
|
|
49
63
|
|
|
50
|
-
//
|
|
51
|
-
|
|
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.
|
|
52
73
|
interface FunctionBodyScanState {
|
|
53
74
|
depth: number;
|
|
54
75
|
hasSeenOpen: boolean;
|
|
55
76
|
}
|
|
56
77
|
|
|
57
|
-
//
|
|
58
|
-
//
|
|
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.
|
|
59
82
|
export interface BlockRuleContext {
|
|
60
83
|
file: SourceFile;
|
|
61
84
|
block: FunctionBlock;
|
|
62
85
|
config: Config;
|
|
63
86
|
findings: Finding[];
|
|
64
87
|
complexityMetrics: ComplexityMetrics;
|
|
65
|
-
//
|
|
88
|
+
// The shared cyclomatic count the cyclomatic finding reports.
|
|
66
89
|
cyclomatic: number;
|
|
67
|
-
functionBody: string;
|
|
68
90
|
}
|
|
69
91
|
|
|
70
|
-
//
|
|
71
|
-
//
|
|
72
|
-
//
|
|
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.
|
|
73
96
|
export interface BlockFindingArgs {
|
|
74
97
|
ruleId: string;
|
|
75
98
|
message: string;
|
|
@@ -79,26 +102,39 @@ export interface BlockFindingArgs {
|
|
|
79
102
|
pillar: Pillar;
|
|
80
103
|
}
|
|
81
104
|
|
|
82
|
-
//
|
|
83
|
-
//
|
|
84
|
-
// 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.
|
|
85
110
|
export interface BlockFindingWithMetadataArgs extends BlockFindingArgs {
|
|
86
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;
|
|
87
114
|
}
|
|
88
115
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
+
*/
|
|
93
123
|
export function blockFinding(args: BlockFindingArgs): Finding {
|
|
94
124
|
const endLine = args.block.startLine + args.block.lineCount - 1;
|
|
95
|
-
|
|
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 }) });
|
|
96
127
|
}
|
|
97
128
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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
|
+
*/
|
|
101
136
|
export function blockFindingWithMetadata(args: BlockFindingWithMetadataArgs): Finding {
|
|
137
|
+
const remediation = args.remediation ?? TEST_QUALITY_ADVICE.get(args.ruleId);
|
|
102
138
|
return makeFinding({
|
|
103
139
|
ruleId: args.ruleId,
|
|
104
140
|
message: args.message,
|
|
@@ -109,12 +145,20 @@ export function blockFindingWithMetadata(args: BlockFindingWithMetadataArgs): Fi
|
|
|
109
145
|
pillar: args.pillar,
|
|
110
146
|
confidence: "medium",
|
|
111
147
|
symbol: args.block.name,
|
|
148
|
+
...(remediation === undefined ? {} : { remediation }),
|
|
112
149
|
metadata: args.metadata,
|
|
113
150
|
});
|
|
114
151
|
}
|
|
115
152
|
|
|
116
|
-
|
|
117
|
-
|
|
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
|
+
*/
|
|
118
162
|
export function blockRuleContext(file: SourceFile, block: FunctionBlock, config: Config, findings: Finding[]): BlockRuleContext {
|
|
119
163
|
// A regex-only caller has no shared syntax node, so it receives the neutral base measurement.
|
|
120
164
|
const sharedComplexityMetrics = block.complexityMetrics ?? baseComplexityMetrics();
|
|
@@ -125,247 +169,180 @@ export function blockRuleContext(file: SourceFile, block: FunctionBlock, config:
|
|
|
125
169
|
findings,
|
|
126
170
|
complexityMetrics: sharedComplexityMetrics,
|
|
127
171
|
cyclomatic: sharedComplexityMetrics.cyclomatic,
|
|
128
|
-
functionBody: functionBodyContent(block.codeBody),
|
|
129
172
|
};
|
|
130
173
|
}
|
|
131
174
|
|
|
132
|
-
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
*
|
|
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.
|
|
136
180
|
*/
|
|
137
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 {
|
|
138
195
|
pushFunctionLengthFinding(context);
|
|
139
196
|
pushParameterCountFinding(context);
|
|
140
197
|
pushCyclomaticFinding(context);
|
|
141
|
-
pushCognitiveFinding(context);
|
|
142
|
-
pushGenericFunctionFinding(context);
|
|
143
|
-
pushMissingFunctionDocFinding(context);
|
|
144
|
-
pushEmptyFunctionFinding(context);
|
|
145
|
-
pushUnusedParameterFindings(context);
|
|
146
|
-
pushRedundantVariableFindings(context);
|
|
147
|
-
pushUselessReturnFindings(context);
|
|
148
198
|
}
|
|
149
199
|
|
|
150
|
-
|
|
151
|
-
|
|
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
|
+
*/
|
|
152
206
|
function pushFunctionLengthFinding(context: BlockRuleContext): void {
|
|
153
207
|
const functionLengthThreshold = threshold(context.config, "size.function-length", 200);
|
|
154
|
-
|
|
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);
|
|
155
211
|
context.findings.push(blockFindingWithMetadata({
|
|
156
212
|
ruleId: "size.function-length",
|
|
157
|
-
message: `Function \`${context.block.name}\` has ${context.block.
|
|
213
|
+
message: `Function \`${context.block.name}\` has ${context.block.codeLineCount} lines, above the threshold of ${functionLengthThreshold}.`,
|
|
158
214
|
file: context.file,
|
|
159
215
|
block: context.block,
|
|
160
|
-
severity:
|
|
216
|
+
severity: band.severity,
|
|
161
217
|
pillar: "size",
|
|
162
|
-
|
|
218
|
+
remediation: band.remediation,
|
|
219
|
+
metadata: { lines: context.block.codeLineCount, threshold: functionLengthThreshold, limitBand: band.limitBand },
|
|
163
220
|
}));
|
|
164
221
|
}
|
|
165
222
|
}
|
|
166
223
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
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
|
+
*/
|
|
170
231
|
function pushParameterCountFinding(context: BlockRuleContext): void {
|
|
171
232
|
const params = context.block.parameterCount ?? context.block.params.split(",").map((value) => value.trim()).filter(Boolean).length;
|
|
172
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.
|
|
173
235
|
if (params > parameterCountThreshold) {
|
|
236
|
+
const band = bandedFields(params, parameterCountThreshold, ruleSeverity(context.config, "size.parameter-count", "warning"), LOWER_BAND_PARAMETER, GROUP_PARAMETERS);
|
|
174
237
|
context.findings.push(blockFindingWithMetadata({
|
|
175
238
|
ruleId: "size.parameter-count",
|
|
176
239
|
message: `Function \`${context.block.name}\` declares ${params} parameters.`,
|
|
177
240
|
file: context.file,
|
|
178
241
|
block: context.block,
|
|
179
|
-
severity:
|
|
242
|
+
severity: band.severity,
|
|
180
243
|
pillar: "size",
|
|
181
|
-
|
|
244
|
+
remediation: band.remediation,
|
|
245
|
+
metadata: { parameters: params, threshold: parameterCountThreshold, limitBand: band.limitBand },
|
|
182
246
|
}));
|
|
183
247
|
}
|
|
184
248
|
}
|
|
185
249
|
|
|
186
|
-
|
|
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
|
+
*/
|
|
187
257
|
function pushCyclomaticFinding(context: BlockRuleContext): void {
|
|
188
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.
|
|
189
260
|
if (context.cyclomatic > cyclomaticThreshold) {
|
|
261
|
+
const band = bandedFields(context.cyclomatic, cyclomaticThreshold, ruleSeverity(context.config, "complexity.cyclomatic", "warning"), LOWER_BAND_FUNCTION, SIMPLIFY_PATH);
|
|
190
262
|
context.findings.push(blockFindingWithMetadata({
|
|
191
263
|
ruleId: "complexity.cyclomatic",
|
|
192
264
|
message: `Function \`${context.block.name}\` has cyclomatic complexity ${context.cyclomatic}.`,
|
|
193
265
|
file: context.file,
|
|
194
266
|
block: context.block,
|
|
195
|
-
severity:
|
|
267
|
+
severity: band.severity,
|
|
196
268
|
pillar: "complexity",
|
|
197
|
-
|
|
269
|
+
remediation: band.remediation,
|
|
270
|
+
metadata: { complexity: context.cyclomatic, threshold: cyclomaticThreshold, breakdown: context.complexityMetrics.breakdown, limitBand: band.limitBand },
|
|
198
271
|
}));
|
|
199
272
|
}
|
|
200
273
|
}
|
|
201
274
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
ruleId: "complexity.cognitive",
|
|
209
|
-
message: `Function \`${context.block.name}\` has cognitive complexity ${cognitive}.`,
|
|
210
|
-
file: context.file,
|
|
211
|
-
block: context.block,
|
|
212
|
-
severity: ruleSeverity(context.config, "complexity.cognitive", "warning"),
|
|
213
|
-
pillar: "complexity",
|
|
214
|
-
metadata: { complexity: cognitive, threshold: cognitiveThreshold, breakdown: context.complexityMetrics.breakdown },
|
|
215
|
-
}));
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
// Names like `process`, `handle`, `run` from `config.bannedGenericNames`. The list is user-configurable;
|
|
220
|
-
// the rule body itself just consults the config. Reports `naming.generic-function`.
|
|
221
|
-
function pushGenericFunctionFinding(context: BlockRuleContext): void {
|
|
222
|
-
if (isGenericName(context.block.name, context.config.bannedGenericNames)) {
|
|
223
|
-
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" }));
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/*
|
|
228
|
-
* Every non-test function must carry a leading comment. Test blocks are exempted because their
|
|
229
|
-
* `test("name", …)` description already documents intent. Reports
|
|
230
|
-
* `docs.missing-exported-function-doc` (warning, higher cost of omission on the public API
|
|
231
|
-
* 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.
|
|
232
281
|
*/
|
|
233
282
|
function pushMissingFunctionDocFinding(context: BlockRuleContext): void {
|
|
234
283
|
if (context.block.isTest || context.block.hasLeadingComment) {
|
|
235
284
|
return;
|
|
236
285
|
}
|
|
237
|
-
const
|
|
238
|
-
const
|
|
239
|
-
const
|
|
240
|
-
context.findings.push(blockFinding({ ruleId, message:
|
|
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" }));
|
|
241
290
|
}
|
|
242
291
|
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
// Empty test doubles can be required by external interfaces when the body carries a rationale.
|
|
258
|
-
function isDocumentedEmptyTestDouble(context: BlockRuleContext): boolean {
|
|
259
|
-
return isTestOrFixturePath(context.file.displayPath) && hasEmptyTestDoubleRationale(context.block.body);
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
// Test and fixture paths are the only places where empty protocol stubs are normal.
|
|
263
|
-
function isTestOrFixturePath(path: string): boolean {
|
|
264
|
-
return /(?:^|\/)(?:__tests__|tests?|spec|__fixtures__|fixtures?|testdata)\//.test(path) || /\.(?:test|spec)\.[cm]?[tj]sx?$/.test(path);
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
// Requires an explicit no-op/stub/fake rationale so real empty implementations still surface.
|
|
268
|
-
function hasEmptyTestDoubleRationale(source: string): boolean {
|
|
269
|
-
return /(?:\/\/|\/\*)/.test(source) && /\b(?:intentional no-op|test double|stub|fake|interface contract)\b/i.test(source);
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
// `_`-prefixed parameters are exempted (the standard "intentionally unused" convention).
|
|
273
|
-
// Reports `waste.unused-parameter` for parameter names that never appear in the callable body.
|
|
274
|
-
function pushUnusedParameterFindings(context: BlockRuleContext): void {
|
|
275
|
-
if (isBodyLessDeclaration(context.block) || isDeclarationFile(context.file)) {
|
|
276
|
-
return;
|
|
277
|
-
}
|
|
278
|
-
for (const parameter of parameterNames(context.block.params)) {
|
|
279
|
-
if (!isUnusedParameter(context, parameter.name)) {
|
|
280
|
-
continue;
|
|
281
|
-
}
|
|
282
|
-
context.findings.push(unusedParameterFinding(context, parameter.name));
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
// Skips interface methods, type-literal methods, function-type aliases, abstract members, and
|
|
287
|
-
// overload signatures - all of which look like a function declaration ending in `;` rather than `{`,
|
|
288
|
-
// and have no real body to check for emptiness or parameter usage.
|
|
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
|
-
}
|
|
295
|
-
for (const rawLine of block.codeBody.split("\n")) {
|
|
296
|
-
const trimmed = rawLine.trim();
|
|
297
|
-
if (trimmed === "" || trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
|
|
298
|
-
continue;
|
|
299
|
-
}
|
|
300
|
-
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(", ")}`);
|
|
301
305
|
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
// TypeScript `.d.ts` files only declare types; every callable in them is a signature, never an
|
|
306
|
-
// implementation, so the empty/unused-parameter rules are categorically misapplied there.
|
|
307
|
-
function isDeclarationFile(file: SourceFile): boolean {
|
|
308
|
-
return file.displayPath.endsWith(".d.ts");
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
// Word-boundary regex against the masked function body. The body is masked so a parameter mentioned
|
|
312
|
-
// only in a string literal would still count as unused - that matches the intent of the rule. A
|
|
313
|
-
// loose `${...param...}` regex over the raw body catches parameters used only inside template
|
|
314
|
-
// interpolations, which the mask would otherwise hide.
|
|
315
|
-
function isUnusedParameter(context: BlockRuleContext, parameterName: string): boolean {
|
|
316
|
-
if (parameterName.startsWith("_")) {
|
|
317
|
-
return false;
|
|
306
|
+
if (block.callableNode !== undefined && isCallableReturningValue(block.callableNode)) {
|
|
307
|
+
asks.push("describe the return value");
|
|
318
308
|
}
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
return false;
|
|
309
|
+
if (/\bthrow\b/.test(block.codeBody)) {
|
|
310
|
+
asks.push("say when it throws");
|
|
322
311
|
}
|
|
323
|
-
|
|
312
|
+
const suffix = asks.length > 0 ? `; ${asks.join("; ")}` : "";
|
|
313
|
+
return `${audience} function \`${block.name}\` is missing a leading maintainer comment${suffix}.`;
|
|
324
314
|
}
|
|
325
315
|
|
|
326
|
-
|
|
327
|
-
*
|
|
328
|
-
*
|
|
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.
|
|
329
321
|
*/
|
|
330
|
-
function
|
|
331
|
-
return
|
|
332
|
-
ruleId: "waste.unused-parameter",
|
|
333
|
-
message: `Parameter \`${parameterName}\` does not appear to be used.`,
|
|
334
|
-
filePath: context.file.displayPath,
|
|
335
|
-
line: context.block.startLine,
|
|
336
|
-
severity: "advisory",
|
|
337
|
-
pillar: "maintainability",
|
|
338
|
-
confidence: "medium",
|
|
339
|
-
symbol: context.block.name,
|
|
340
|
-
remediation: "Remove the parameter or prefix it with _ if it is intentionally unused.",
|
|
341
|
-
metadata: { parameter: parameterName },
|
|
342
|
-
});
|
|
322
|
+
function isEveryCallablePublicMethod(context: BlockRuleContext): boolean {
|
|
323
|
+
return isTagRuleEveryCallable(context.config) && context.block.callableNode !== undefined && isPublicExportedClassMethod(context.block.callableNode);
|
|
343
324
|
}
|
|
344
325
|
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
severity: "advisory",
|
|
356
|
-
pillar: "maintainability",
|
|
357
|
-
confidence: "medium",
|
|
358
|
-
symbol: redundant.name,
|
|
359
|
-
remediation: "Return the expression directly.",
|
|
360
|
-
metadata: { variable: redundant.name },
|
|
361
|
-
}),
|
|
362
|
-
);
|
|
363
|
-
}
|
|
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);
|
|
364
336
|
}
|
|
365
337
|
|
|
366
|
-
|
|
367
|
-
|
|
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
|
+
*/
|
|
368
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.
|
|
369
346
|
for (const lineOffset of terminalBareReturnLines(context.block.codeBody)) {
|
|
370
347
|
context.findings.push(
|
|
371
348
|
makeFinding({
|
|
@@ -383,22 +360,16 @@ function pushUselessReturnFindings(context: BlockRuleContext): void {
|
|
|
383
360
|
}
|
|
384
361
|
}
|
|
385
362
|
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
.trim();
|
|
393
|
-
return body === "";
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
// Two shapes: block-body callables return the text between the outermost `{` and `}`; expression
|
|
397
|
-
// arrow functions fall back to the slice after `=>`. The trailing-`;` strip keeps the arrow
|
|
398
|
-
// 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
|
+
*/
|
|
399
369
|
export function functionBodyContent(source: string): string {
|
|
400
|
-
const start = source
|
|
370
|
+
const start = functionBlockBrace(source);
|
|
401
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.
|
|
402
373
|
if (start === -1 || end <= start) {
|
|
403
374
|
const arrow = source.indexOf("=>");
|
|
404
375
|
return arrow === -1 ? "" : source.slice(arrow + 2).replace(/;?\s*$/, "");
|
|
@@ -406,64 +377,158 @@ export function functionBodyContent(source: string): string {
|
|
|
406
377
|
return source.slice(start + 1, end);
|
|
407
378
|
}
|
|
408
379
|
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
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
|
+
*/
|
|
412
404
|
function terminalBareReturnLines(source: string): number[] {
|
|
413
405
|
const lines = source.split(/\r?\n/);
|
|
414
406
|
let current = lines.length - 1;
|
|
415
407
|
while (current >= 0) {
|
|
416
408
|
const trimmed = lines[current]?.trim() ?? "";
|
|
409
|
+
// Closing braces and blank lines can follow the last statement without making it nonterminal.
|
|
417
410
|
if (trimmed === "" || trimmed === "}") {
|
|
418
411
|
current -= 1;
|
|
419
412
|
continue;
|
|
420
413
|
}
|
|
421
|
-
return /^return\s*;?$/.test(trimmed) ? [current] : [];
|
|
414
|
+
return /^return\s*;?$/.test(trimmed) && !isOnlyStatementOfCatch(lines, current) ? [current] : [];
|
|
422
415
|
}
|
|
423
416
|
return [];
|
|
424
417
|
}
|
|
425
418
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
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;
|
|
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);
|
|
434
441
|
}
|
|
435
|
-
return
|
|
442
|
+
return false;
|
|
436
443
|
}
|
|
437
444
|
|
|
438
|
-
|
|
439
|
-
|
|
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
|
+
*/
|
|
440
452
|
function isTestInvocationLine(line: string): boolean {
|
|
441
|
-
return /^\s*(?:test|it)\s*\(/.test(line);
|
|
453
|
+
return /^\s*(?:void\s+)?(?:test|it)\s*\(/.test(line);
|
|
442
454
|
}
|
|
443
455
|
|
|
444
|
-
|
|
445
|
-
|
|
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
|
+
*/
|
|
446
465
|
export function functionBlocks(source: string, codeSource = source, parsed?: ParsedScript): FunctionBlock[] {
|
|
447
|
-
const scan
|
|
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));
|
|
487
|
+
}
|
|
488
|
+
|
|
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 {
|
|
448
500
|
lines: source.split(/\r?\n/),
|
|
449
501
|
codeLines: codeSource.split(/\r?\n/),
|
|
502
|
+
isCodeLine: codeLineFlags(source, parsed),
|
|
450
503
|
patterns: FUNCTION_BLOCK_PATTERNS,
|
|
451
504
|
reExportedNames: collectReExportedNames(codeSource),
|
|
452
505
|
};
|
|
453
|
-
|
|
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> {
|
|
454
517
|
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
518
|
for (const point of matchPoints) {
|
|
457
519
|
// A missing node means a caller requested the legacy regex discovery path without reparsing.
|
|
458
520
|
if (point.callableNode) {
|
|
459
521
|
ownedCallableNodes.add(point.callableNode);
|
|
460
522
|
}
|
|
461
523
|
}
|
|
462
|
-
|
|
463
|
-
|
|
524
|
+
for (const point of parsed ? measuredOnlyCallablePoints(parsed) : []) {
|
|
525
|
+
ownedCallableNodes.add(point.callableNode);
|
|
526
|
+
}
|
|
527
|
+
return ownedCallableNodes;
|
|
464
528
|
}
|
|
465
529
|
|
|
466
530
|
// One callable hit used to build the block that report rules inspect.
|
|
531
|
+
//
|
|
467
532
|
// Parsed hits carry their node and exact range; legacy span probes carry only text coordinates.
|
|
468
533
|
// Empty optional fields mean the caller deliberately supplied no shared parse.
|
|
469
534
|
interface BlockMatchPoint {
|
|
@@ -481,32 +546,28 @@ interface BlockMatchPoint {
|
|
|
481
546
|
isDirectlyExported?: boolean;
|
|
482
547
|
isExplicitlyPublic?: boolean;
|
|
483
548
|
isModuleScoped?: boolean;
|
|
549
|
+
// AST-known `override` modifier; regex points leave it absent, so their names stay reportable.
|
|
550
|
+
isOverride?: boolean;
|
|
484
551
|
callableNode?: import("typescript").Node;
|
|
485
552
|
}
|
|
486
553
|
|
|
487
|
-
|
|
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
|
+
*/
|
|
488
562
|
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
563
|
if (parsed) {
|
|
491
|
-
return callableMatchPoints(parsed).map(
|
|
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
|
-
}));
|
|
564
|
+
return callableMatchPoints(parsed).map(blockMatchPoint);
|
|
504
565
|
}
|
|
505
566
|
const points: BlockMatchPoint[] = [];
|
|
506
567
|
// Span-only utilities still use the legacy masked-line inventory without triggering a parse.
|
|
507
568
|
scan.codeLines.forEach((line, index) => {
|
|
508
569
|
const match = functionBlockMatch(scan, line, index);
|
|
509
|
-
//
|
|
570
|
+
// A legacy hit carries text coordinates, so block construction estimates its end from the source.
|
|
510
571
|
if (match) {
|
|
511
572
|
points.push({ lineIndex: index, name: match[1] ?? "", params: match[2] ?? "" });
|
|
512
573
|
}
|
|
@@ -514,18 +575,35 @@ function matchPointsFor(scan: FunctionBlockScan, parsed: ParsedScript | undefine
|
|
|
514
575
|
return points;
|
|
515
576
|
}
|
|
516
577
|
|
|
517
|
-
|
|
518
|
-
*
|
|
519
|
-
* bar }` (the local name `foo` is recorded, not the renamed `bar`), and `export default foo`
|
|
520
|
-
* (bare-identifier form - `export default function ...` is matched via pattern 2 in
|
|
521
|
-
* functionBlockPatterns instead, then classified exported because the line itself starts with
|
|
522
|
-
* `export`). Re-export-from clauses (`export { foo } from "./other"`) are intentionally skipped
|
|
523
|
-
* via the negative lookahead: those names are not local declarations of this file, so promoting
|
|
524
|
-
* a same-named local to "exported" would emit a false missing-public-doc finding.
|
|
578
|
+
/**
|
|
579
|
+
* Converts a parsed callable match point into block builder input, preserving its declaration metadata and syntax node.
|
|
525
580
|
*
|
|
526
|
-
*
|
|
527
|
-
*
|
|
528
|
-
|
|
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
|
+
};
|
|
599
|
+
}
|
|
600
|
+
|
|
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.
|
|
604
|
+
*
|
|
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.
|
|
529
607
|
*/
|
|
530
608
|
function collectReExportedNames(codeSource: string): ReadonlySet<string> {
|
|
531
609
|
const names = new Set<string>();
|
|
@@ -537,6 +615,7 @@ function collectReExportedNames(codeSource: string): ReadonlySet<string> {
|
|
|
537
615
|
}
|
|
538
616
|
}
|
|
539
617
|
}
|
|
618
|
+
// A bare default export can make an earlier local declaration public.
|
|
540
619
|
for (const match of codeSource.matchAll(/^\s*export\s+default\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*;?\s*$/gm)) {
|
|
541
620
|
if (match[1]) {
|
|
542
621
|
names.add(match[1]);
|
|
@@ -545,32 +624,39 @@ function collectReExportedNames(codeSource: string): ReadonlySet<string> {
|
|
|
545
624
|
return names;
|
|
546
625
|
}
|
|
547
626
|
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
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
|
+
*/
|
|
554
633
|
function functionBlockPatterns(): RegExp[] {
|
|
555
634
|
return [
|
|
556
|
-
/^\s*(?:test|it)\s*\(\s*["'`]([^"'`]+)["'`]\s*,\s*(?:async\s*)?\(([^)]*)\)\s*=>/,
|
|
635
|
+
/^\s*(?:void\s+)?(?:test|it)\s*\(\s*["'`]([^"'`]+)["'`]\s*,\s*(?:async\s*)?\(([^)]*)\)\s*=>/,
|
|
557
636
|
/^\s*(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)/,
|
|
558
637
|
/^\s*(?:public|private|protected)?\s*(?:async\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)\s*[:{]/,
|
|
559
638
|
/^\s*(?:export\s+)?(?:const|let)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*=>/,
|
|
560
639
|
];
|
|
561
640
|
}
|
|
562
641
|
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
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
|
+
*/
|
|
566
650
|
function functionBlockMatch(scan: FunctionBlockScan, line: string, index: number): RegExpMatchArray | undefined {
|
|
567
651
|
const rawLine = scan.lines[index] ?? "";
|
|
652
|
+
// Try the supported callable forms in order so test registrations keep their own block role.
|
|
568
653
|
for (let patternIndex = 0; patternIndex < scan.patterns.length; patternIndex += 1) {
|
|
569
654
|
const pattern = scan.patterns[patternIndex];
|
|
570
655
|
if (!pattern) {
|
|
571
656
|
continue;
|
|
572
657
|
}
|
|
573
658
|
const match = functionPatternMatch(pattern, patternIndex, line, rawLine);
|
|
659
|
+
// The first supported match determines the callable shown to block rules.
|
|
574
660
|
if (match) {
|
|
575
661
|
return match;
|
|
576
662
|
}
|
|
@@ -578,23 +664,41 @@ function functionBlockMatch(scan: FunctionBlockScan, line: string, index: number
|
|
|
578
664
|
return undefined;
|
|
579
665
|
}
|
|
580
666
|
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
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
|
+
*/
|
|
584
677
|
function functionPatternMatch(pattern: RegExp, patternIndex: number, line: string, rawLine: string): RegExpMatchArray | undefined {
|
|
585
678
|
const candidate = patternIndex === 0 && isTestInvocationLine(line) ? rawLine : line;
|
|
586
679
|
const match = candidate.match(pattern);
|
|
680
|
+
// A missing name or control keyword cannot represent a callable in the scan.
|
|
587
681
|
if (!match?.[1] || isControlBlockName(match[1])) {
|
|
588
682
|
return undefined;
|
|
589
683
|
}
|
|
590
684
|
return match;
|
|
591
685
|
}
|
|
592
686
|
|
|
593
|
-
|
|
594
|
-
|
|
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
|
+
*/
|
|
595
696
|
function functionBlockFromPoint(scan: FunctionBlockScan, point: BlockMatchPoint, ownedCallableNodes: ReadonlySet<import("typescript").Node>): FunctionBlock {
|
|
596
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`.
|
|
597
700
|
const start = functionStartIndex(scan.lines, index);
|
|
701
|
+
const codeStart = Math.min(start, point.declarationLineIndex ?? start);
|
|
598
702
|
const end = point.endLineIndex ?? functionEndIndex(scan, index);
|
|
599
703
|
const body = scan.lines.slice(start, end + 1).join("\n");
|
|
600
704
|
const codeBody = scan.codeLines.slice(start, end + 1).join("\n");
|
|
@@ -606,32 +710,43 @@ function functionBlockFromPoint(scan: FunctionBlockScan, point: BlockMatchPoint,
|
|
|
606
710
|
params: point.params,
|
|
607
711
|
...(point.parameterCount === undefined ? {} : { parameterCount: point.parameterCount }),
|
|
608
712
|
...(point.hasBody === undefined ? {} : { hasBody: point.hasBody }),
|
|
713
|
+
...(point.callableNode === undefined ? {} : { callableNode: point.callableNode }),
|
|
714
|
+
...(point.isOverride === undefined ? {} : { isOverride: point.isOverride }),
|
|
609
715
|
...(sharedComplexityMetrics === undefined ? {} : { complexityMetrics: sharedComplexityMetrics }),
|
|
610
716
|
startLine: start + 1,
|
|
611
717
|
lineCount: end - start + 1,
|
|
718
|
+
codeLineCount: scan.isCodeLine.slice(codeStart, end + 1).filter(Boolean).length,
|
|
612
719
|
body,
|
|
613
720
|
codeBody,
|
|
614
721
|
isPublic: point.isExplicitlyPublic ?? /\bexport\b|\bpublic\b/.test(scan.codeLines.slice(start, index + 1).join("\n")),
|
|
615
722
|
isExported: (point.isDirectlyExported ?? /^\s*export\b/.test(scan.codeLines[index] ?? ""))
|
|
616
723
|
|| point.isModuleScoped !== false && scan.reExportedNames.has(point.name),
|
|
617
724
|
isTest: isTestInvocationLine(scan.codeLines[index] ?? ""),
|
|
618
|
-
// Look upward from the declaration, not the name: a split-line `export async function` header
|
|
619
|
-
//
|
|
620
|
-
hasLeadingComment:
|
|
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),
|
|
621
728
|
declarationLine: index + 1,
|
|
622
729
|
};
|
|
623
730
|
}
|
|
624
731
|
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
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
|
+
*/
|
|
628
739
|
function functionEndIndex(scan: FunctionBlockScan, index: number): number {
|
|
629
740
|
return expressionArrowEndIndex(scan.codeLines, index) ?? blockFunctionEndIndex(scan, index);
|
|
630
741
|
}
|
|
631
742
|
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
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
|
+
*/
|
|
635
750
|
function blockFunctionEndIndex(scan: FunctionBlockScan, index: number): number {
|
|
636
751
|
const state: FunctionBodyScanState = { depth: 0, hasSeenOpen: false };
|
|
637
752
|
let end = index;
|
|
@@ -640,6 +755,7 @@ function blockFunctionEndIndex(scan: FunctionBlockScan, index: number): number {
|
|
|
640
755
|
applyFunctionBodyCharacter(state, character);
|
|
641
756
|
}
|
|
642
757
|
end = current;
|
|
758
|
+
// Stop once the opened body closes so later functions cannot enter this block's findings.
|
|
643
759
|
if (isFunctionBodyClosed(state)) {
|
|
644
760
|
break;
|
|
645
761
|
}
|
|
@@ -647,9 +763,13 @@ function blockFunctionEndIndex(scan: FunctionBlockScan, index: number): number {
|
|
|
647
763
|
return end;
|
|
648
764
|
}
|
|
649
765
|
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
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
|
+
*/
|
|
653
773
|
function applyFunctionBodyCharacter(state: FunctionBodyScanState, character: string): void {
|
|
654
774
|
if (character === "{") {
|
|
655
775
|
state.depth += 1;
|
|
@@ -659,24 +779,33 @@ function applyFunctionBodyCharacter(state: FunctionBodyScanState, character: str
|
|
|
659
779
|
}
|
|
660
780
|
}
|
|
661
781
|
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
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
|
+
*/
|
|
665
788
|
function isFunctionBodyClosed(state: FunctionBodyScanState): boolean {
|
|
666
789
|
return state.hasSeenOpen && state.depth <= 0;
|
|
667
790
|
}
|
|
668
791
|
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
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
|
+
*/
|
|
672
799
|
function expressionArrowEndIndex(codeLines: string[], index: number): number | undefined {
|
|
673
800
|
const line = codeLines[index] ?? "";
|
|
674
801
|
const arrowIndex = line.indexOf("=>");
|
|
802
|
+
// These lines fall through to the caller's brace scan for a span estimate.
|
|
675
803
|
if (!isExpressionArrowLine(line, arrowIndex)) {
|
|
676
804
|
return undefined;
|
|
677
805
|
}
|
|
678
806
|
for (let current = index; current < codeLines.length; current += 1) {
|
|
679
807
|
const endIndex = expressionArrowEndStep(codeLines, line, arrowIndex, index, current);
|
|
808
|
+
// A terminator or following blank line sets the reported end; otherwise keep looking.
|
|
680
809
|
if (endIndex !== undefined) {
|
|
681
810
|
return endIndex;
|
|
682
811
|
}
|
|
@@ -684,17 +813,30 @@ function expressionArrowEndIndex(codeLines: string[], index: number): number | u
|
|
|
684
813
|
return index;
|
|
685
814
|
}
|
|
686
815
|
|
|
687
|
-
|
|
688
|
-
|
|
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
|
+
*/
|
|
689
823
|
function isExpressionArrowLine(line: string, arrowIndex: number): boolean {
|
|
690
824
|
return arrowIndex !== -1 && !line.slice(arrowIndex + 2).includes("{");
|
|
691
825
|
}
|
|
692
826
|
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
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
|
+
*/
|
|
696
837
|
function expressionArrowEndStep(codeLines: string[], line: string, arrowIndex: number, start: number, current: number): number | undefined {
|
|
697
838
|
const trimmed = (codeLines[current] ?? "").trim();
|
|
839
|
+
// Only the text after the arrow can end the span on the declaration line.
|
|
698
840
|
if (current === start) {
|
|
699
841
|
return line.slice(arrowIndex + 2).trim().endsWith(";") ? current : undefined;
|
|
700
842
|
}
|
|
@@ -704,16 +846,23 @@ function expressionArrowEndStep(codeLines: string[], line: string, arrowIndex: n
|
|
|
704
846
|
return trimmed.endsWith(";") ? current : undefined;
|
|
705
847
|
}
|
|
706
848
|
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
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
|
+
*/
|
|
710
855
|
function isControlBlockName(name: string): boolean {
|
|
711
856
|
return ["if", "for", "while", "switch", "catch"].includes(name);
|
|
712
857
|
}
|
|
713
858
|
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
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
|
+
*/
|
|
717
866
|
function functionStartIndex(lines: string[], index: number): number {
|
|
718
867
|
let start = index;
|
|
719
868
|
while (start > 0) {
|
|
@@ -724,47 +873,70 @@ function functionStartIndex(lines: string[], index: number): number {
|
|
|
724
873
|
}
|
|
725
874
|
break;
|
|
726
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
|
+
}
|
|
727
880
|
return start;
|
|
728
881
|
}
|
|
729
882
|
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
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
|
+
*/
|
|
733
889
|
function isFunctionPrefixLine(trimmedLine: string): boolean {
|
|
734
890
|
return trimmedLine.startsWith("@") || trimmedLine.startsWith("/**") || trimmedLine.startsWith("*") || trimmedLine === "";
|
|
735
891
|
}
|
|
736
892
|
|
|
737
|
-
//
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
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)) {
|
|
744
908
|
return true;
|
|
745
909
|
}
|
|
746
|
-
|
|
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)) {
|
|
747
912
|
return true;
|
|
748
913
|
}
|
|
749
|
-
|
|
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)) {
|
|
750
916
|
return true;
|
|
751
917
|
}
|
|
752
|
-
if (
|
|
918
|
+
if (/\.\s*should\s*\.\s*be\s*\.\s*(?:eql|equal|greaterThan|instanceOf)\s*\(/.test(maskedTestBody)) {
|
|
753
919
|
return true;
|
|
754
920
|
}
|
|
755
921
|
return false;
|
|
756
922
|
}
|
|
757
923
|
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
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
|
+
*/
|
|
761
931
|
export function setupLineCount(source: string): number {
|
|
762
932
|
let count = 0;
|
|
763
933
|
for (const line of functionBodyContent(source).split(/\r?\n/)) {
|
|
764
934
|
const trimmed = line.trim();
|
|
935
|
+
// Standalone block and callback closers add no setup work in the two recognized forms.
|
|
765
936
|
if (isIgnorableSetupLine(trimmed)) {
|
|
766
937
|
continue;
|
|
767
938
|
}
|
|
939
|
+
// The first recognized assertion marker ends this count, so later test work cannot inflate it.
|
|
768
940
|
if (hasAssertion(trimmed)) {
|
|
769
941
|
break;
|
|
770
942
|
}
|
|
@@ -773,8 +945,12 @@ export function setupLineCount(source: string): number {
|
|
|
773
945
|
return count;
|
|
774
946
|
}
|
|
775
947
|
|
|
776
|
-
|
|
777
|
-
|
|
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
|
+
*/
|
|
778
954
|
function isIgnorableSetupLine(trimmedLine: string): boolean {
|
|
779
955
|
return trimmedLine.length === 0 || trimmedLine === "});" || trimmedLine === "}";
|
|
780
956
|
}
|