@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.
Files changed (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
package/src/blocks.ts CHANGED
@@ -1,71 +1,98 @@
1
- // Function-block parsing + per-block rule pass (size, complexity, doc,
2
- // empty-function, unused-parameter, redundant-variable, useless-return) and the block-anchored
3
- // finding factories. Pulls the parser and the rules that operate on parsed blocks out of cli.ts.
4
- import { ruleSeverity, threshold } from "./config.ts";
5
- import { hasLeadingCommentBeforeLines } from "./comment-scanner.ts";
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 { escapeRegex, isGenericName, lineOffset } from "./findings-helpers.ts";
9
- import { countMatches } from "./text-scans.ts";
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
- // Parsed callable body shared by every block-level rule (size, complexity, naming, docs). The
13
- // `body` / `codeBody` split (raw text vs. comment-masked) lets rules choose between literal
14
- // inspection and code-only matching without re-running the masker.
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 when the function declaration line itself starts with `export`. Distinct from `isPublic`,
24
- // which also matches class `public` modifiers - exports are the top-level API surface, while a
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
- // Working state for the function-block parser. Patterns are precompiled once per file so each
35
- // callable detection doesn't re-instantiate the same RegExp objects. `reExportedNames` carries
36
- // the file-level scan of `export { foo }` / `export default foo` so a declaration like
37
- // `function foo() {}` later re-exported via `export { foo }` is still classified as exported
38
- // (the line-local `^export` check alone would miss this common pattern).
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
- // Tiny lexer for finding the closing brace of a callable. `hasSeenOpen` matters because the depth
49
- // counter would otherwise hit zero before the body ever opened (arrow functions with a default body).
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
- // Precomputed inputs for every block-level rule. Computing cyclomatic / functionBody once and
56
- // reusing the values keeps each rule's deterministic per-block work down to a single pattern test.
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
- // Input bundle for `blockFinding()`. The block reference replaces the explicit line: the builder
67
- // reads `block.startLine` and `block.name` so the stable finding anchor and symbol metadata stay
68
- // in sync with the parsed callable across every block-level rule.
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
- // `BlockFindingArgs` plus a rule-specific metadata payload. Used by rules that need to encode
79
- // numeric thresholds or measurements (size, complexity values) into the Finding so downstream
80
- // consumers can filter without re-running the analyzer.
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
- // Block-anchored finding factory: pulls line + symbol from the parsed callable so every
86
- // block-level rule reports against the same anchor. Default confidence is "high"; callers
87
- // needing metadata or lower confidence go through `blockFindingWithMetadata` to keep the
88
- // per-rule fingerprint shape stable.
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
- 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 });
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
- // Block-anchored variant that ships rule-specific metadata. Confidence defaults to "medium"
95
- // because metadata-carrying rules (e.g. test-quality magic-number) report measurements rather than
96
- // definitive defects; the metadata payload is part of each rule's stable fingerprint contract.
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
- // Computes cyclomatic and function-body once and threads them through the per-block rule pipeline.
113
- // Pre-computing here keeps each rule's per-block work to a single threshold comparison; the
114
- // resulting struct is part of the stable rule-context contract every per-block helper consumes.
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
- cyclomatic: countMatches(block.codeBody, /\b(if|else if|switch|case|for|while|catch)\b|\?|&&|\|\|/g) + 1,
122
- functionBody: functionBodyContent(block.codeBody),
170
+ complexityMetrics: sharedComplexityMetrics,
171
+ cyclomatic: sharedComplexityMetrics.cyclomatic,
123
172
  };
124
173
  }
125
174
 
126
- /*
127
- * Per-block rule sequence. The ordering is the stable baseline contract - every block emits its
128
- * findings in this exact deterministic order, so reshuffling the call list churns fingerprints
129
- * even when no rule changes.
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
- // Default threshold 200, default severity `warning` - functions past that length are usually a
145
- // maintenance signal, not a stylistic preference. Reports `size.function-length` when the block exceeds the limit.
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
- if (context.block.lineCount > functionLengthThreshold) {
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.lineCount} lines, above the threshold of ${functionLengthThreshold}.`,
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: ruleSeverity(context.config, "size.function-length", "warning"),
216
+ severity: band.severity,
155
217
  pillar: "size",
156
- metadata: { lines: context.block.lineCount, threshold: functionLengthThreshold },
218
+ remediation: band.remediation,
219
+ metadata: { lines: context.block.codeLineCount, threshold: functionLengthThreshold, limitBand: band.limitBand },
157
220
  }));
158
221
  }
159
222
  }
160
223
 
161
- // Default threshold 7. Comma-counts on `block.params` rather than parsing because the parser
162
- // already validated the signature shape upstream. Reports `size.parameter-count` when exceeded.
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: ruleSeverity(context.config, "size.parameter-count", "warning"),
242
+ severity: band.severity,
173
243
  pillar: "size",
174
- metadata: { parameters: params, threshold: parameterCountThreshold },
244
+ remediation: band.remediation,
245
+ metadata: { parameters: params, threshold: parameterCountThreshold, limitBand: band.limitBand },
175
246
  }));
176
247
  }
177
248
  }
178
249
 
179
- // Default threshold 15. Counts conditional keywords + boolean operators in the code body - see
180
- // `blockRuleContext` for the pre-computed value. Reports `complexity.cyclomatic` when exceeded.
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: ruleSeverity(context.config, "complexity.cyclomatic", "warning"),
267
+ severity: band.severity,
190
268
  pillar: "complexity",
191
- metadata: { complexity: context.cyclomatic, threshold: cyclomaticThreshold },
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
- // Default threshold 15. Cognitive complexity is cyclomatic + max nesting depth - captures the
197
- // "deeply nested" intuition pure cyclomatic misses. Reports `complexity.cognitive` when exceeded.
198
- function pushCognitiveFinding(context: BlockRuleContext): void {
199
- const cognitive = context.cyclomatic + maxNestingDepth(context.block.codeBody);
200
- const cognitiveThreshold = threshold(context.config, "complexity.cognitive", 15);
201
- if (cognitive > cognitiveThreshold) {
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 ruleId = context.block.isExported ? "docs.missing-exported-function-doc" : "docs.missing-internal-function-doc";
233
- const severity = context.block.isExported ? "warning" : "advisory";
234
- const audience = context.block.isExported ? "exported" : "internal";
235
- context.findings.push(blockFinding({ ruleId, message: `${audience === "exported" ? "Exported" : "Internal"} function \`${context.block.name}\` is missing a leading maintainer comment.`, file: context.file, block: context.block, severity, pillar: "documentation" }));
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
- // Empty test doubles can be required by external interfaces when the body carries a rationale.
253
- function isDocumentedEmptyTestDouble(context: BlockRuleContext): boolean {
254
- return isTestOrFixturePath(context.file.displayPath) && hasEmptyTestDoubleRationale(context.block.body);
255
- }
256
-
257
- // Test and fixture paths are the only places where empty protocol stubs are normal.
258
- function isTestOrFixturePath(path: string): boolean {
259
- return /(?:^|\/)(?:__tests__|tests?|spec|__fixtures__|fixtures?|testdata)\//.test(path) || /\.(?:test|spec)\.[cm]?[tj]sx?$/.test(path);
260
- }
261
-
262
- // Requires an explicit no-op/stub/fake rationale so real empty implementations still surface.
263
- function hasEmptyTestDoubleRationale(source: string): boolean {
264
- return /(?:\/\/|\/\*)/.test(source) && /\b(?:intentional no-op|test double|stub|fake|interface contract)\b/i.test(source);
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
- return false;
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
- const escaped = escapeRegex(parameterName);
310
- if (new RegExp(`\\b${escaped}\\b`).test(context.functionBody)) {
311
- return false;
309
+ if (/\bthrow\b/.test(block.codeBody)) {
310
+ asks.push("say when it throws");
312
311
  }
313
- return !new RegExp(`\\$\\{[^}]*\\b${escaped}\\b[^}]*\\}`).test(context.block.body);
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
- * Stable `waste.unused-parameter` finding shape. `block.startLine` is the anchor so the fingerprint
318
- * stays at the callable's declaration line, not at the parameter's column position.
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 unusedParameterFinding(context: BlockRuleContext, parameterName: string): Finding {
321
- return makeFinding({
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
- // Targets `const x = expr; return x;` patterns. The detector walks the function source once and
336
- // reports each variable whose only use is the trailing return as `waste.redundant-variable`.
337
- function pushRedundantVariableFindings(context: BlockRuleContext): void {
338
- for (const redundant of redundantVariableReturns(context.block.codeBody)) {
339
- context.findings.push(
340
- makeFinding({
341
- ruleId: "waste.redundant-variable",
342
- message: `Variable \`${redundant.name}\` is returned immediately after assignment.`,
343
- filePath: context.file.displayPath,
344
- line: context.block.startLine + redundant.lineOffset,
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
- // Caller adds the block's start line to the relative offset so the finding anchors at the actual
357
- // trailing statement. Reports `waste.useless-return` when the final statement is a redundant bare exit.
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
- // Strips line and block comments before measuring - a body containing only documentation is still
377
- // considered empty for the `waste.empty-function` check, since no executable statements run.
378
- function isEmptyFunctionBody(source: string): boolean {
379
- const body = functionBodyContent(source)
380
- .replace(/\/\/.*$/gm, "")
381
- .replace(/\/\*[\s\S]*?\*\//g, "")
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.indexOf("{");
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
- // Walks upward past blank lines and the closing `}` looking for a final `return;`. Returns the
400
- // line offset of that statement (zero-based) or an empty list if the last real line is anything
401
- // else - used by `waste.redundant-variable` so the finding anchors on the actual statement.
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
- // Splits on `,` then strips visibility modifiers, `...rest`, default values, and type annotations
417
- // in that order. Final filter rejects entries whose name isn't a plain identifier - destructured
418
- // parameters land in that bucket and are intentionally invisible to per-parameter rules.
419
- export function parameterNames(params: string): Array<{ name: string; raw: string }> {
420
- return params
421
- .split(",")
422
- .map((parameter) => parameter.trim())
423
- .filter(Boolean)
424
- .map((raw) => {
425
- const stripped = raw.replace(/^(?:public|private|protected|readonly)\s+/, "").replace(/^\.\.\./, "");
426
- const name = stripped.split(/[?:=]/)[0]?.trim() ?? "";
427
- return { name, raw: stripped };
428
- })
429
- .filter((parameter) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(parameter.name));
430
- }
431
-
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 Math.max(0, maxDepth - 1);
442
+ return false;
458
443
  }
459
444
 
460
- // Matches `test("…", …)` and `it("…", …)` openers. Used both by the function-block parser to
461
- // pick the right pattern and by setup detection to skip the test wrapper line itself.
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
- // Top-level driver: precompiles patterns once, then walks the masked code lines so commented-out
467
- // declarations don't fire. The two-source split (`source` / `codeSource`) keeps raw line text
468
- // available for body extraction while preserving stable, comment-masked matching.
469
- export function functionBlocks(source: string, codeSource = source): FunctionBlock[] {
470
- const scan: FunctionBlockScan = {
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
- const blocks: FunctionBlock[] = [];
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
- if (!match) {
480
- return;
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 blocks;
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
- * File-level scan for re-exported local declarations. Matches `export { foo }`, `export { foo as
489
- * bar }` (the local name `foo` is recorded, not the renamed `bar`), and `export default foo`
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
- * Operates on the masked codeSource so `export { foo }` inside a string literal or comment is
497
- * skipped. Multi-line export blocks work because `[^}]+` spans newlines, and the lookahead
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
- // Four callable shapes in the order `functionBlockMatch` tries them: `test()` / `it()` bodies,
519
- // `function` declarations, class methods, and arrow assignments. Pattern[0] is intentionally
520
- // first because test bodies must match before the generic arrow pattern claims them. Pattern[1]
521
- // accepts an optional `default` after `export` so `export default function foo() {}` parses into
522
- // a FunctionBlock - the CHANGELOG's exported-doc-rule contract advertises that shape and the
523
- // missing `default` token previously made those declarations invisible to every block-level rule.
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
- // Tries each compiled pattern in order and returns the first hit. The loop bails when a pattern
534
- // slot is missing (defensive guard for the precompiled list) and uses the patternIndex to let
535
- // `functionPatternMatch` pick raw vs. masked text per pattern.
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
- // Pattern[0] (`test`/`it`) needs the raw line because the test name lives inside a string
552
- // literal that the masker would otherwise blank out. Everything else runs against the masked
553
- // `line`. Filters out control-block keywords so `if(...) {` doesn't register as a callable.
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
- // Promotes a regex match into a `FunctionBlock`. `start` walks up to capture leading docblock /
564
- // decorator lines so size and documentation rules see the full declaration footprint; the
565
- // `isPublic` check scans that same range so `export` / `public` modifiers above the line count.
566
- function functionBlockFromMatch(scan: FunctionBlockScan, match: RegExpMatchArray, index: number): FunctionBlock {
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 end = functionEndIndex(scan, index);
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: match[1] ?? "",
573
- params: match[2] ?? "",
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] ?? "") || scan.reExportedNames.has(match[1] ?? ""),
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
- hasLeadingComment: hasLeadingCommentBeforeLines(scan.lines, index + 1),
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
- // Two callable shapes share one entry point: single-expression arrows return early via
587
- // `expressionArrowEndIndex`, everything else falls into the brace-depth walker. Returning the
588
- // wrong end index would slice the wrong body and silently corrupt every per-block rule's input.
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
- // Brace-depth walker over masked code lines. Operates on `codeLines` so braces inside strings or
594
- // comments don't disturb the depth counter - the masker preserves brace positions in real code
595
- // and neutralises them everywhere else, keeping the body slice stable.
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
- // Per-character transition for the brace-depth walker. Setting `hasSeenOpen` on `{` is the
612
- // invariant `isFunctionBodyClosed` relies on - without it, the walker would treat the
613
- // pre-open state (depth 0) as already closed.
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
- // Termination predicate for the brace-depth walker. Requires `hasSeenOpen` so the initial
624
- // pre-body state doesn't read as already closed - the depth counter is only meaningful after the
625
- // first `{`.
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
- // Returns the line index where a single-expression arrow body terminates. Detection bails when
631
- // the line contains a `{` after `=>` (a block-bodied arrow); otherwise walks forward until a `;`
632
- // closes the expression or a blank line ends it.
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
- // `=>` exists and no `{` follows it - that means the body is a bare expression, not a block.
649
- // The distinction matters because expression bodies need a different end-of-block strategy.
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
- // One step of the arrow-expression walker. On the declaration line itself, a trailing `;` closes
655
- // the body immediately. Otherwise: a blank line means we walked past the body (back up one
656
- // index), and a `;`-terminated line is the actual end. Returning undefined means keep walking.
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
- // `if (...) { … }`, `for (...)`, etc. all look like `<name>(` to the pattern walker. The fixed
669
- // exclusion list prevents control-flow blocks from being treated as callables and reported by
670
- // per-block rules.
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
- // Walks upward from the declaration line absorbing decorator (`@`), docblock (`/**`, `*`), and
676
- // blank lines so the function block includes its leading documentation. Stops at the first real
677
- // code line above - that boundary becomes the block's start line.
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
- // Predicate that decides whether `functionStartIndex` should keep walking upward. Decorators,
692
- // docblock openers, docblock body lines (`*`), and blank lines all belong to the declaration's
693
- // leading block; anything else marks the boundary.
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
- // Generic "is there any assertion at all" probe used by missing-assertion rules. Accepts standard
699
- // `assert(...)` / `assert.foo(...)` / `expect(...)` (including `expect.assertions()` / `expect.hasAssertions()`)
700
- // PLUS project-local helpers shaped like `assertFoo(...)`, `expectFoo(...)`, `fooCheck(...)`, and
701
- // promise-rejection patterns (`rejects.`, `doesNotReject(`). Custom helpers are common in mature
702
- // test suites and missing them produced false positives in M38 false-positive triage.
703
- export function hasAssertion(source: string): boolean {
704
- if (/\bassert(?:\.[A-Za-z]+|[A-Z][A-Za-z0-9_$]*)?\s*\(/.test(source)) {
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
- if (/\bexpect(?:\.(?:assertions|hasAssertions)|[A-Z][A-Za-z0-9_$]*)?\s*\(/.test(source)) {
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
- if (/\b[A-Za-z_$][A-Za-z0-9_$]*Check\s*\(/.test(source)) {
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 (/\.(?:rejects|resolves)\b/.test(source) || /\b(?:doesNotReject|rejects)\s*\(/.test(source)) {
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
- // Counts non-ignorable lines preceding the first assertion in a test body. Stops as soon as an
720
- // assertion appears, so the value never overshoots the actual prologue length. Used by
721
- // `docs.fixture-purpose-missing` to size test-setup fixtures.
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
- // Filter for `setupLineCount`. Blank lines plus the two closer shapes (`}` and `});`) shouldn't
738
- // inflate the count - those are syntax, not setup work.
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
  }