@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.
Files changed (77) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +49 -50
  4. package/SECURITY.md +18 -31
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -10
  8. package/docs/agent-hook.md +32 -35
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +160 -89
  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 -172
  15. package/docs/rules.md +126 -98
  16. package/package.json +10 -8
  17. package/src/analyser.ts +817 -323
  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 +62 -68
  22. package/src/blocks.ts +512 -336
  23. package/src/changed-regions.ts +380 -79
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +445 -436
  26. package/src/cli-program.ts +915 -172
  27. package/src/cli.ts +9 -3
  28. package/src/comment-rules.ts +236 -418
  29. package/src/comment-scanner.ts +339 -47
  30. package/src/complexity-metrics.ts +111 -35
  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 +751 -223
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +182 -54
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +493 -140
  40. package/src/doc-rules.ts +602 -126
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +134 -109
  43. package/src/findings.ts +47 -27
  44. package/src/fixture-purpose-rules.ts +194 -50
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +328 -121
  47. package/src/hook-contract.ts +681 -255
  48. package/src/init-config.ts +163 -118
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -468
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +32 -127
  54. package/src/parsed-script.ts +868 -314
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +86 -74
  57. package/src/project-config-rules.ts +324 -140
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +102 -38
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +821 -203
  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 +249 -55
  66. package/src/security-flow-rules.ts +791 -115
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +460 -387
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +378 -104
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +343 -253
  73. package/src/text-scans.ts +62 -11
  74. package/src/types.ts +220 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -163
  77. package/src/test-fixtures.ts +0 -671
@@ -1,9 +1,10 @@
1
- // Shared syntax-only parse boundary (ADR-012): each analysed script is parsed exactly once per
2
- // analysis run, and that one result feeds parse diagnostics, security-flow analysis, and AST
3
- // function discovery. Separate parse paths would triple parser cost and drift apart; this module
4
- // owns the parser, the script-kind mapping, and the AST callable enumeration consumed by the
5
- // block rules (and, downstream, complexity metrics and naming ownership).
1
+ // Shared syntax-only parse boundary (ADR-012): parses each analysed script at most once per run.
2
+ //
3
+ // Feeds parse diagnostics, security-flow analysis, docblock rules, and AST callable discovery from one syntax tree:
4
+ // - prevents triple parser overhead and drift between rule modules;
5
+ // - owns script-kind mapping, decorator masking, and callable enumeration consumed by block, complexity, and naming rules.
6
6
  import { createRequire } from "node:module";
7
+ import { commentRecords, isDividerComment, isFileOverviewComment } from "./comment-scanner.ts";
7
8
  import type { RunDiagnostic } from "./types.ts";
8
9
 
9
10
  // Loaded via createRequire because typescript ships as CommonJS; usage stays bounded to syntax
@@ -29,53 +30,15 @@ export interface ParsedScript {
29
30
  }
30
31
 
31
32
  /*
32
- * Stable owner categories attached to naming inventory rows. CLI users see these categories only
33
- * inside finding metadata, where they explain whether a casing comparison came from the module,
34
- * one callable, one interface, or one type-literal contract.
35
- */
36
- export type IdentifierOwnerKind = "module" | "function" | "interface" | "type-literal";
37
-
38
- /*
39
- * Deterministic syntax owner projected into naming diagnostics. The id contains source ranges or
40
- * lexical names, never paths or TypeScript object identities; ownerName is absent when the module
41
- * itself is the user-visible comparison boundary.
42
- */
43
- export interface IdentifierOwner {
44
- ownerId: string;
45
- ownerKind: IdentifierOwnerKind;
46
- ownerName?: string;
47
- }
48
-
49
- /*
50
- * One syntax-backed declaration row for the shared naming inventory. The row retains the existing
51
- * name and line presented to users, while owner fields let a later rule compare only declarations
52
- * that belong to the same reviewable surface.
53
- */
54
- export interface OwnedDeclarationPoint extends IdentifierOwner {
55
- name: string;
56
- line: number;
57
- }
58
-
59
- /*
60
- * The two non-parameter inventories collected during the shared callable walk. Keeping variable
61
- * declarations and contract fields separate preserves the existing acronym input order when the
62
- * analyser inserts callable parameters between them.
63
- */
64
- export interface DeclarationOwnershipPoints {
65
- variableDeclarations: OwnedDeclarationPoint[];
66
- contractFields: OwnedDeclarationPoint[];
67
- }
68
-
69
- /*
70
- * One cached projection of the shared syntax tree. Function discovery and naming ownership read
71
- * this same result, so enabling both rule families does not walk or parse the user's file twice.
33
+ * One cached projection of the shared syntax tree. Every block rule reads this same result, so no
34
+ * rule walks or parses the user's file twice.
72
35
  */
73
36
  interface ParsedSyntaxIndex {
74
37
  callablePoints: CallableMatchPoint[];
75
- declarationOwnership: DeclarationOwnershipPoints;
38
+ // Callables only the size and complexity rules measure; every other block rule reads `callablePoints` alone.
39
+ measuredOnlyPoints: CallableMatchPoint[];
76
40
  }
77
41
 
78
- const MODULE_IDENTIFIER_OWNER: IdentifierOwner = { ownerId: "module", ownerKind: "module" };
79
42
  const parsedSyntaxIndexes = new WeakMap<ParsedScript, ParsedSyntaxIndex>();
80
43
 
81
44
  // `createSourceFile` recovers from syntax errors and records them on an internal field; this
@@ -87,8 +50,12 @@ interface ParsedSourceFileWithDiagnostics extends TsSourceFile {
87
50
  // Test-visible parse counter backing the one-parse-per-script assertion; never drives behavior.
88
51
  let parseCount = 0;
89
52
 
90
- // Returns how many times the shared parser has run in this process; tests subtract before/after
91
- // snapshots to assert one parse per analysed script.
53
+ /**
54
+ * Reads how many times the shared parser has run in this process; tests subtract before/after
55
+ * snapshots to assert one parse per analysed script.
56
+ *
57
+ * @returns Total number of scripts parsed by `parseScript` in this process.
58
+ */
92
59
  export function parsedScriptParseCount(): number {
93
60
  return parseCount;
94
61
  }
@@ -96,10 +63,11 @@ export function parsedScriptParseCount(): number {
96
63
  /**
97
64
  * Parses one script into the shared boundary result. Non-script inputs return undefined so a
98
65
  * config or text file never parses; diagnostics always cover the whole file (never range-filtered).
66
+ * Each script input increments the process-wide parse count exposed by parsedScriptParseCount.
99
67
  *
100
68
  * @param file - display path plus the script flag from discovery; a false script flag skips parsing
101
69
  * @param source - decoded file text; empty script text produces a source file with no diagnostics
102
- * @returns shared parse result; undefined means the input was a config or text file
70
+ * @returns - shared parse result. No diagnostics means a clean parse. Undefined means the script flag was false.
103
71
  */
104
72
  export function parseScript(file: ParsedScriptInput, source: string): ParsedScript | undefined {
105
73
  // Config and text inputs do not enter the script parser, so callers receive no parse result.
@@ -118,8 +86,75 @@ export function parseScript(file: ParsedScriptInput, source: string): ParsedScri
118
86
  };
119
87
  }
120
88
 
121
- // Maps extensions onto the matching TypeScript parser mode so TSX/JSX syntax parses as syntax.
122
- // The single copy: source-text and security-flow used to carry one each.
89
+ /**
90
+ * Masks decorators with spaces while preserving line breaks and offsets, so decorator-only lines read as blank.
91
+ *
92
+ * @param text - the parsed source text, or a same-length masking of it such as the source with its comments blanked
93
+ * @param parsed - the shared parse of that source
94
+ * @returns Text with decorator characters replaced by spaces except for CR and LF.
95
+ */
96
+ export function maskDecorators(text: string, parsed: ParsedScript): string {
97
+ const characters = text.split("");
98
+ /**
99
+ * Visits a syntax node and its descendants, blanking decorator spans in the shared buffer to preserve source offsets.
100
+ *
101
+ * @param node - syntax node inspected for a decorator and traversed recursively
102
+ * @returns Nothing. Replaces decorator characters in the shared buffer with spaces while keeping line breaks.
103
+ */
104
+ const visit = (node: TsNode): void => {
105
+ // A decorator's span runs from its at sign to the end of its expression, arguments included.
106
+ if (node.kind === typescriptSyntax.SyntaxKind.Decorator) {
107
+ blankRange(characters, node.getStart(parsed.sourceFile), node.end);
108
+ }
109
+ node.forEachChild(visit);
110
+ };
111
+ parsed.sourceFile.forEachChild(visit);
112
+ return characters.join("");
113
+ }
114
+
115
+ /**
116
+ * Flags lines for the function-block, for-of body and module counts in FAMILY-CONTRACT section 12.
117
+ * Blank lines and comment-only lines do not count. With a parse, decorator-only lines do not count either.
118
+ * Nonblank string and template text outside those masked spans counts as code.
119
+ *
120
+ * @param source - decoded file text whose comment ranges and line boundaries determine the flags
121
+ * @param parsed - the shared parse of source; without it decorators are not recognised and count as code
122
+ * @returns - one flag per LF- or CRLF-delimited line in source order. Empty source returns one false flag.
123
+ */
124
+ export function codeLineFlags(source: string, parsed?: ParsedScript): boolean[] {
125
+ const characters = source.split("");
126
+ for (const comment of commentRecords(source)) {
127
+ blankRange(characters, comment.startIndex, comment.kind === "block" ? Math.min(source.length, comment.endIndex + 1) : comment.endIndex);
128
+ }
129
+ const withoutComments = characters.join("");
130
+ const code = parsed ? maskDecorators(withoutComments, parsed) : withoutComments;
131
+ return code.split(/\r?\n/).map((line) => line.trim() !== "");
132
+ }
133
+
134
+ /**
135
+ * Replaces non-newline characters in place with spaces across a half-open range.
136
+ * Preserves CR and LF so line numbers stay fixed for LF- and CRLF-delimited text.
137
+ *
138
+ * @param characters - mutable character array modified in place
139
+ * @param start - zero-based starting index, inclusive, where blanking begins
140
+ * @param end - zero-based ending index, exclusive, bounded by the array length
141
+ * @returns Nothing. Mutates `characters` in place with spaces from `start` up to `end`, leaving `\n` and `\r` intact.
142
+ */
143
+ function blankRange(characters: string[], start: number, end: number): void {
144
+ for (let index = start; index < end && index < characters.length; index += 1) {
145
+ if (characters[index] !== "\n" && characters[index] !== "\r") {
146
+ characters[index] = " ";
147
+ }
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Selects the TypeScript parser mode from `path`'s case-sensitive extension so JSX and TSX are parsed correctly.
153
+ * Recognises `.tsx`, `.jsx`, `.js`, `.mjs`, and `.cjs`; all other paths use TS mode.
154
+ *
155
+ * @param path - file path whose trailing extension selects the grammar mode
156
+ * @returns TypeScript `ScriptKind` (`TSX`, `JSX`, `JS`, or `TS`) matching the extension.
157
+ */
123
158
  export function scriptKindFor(path: string): import("typescript").ScriptKind {
124
159
  if (path.endsWith(".tsx")) {
125
160
  return typescriptSyntax.ScriptKind.TSX;
@@ -162,22 +197,15 @@ function summarizeParseErrors(file: ParsedScriptInput, sourceFile: TsSourceFile,
162
197
  }
163
198
 
164
199
  /*
165
- * One discovered callable declaration point: the zero-based line index where the legacy regex
166
- * scanner would have matched, the reported block name, raw parameter text, actual AST parameter
167
- * count, and the callable node used by later syntax metrics. The block parser turns points into
168
- * FunctionBlocks with the exact same start/end/body slicing it always used, so the retained
169
- * fingerprint invariant cannot move.
200
+ * One discovered callable match point projected from the shared syntax tree for block rules.
201
+ *
202
+ * Invariant: preserves the exact line anchor and slicing rules the block parser expects so existing finding fingerprints never move.
170
203
  */
171
- export interface CallableMatchPoint extends IdentifierOwner {
204
+ export interface CallableMatchPoint {
172
205
  lineIndex: number;
173
- // Zero-based first line of the declaration itself, modifiers included but leading documentation
174
- // excluded. Equals `lineIndex` for every single-line declaration; it moves earlier only when a
175
- // declaration splits its modifiers onto their own line, where the line above the name is
176
- // `export async function` rather than the docblock a reader can plainly see.
206
+ // Zero-based first line of the declaration (modifiers included, docs excluded) so split headers keep doc lookup intact.
177
207
  declarationLineIndex: number;
178
- // Zero-based line of the callable's final token. The block parser prefers this over its legacy
179
- // brace walk: a `{}` inside a multi-line parameter default would otherwise close the walk early
180
- // and slice an empty body.
208
+ // Zero-based line of the callable's final token, preferred over brace walking so `{}` in defaults cannot truncate bodies.
181
209
  endLineIndex: number;
182
210
  name: string;
183
211
  params: string;
@@ -192,35 +220,43 @@ export interface CallableMatchPoint extends IdentifierOwner {
192
220
  // signatures, and abstract or ambient members. The block rules use this instead of guessing
193
221
  // from text, because a multi-line signature reads like an implementation on its first line.
194
222
  hasBody: boolean;
223
+ // True only for a declaration carrying the `override` modifier: its base class chose the name.
224
+ isOverride: boolean;
195
225
  // Shared-parse node whose parameters and body belong to this stable analysed block.
196
226
  callableNode: TsNode;
197
227
  }
198
228
 
199
229
  /**
200
- * Enumerates callable declarations from the shared syntax tree: function declarations (including
201
- * generic and multi-line signatures the regex missed), class/object methods and constructors,
202
- * interface/type-literal method signatures, const/let arrow and function initializers (including
203
- * parenless single-argument arrows), and test/it callbacks. At most one point per source line is
204
- * returned (source order wins) - the legacy scanner's one-block-per-line invariant.
230
+ * Returns cached callable points, building the shared syntax index on first access. Ties go to the first point recorded on the line.
231
+ * Covers named functions, identifier-named methods and signatures, constructors, and identifier-bound const or let function values.
232
+ * Bare test and it calls need a literal title and a function callback. These callbacks take priority over other points on the same line.
205
233
  *
206
- * @param parsed Shared parse result for the script.
207
- * @returns Match points sorted by line, ready for the block parser.
234
+ * @param parsed - script parse whose syntax tree is indexed
235
+ * @returns - cached points sorted by zero-based source line; empty when no supported callable is found
208
236
  */
209
237
  export function callableMatchPoints(parsed: ParsedScript): CallableMatchPoint[] {
210
238
  return parsedSyntaxIndex(parsed).callablePoints;
211
239
  }
212
240
 
213
241
  /**
214
- * Returns variable and contract-field owners from the same syntax walk used for callable blocks.
215
- * @param parsed Shared parse for the user's script; it is always present for a deep script scan.
216
- * @returns Ordered rows; empty arrays mean the source declares no currently inventoried names.
242
+ * List the four callable forms reserved for size and complexity checks in FAMILY-CONTRACT.md section 12.
243
+ * Covers function or arrow expressions in non-computed properties, member assignments, identifier-bound var initializers and immediate calls.
244
+ * Uses the shared syntax index and caches it on first access for this parse.
245
+ *
246
+ * @param parsed - script parse whose syntax index supplies the callable locations
247
+ * @returns the cached match points in source order, empty when the script uses none of those forms
217
248
  */
218
- export function declarationOwnershipPoints(parsed: ParsedScript): DeclarationOwnershipPoints {
219
- return parsedSyntaxIndex(parsed).declarationOwnership;
249
+ export function measuredOnlyCallablePoints(parsed: ParsedScript): CallableMatchPoint[] {
250
+ return parsedSyntaxIndex(parsed).measuredOnlyPoints;
220
251
  }
221
252
 
222
- // Builds one deterministic syntax index per parsed script so block and naming rules share a walk.
223
- // Stable contract: repeated consumers receive the same ordered rows and owner ids.
253
+ /**
254
+ * Builds or retrieves the cached syntax index for `parsed` so that block rules share one walk.
255
+ * Caches the index by parse identity and reuses it on later calls.
256
+ *
257
+ * @param parsed - shared script parse whose syntax tree is indexed
258
+ * @returns The stable index holding ordinary callable points sorted by line and measured-only points in traversal order.
259
+ */
224
260
  function parsedSyntaxIndex(parsed: ParsedScript): ParsedSyntaxIndex {
225
261
  const cachedIndex = parsedSyntaxIndexes.get(parsed);
226
262
  // Multiple rule consumers reach the same file, so a completed projection is reused verbatim.
@@ -228,266 +264,252 @@ function parsedSyntaxIndex(parsed: ParsedScript): ParsedSyntaxIndex {
228
264
  return cachedIndex;
229
265
  }
230
266
  const callablePointsByLine = new Map<number, CallableMatchPoint>();
231
- const variableDeclarations: OwnedDeclarationPoint[] = [];
232
- const contractFields: OwnedDeclarationPoint[] = [];
233
- const sourceLines = parsed.sourceFile.text.split(/\r?\n/);
234
- // Carries the nearest callable owner for local declarations and the lexical type scope for
235
- // declaration merging while one depth-first walk visits the user's syntax tree.
236
- const visitSyntaxNode = (node: TsNode, declarationOwner: IdentifierOwner, contractScopeId: string): void => {
267
+ const measuredOnlyPoints: CallableMatchPoint[] = [];
268
+ /**
269
+ * Visits a syntax node and its descendants to populate the shared callable map and list of measured-only points.
270
+ *
271
+ * @param node - AST node inspected for callable match points and traversed recursively
272
+ * @returns Nothing. Records any matching declaration and measured-only points in the enclosing collections.
273
+ */
274
+ const visitSyntaxNode = (node: TsNode): void => {
237
275
  recordCallablePoint(callablePointsByLine, matchPointFor(parsed.sourceFile, node));
238
- recordVariableDeclaration(parsed.sourceFile, node, declarationOwner, variableDeclarations);
239
- recordContractFields(parsed.sourceFile, sourceLines, node, contractScopeId, contractFields);
240
- const callableOwner = functionLikeOwner(parsed.sourceFile, node);
241
- const childDeclarationOwner = callableOwner ?? declarationOwner;
242
- const childContractScopeId = nestedContractScopeId(parsed.sourceFile, node, callableOwner, contractScopeId);
243
- // Nested declarations inherit the nearest user-visible callable and lexical contract boundary.
244
- node.forEachChild((child) => visitSyntaxNode(child, childDeclarationOwner, childContractScopeId));
276
+ const measuredOnlyPoint = measuredOnlyPointFor(parsed.sourceFile, node);
277
+ if (measuredOnlyPoint) {
278
+ measuredOnlyPoints.push(measuredOnlyPoint);
279
+ }
280
+ node.forEachChild(visitSyntaxNode);
245
281
  };
246
- // Top-level declarations begin in the module owner shown to CLI and report consumers.
247
- parsed.sourceFile.forEachChild((node) => visitSyntaxNode(node, MODULE_IDENTIFIER_OWNER, MODULE_IDENTIFIER_OWNER.ownerId));
282
+ parsed.sourceFile.forEachChild(visitSyntaxNode);
248
283
  const syntaxIndex: ParsedSyntaxIndex = {
249
284
  callablePoints: [...callablePointsByLine.values()].sort((left, right) => left.lineIndex - right.lineIndex),
250
- declarationOwnership: { variableDeclarations, contractFields },
285
+ measuredOnlyPoints,
251
286
  };
252
287
  parsedSyntaxIndexes.set(parsed, syntaxIndex);
253
288
  return syntaxIndex;
254
289
  }
255
290
 
256
- // Applies the established one-block-per-line policy while the shared syntax index is built.
291
+ /**
292
+ * Updates `callablePointsByLine` with `callablePoint` under the one-block-per-line policy.
293
+ *
294
+ * @param callablePointsByLine - map keyed by zero-based `lineIndex` holding the winning point per line
295
+ * @param callablePoint - candidate callable point, or undefined when the visited node is not a callable declaration
296
+ * @returns Nothing. Inserts `callablePoint` or replaces a non-test point with a test callback; undefined leaves the map unchanged.
297
+ */
257
298
  function recordCallablePoint(callablePointsByLine: Map<number, CallableMatchPoint>, callablePoint: CallableMatchPoint | undefined): void {
258
299
  // Most syntax nodes are not callable declarations, so they add no report block.
259
300
  if (!callablePoint) {
260
301
  return;
261
302
  }
262
303
  const existingPoint = callablePointsByLine.get(callablePoint.lineIndex);
263
- // Test callbacks outrank same-line declarations; otherwise the first source declaration wins.
304
+ // A test callback replaces a non-test point on the same line. Otherwise the first recorded point stays.
264
305
  if (!existingPoint || (callablePoint.isTestCallable && !existingPoint.isTestCallable)) {
265
306
  callablePointsByLine.set(callablePoint.lineIndex, callablePoint);
266
307
  }
267
308
  }
268
309
 
269
- const CONTRACT_FIELD_LINE = /^[ \t]*(?:readonly\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\??\s*:/;
270
-
271
- /*
272
- * Inputs for projecting one named contract into naming inventory rows. Bundling the syntax owner,
273
- * source view, and result sink keeps the traversal call readable when a CLI scan reaches an
274
- * interface or type-literal declaration.
310
+ /**
311
+ * Builds a match point for named functions, identifier-named methods or signatures, constructors,
312
+ * identifier-bound const/let function values, and bare test or it calls with a literal title and callback.
313
+ *
314
+ * @param sourceFile - parsed TypeScript source file used for positions and parameter text
315
+ * @param node - AST node inspected for a supported callable form
316
+ * @returns Match point for supported declarations, or undefined for unsupported shapes including accessors and anonymous declarations.
275
317
  */
276
- interface ContractFieldCollection {
277
- sourceFile: TsSourceFile;
278
- sourceLines: string[];
279
- members: import("typescript").NodeArray<import("typescript").TypeElement>;
280
- ownerName: string;
281
- ownerKind: "interface" | "type-literal";
282
- contractScopeId: string;
283
- declarationPosition: number;
284
- contractFields: OwnedDeclarationPoint[];
285
- }
286
-
287
- // Records the first simple binding from each declaration list, matching the inventory users saw
288
- // before ownership was added. A comma-separated second binding remains outside this rule's scope.
289
- function recordVariableDeclaration(sourceFile: TsSourceFile, node: TsNode, owner: IdentifierOwner, variableDeclarations: OwnedDeclarationPoint[]): void {
290
- // Other syntax nodes cannot introduce the const/let/var rows this naming inventory covers.
291
- if (!typescriptSyntax.isVariableDeclarationList(node)) {
292
- return;
318
+ function matchPointFor(sourceFile: TsSourceFile, node: TsNode): CallableMatchPoint | undefined {
319
+ if (typescriptSyntax.isFunctionDeclaration(node) && node.name) {
320
+ return declarationPoint(sourceFile, node.name.getStart(sourceFile), node, node.name.text, node.parameters);
293
321
  }
294
- const firstDeclaration = node.declarations[0];
295
- // Destructuring or an empty recovered declaration stays outside the existing simple-name rule.
296
- if (!firstDeclaration || !typescriptSyntax.isIdentifier(firstDeclaration.name)) {
297
- return;
322
+ if ((typescriptSyntax.isMethodDeclaration(node) || typescriptSyntax.isMethodSignature(node)) && typescriptSyntax.isIdentifier(node.name)) {
323
+ return declarationPoint(sourceFile, node.name.getStart(sourceFile), node, node.name.text, node.parameters);
298
324
  }
299
- variableDeclarations.push({
300
- name: firstDeclaration.name.text,
301
- line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
302
- ...owner,
303
- });
304
- }
305
-
306
- // Adds direct interface or named type-literal fields to the report inventory. Member methods,
307
- // computed keys, mapped types, and same-line bodies remain outside the established rule surface.
308
- function recordContractFields(sourceFile: TsSourceFile, sourceLines: string[], node: TsNode, contractScopeId: string, contractFields: OwnedDeclarationPoint[]): void {
309
- // Interface declaration blocks with the same name and lexical scope intentionally share an owner.
310
- if (typescriptSyntax.isInterfaceDeclaration(node)) {
311
- recordNamedContractFields({ sourceFile, sourceLines, members: node.members, ownerName: node.name.text, ownerKind: "interface", contractScopeId, declarationPosition: node.name.getStart(sourceFile), contractFields });
312
- return;
325
+ if (typescriptSyntax.isConstructorDeclaration(node)) {
326
+ // Constructors have no name node, so the match point uses the parameter-list position as its anchor.
327
+ return declarationPoint(sourceFile, node.parameters.pos, node, "constructor", node.parameters);
313
328
  }
314
- // Only a named alias whose direct value is an object type matches the existing type-literal scan.
315
- if (typescriptSyntax.isTypeAliasDeclaration(node) && typescriptSyntax.isTypeLiteralNode(node.type)) {
316
- recordNamedContractFields({ sourceFile, sourceLines, members: node.type.members, ownerName: node.name.text, ownerKind: "type-literal", contractScopeId, declarationPosition: node.name.getStart(sourceFile), contractFields });
329
+ if (typescriptSyntax.isVariableDeclaration(node)) {
330
+ return variableInitializerPoint(sourceFile, node);
317
331
  }
318
- }
319
-
320
- // Projects direct property signatures for one contract owner while retaining the old line filter.
321
- function recordNamedContractFields(args: ContractFieldCollection): void {
322
- const declarationLineIndex = args.sourceFile.getLineAndCharacterOfPosition(args.declarationPosition).line;
323
- const owner = contractIdentifierOwner(args.ownerKind, args.contractScopeId, args.ownerName);
324
- // Each direct member is evaluated once in source order, which keeps report ordering stable.
325
- for (const member of args.members) {
326
- // Methods, indexes, and computed property names are not simple field declarations for users.
327
- if (!typescriptSyntax.isPropertySignature(member) || !typescriptSyntax.isIdentifier(member.name)) {
328
- continue;
329
- }
330
- const lineIndex = args.sourceFile.getLineAndCharacterOfPosition(member.name.getStart(args.sourceFile)).line;
331
- // The legacy line walker begins after the header, so a one-line contract remains un-inventoried.
332
- if (lineIndex <= declarationLineIndex) {
333
- continue;
334
- }
335
- const sourceName = args.sourceLines[lineIndex]?.match(CONTRACT_FIELD_LINE)?.[1];
336
- // Multi-line or non-leading property syntax stays outside the current user-visible coverage.
337
- if (sourceName !== member.name.text) {
338
- continue;
339
- }
340
- args.contractFields.push({ name: member.name.text, line: lineIndex + 1, ...owner });
332
+ if (typescriptSyntax.isCallExpression(node)) {
333
+ return testCallbackPoint(sourceFile, node);
341
334
  }
335
+ return undefined;
342
336
  }
343
337
 
344
- // Builds the merged contract identity shown in finding metadata. Names are syntactic identifiers,
345
- // while the lexical prefix separates equally named contracts in unrelated user scopes.
346
- function contractIdentifierOwner(ownerKind: "interface" | "type-literal", contractScopeId: string, ownerName: string): IdentifierOwner {
347
- return {
348
- ownerId: `${ownerKind}:${contractScopeId}:${ownerName}`,
349
- ownerKind,
350
- ownerName,
351
- };
338
+ /**
339
+ * Projects `node` into a size/complexity-only match point for a var binding, object key, member assignment, or immediate invocation.
340
+ *
341
+ * @param sourceFile - parsed TypeScript source file used for positions and parameter text
342
+ * @param node - AST node inspected against the four measured-only function-value forms
343
+ * @returns Match point for the first matching form, or undefined when no supported function-value form matches.
344
+ */
345
+ function measuredOnlyPointFor(sourceFile: TsSourceFile, node: TsNode): CallableMatchPoint | undefined {
346
+ return varFunctionPoint(sourceFile, node) ?? keyFunctionPoint(sourceFile, node) ?? memberFunctionPoint(sourceFile, node) ?? invokedFunctionPoint(sourceFile, node);
352
347
  }
353
348
 
354
- // Returns a stable callable owner for descendants, or no replacement when this node is ordinary
355
- // syntax. An absent owner means local declarations keep the nearest callable or module boundary.
356
- function functionLikeOwner(sourceFile: TsSourceFile, node: TsNode): IdentifierOwner | undefined {
357
- // Only function-like syntax starts a new local naming boundary for the user's declarations.
358
- if (!typescriptSyntax.isFunctionLike(node)) {
349
+ /**
350
+ * Extracts a match point for an identifier-named `var` binding initialized with a function expression or arrow, naming it after the variable.
351
+ *
352
+ * @param sourceFile - parsed TypeScript source file used for positions and parameter text
353
+ * @param node - AST node checked for a `var` declaration with a function or arrow initializer
354
+ * @returns Callable match point anchored at the variable identifier, or undefined for other shapes.
355
+ */
356
+ function varFunctionPoint(sourceFile: TsSourceFile, node: TsNode): CallableMatchPoint | undefined {
357
+ if (!typescriptSyntax.isVariableDeclaration(node) || !typescriptSyntax.isIdentifier(node.name) || !isVarList(node.parent)) {
359
358
  return undefined;
360
359
  }
361
- return callableIdentifierOwner(sourceFile, node);
362
- }
363
-
364
- // Creates a range-derived callable identity without exposing TypeScript node objects or file paths.
365
- function callableIdentifierOwner(sourceFile: TsSourceFile, callableNode: TsNode): IdentifierOwner {
366
- const ownerName = functionLikeOwnerName(callableNode);
367
- // Anonymous callbacks retain their range identity while omitting a misleading display name.
368
- return {
369
- ownerId: `function:${callableNode.getStart(sourceFile)}:${callableNode.getEnd()}`,
370
- ownerKind: "function",
371
- ...(ownerName === undefined ? {} : { ownerName }),
372
- };
373
- }
374
-
375
- // Chooses the first human label a CLI user recognizes across declaration, binding, and test shapes.
376
- function functionLikeOwnerName(node: TsNode): string | undefined {
377
- // The precedence matches existing block labels; no recognized shape means an anonymous owner.
378
- return declaredFunctionLikeOwnerName(node) ?? boundFunctionLikeOwnerName(node) ?? testFunctionLikeOwnerName(node);
379
- }
380
-
381
- // Reads names written directly on functions and methods, including the constructor label.
382
- function declaredFunctionLikeOwnerName(node: TsNode): string | undefined {
383
- const namedNode = node as TsNode & { name?: TsNode };
384
- // Named functions, methods, accessors, and signatures already carry their user-facing label.
385
- if (namedNode.name && typescriptSyntax.isIdentifier(namedNode.name)) {
386
- return namedNode.name.text;
387
- }
388
- // Constructors have no name node but are recognizable as one callable in class diagnostics.
389
- if (typescriptSyntax.isConstructorDeclaration(node)) {
390
- return "constructor";
360
+ const initializer = node.initializer ? withoutParentheses(node.initializer) : undefined;
361
+ if (!isFunctionValue(initializer)) {
362
+ return undefined;
391
363
  }
392
- return undefined;
364
+ return declarationPoint(sourceFile, node.name.getStart(sourceFile), initializer, node.name.text, initializer.parameters);
393
365
  }
394
366
 
395
- // Reads the variable or property label that presents an otherwise anonymous callable to users.
396
- function boundFunctionLikeOwnerName(node: TsNode): string | undefined {
397
- const parent = node.parent;
398
- // Variable-bound arrows and function expressions are presented under their declared variable.
399
- if (typescriptSyntax.isVariableDeclaration(parent) && typescriptSyntax.isIdentifier(parent.name)) {
400
- return parent.name.text;
367
+ /**
368
+ * Projects a non-computed object property assigned a function expression or arrow into a match point.
369
+ * Prefixes the key with the object's variable or assignment target when known, keeping the bare key without an owner name.
370
+ *
371
+ * @param sourceFile - parsed TypeScript source file used for positions and parameter text
372
+ * @param node - AST node checked for a non-computed property assignment with a function-value initializer
373
+ * @returns Callable match point for the property function, or undefined when `node` does not match.
374
+ */
375
+ function keyFunctionPoint(sourceFile: TsSourceFile, node: TsNode): CallableMatchPoint | undefined {
376
+ if (!typescriptSyntax.isPropertyAssignment(node) || typescriptSyntax.isComputedPropertyName(node.name)) {
377
+ return undefined;
401
378
  }
402
- // Object and class property callbacks can use the property label without a discovered block row.
403
- if ((typescriptSyntax.isPropertyAssignment(parent) || typescriptSyntax.isPropertyDeclaration(parent)) && typescriptSyntax.isIdentifier(parent.name)) {
404
- return parent.name.text;
379
+ const initializer = withoutParentheses(node.initializer);
380
+ if (!isFunctionValue(initializer)) {
381
+ return undefined;
405
382
  }
406
- return undefined;
383
+ const objectName = objectLiteralName(sourceFile, node.parent);
384
+ const name = objectName ? `${objectName}.${node.name.text}` : node.name.text;
385
+ return declarationPoint(sourceFile, node.name.getStart(sourceFile), initializer, name, initializer.parameters);
407
386
  }
408
387
 
409
- // Reads a literal test title, matching the test block symbol a CLI user already sees.
410
- function testFunctionLikeOwnerName(node: TsNode): string | undefined {
411
- const parent = node.parent;
412
- // Ordinary callback arguments have no stable test label and remain anonymous owner metadata.
413
- if (!typescriptSyntax.isCallExpression(parent) || parent.arguments[1] !== node || !typescriptSyntax.isIdentifier(parent.expression) || (parent.expression.text !== "test" && parent.expression.text !== "it")) {
388
+ /**
389
+ * Extracts a match point when `node` assigns a function expression or arrow to a property or element access.
390
+ *
391
+ * @param sourceFile - parsed TypeScript source file used for positions, parameter text, and compact target naming
392
+ * @param node - AST node checked for a simple `=` assignment onto a member access expression
393
+ * @returns Callable match point named after the target expression, or undefined for other node shapes.
394
+ */
395
+ function memberFunctionPoint(sourceFile: TsSourceFile, node: TsNode): CallableMatchPoint | undefined {
396
+ if (!typescriptSyntax.isBinaryExpression(node) || node.operatorToken.kind !== typescriptSyntax.SyntaxKind.EqualsToken || !isMember(node.left)) {
414
397
  return undefined;
415
398
  }
416
- const title = parent.arguments[0];
417
- // Dynamic test titles have no stable human label, so only literal titles are included.
418
- if (!title || !typescriptSyntax.isStringLiteralLike(title)) {
399
+ const right = withoutParentheses(node.right);
400
+ if (!isFunctionValue(right)) {
419
401
  return undefined;
420
402
  }
421
- return title.text;
403
+ return declarationPoint(sourceFile, node.left.getStart(sourceFile), right, compactText(sourceFile, node.left), right.parameters);
422
404
  }
423
405
 
424
- // Advances the lexical scope used only for merging named contracts. Ordinary function body blocks
425
- // stay under their callable, while nested blocks and namespaces separate same-name declarations.
426
- function nestedContractScopeId(sourceFile: TsSourceFile, node: TsNode, callableOwner: IdentifierOwner | undefined, currentScopeId: string): string {
427
- // A function-like boundary is the lexical contract scope users see around local type declarations.
428
- if (callableOwner) {
429
- return callableOwner.ownerId;
430
- }
431
- // Namespace bodies can contain same-name interfaces that must not merge with module contracts.
432
- // TypeScript merges every block of one namespace into a single declaration space, so the scope
433
- // is keyed on the namespace path - byte offsets would split a re-opened namespace in two.
434
- if (typescriptSyntax.isModuleBlock(node)) {
435
- return `module-block:${namespaceDeclarationPath(node)}`;
436
- }
437
- // A nested statement block is a distinct type-declaration scope; the function body itself is not.
438
- if (typescriptSyntax.isBlock(node) && !typescriptSyntax.isFunctionLike(node.parent)) {
439
- return `block:${node.getStart(sourceFile)}:${node.getEnd()}`;
406
+ /**
407
+ * Extracts a match point when `node` directly invokes a function expression or arrow, using the function's name or `<iife>` when unnamed.
408
+ *
409
+ * @param sourceFile - parsed TypeScript source file used for positions and parameter text
410
+ * @param node - AST node checked for a call expression whose unparenthesized callee is a function or arrow
411
+ * @returns Callable match point for the invoked function, or undefined for all other nodes.
412
+ */
413
+ function invokedFunctionPoint(sourceFile: TsSourceFile, node: TsNode): CallableMatchPoint | undefined {
414
+ const callee = typescriptSyntax.isCallExpression(node) ? withoutParentheses(node.expression) : undefined;
415
+ if (!isFunctionValue(callee)) {
416
+ return undefined;
440
417
  }
441
- return currentScopeId;
418
+ const name = typescriptSyntax.isFunctionExpression(callee) && callee.name ? callee.name.text : "<iife>";
419
+ return declarationPoint(sourceFile, callee.getStart(sourceFile), callee, name, callee.parameters);
442
420
  }
443
421
 
444
- // Joins every enclosing namespace name so the two spellings a user can write for one declaration
445
- // space - `namespace A.B` and `namespace A { namespace B }` - land on the same contract scope.
446
- function namespaceDeclarationPath(moduleBlock: TsNode): string {
447
- const names: string[] = [];
448
- for (let ancestor = moduleBlock.parent; ancestor && !typescriptSyntax.isSourceFile(ancestor); ancestor = ancestor.parent) {
449
- // Only the namespace headers carry a name; intervening blocks are walked through, not recorded.
450
- if (typescriptSyntax.isModuleDeclaration(ancestor)) {
451
- names.push(ancestor.name.text);
452
- }
453
- }
454
- return names.reverse().join(".");
422
+ /**
423
+ * Type guard checking whether `node` is a function expression or arrow function.
424
+ *
425
+ * @param node - AST node or undefined to inspect
426
+ * @returns True and narrows `node` for a function expression or arrow function; undefined and all other node kinds return false.
427
+ */
428
+ function isFunctionValue(node: TsNode | undefined): node is import("typescript").FunctionExpression | import("typescript").ArrowFunction {
429
+ return node !== undefined && (typescriptSyntax.isFunctionExpression(node) || typescriptSyntax.isArrowFunction(node));
455
430
  }
456
431
 
457
- // Classifies one AST node into a callable match point, or undefined for non-callable nodes.
458
- // Accessors and anonymous/default-export-anonymous functions stay excluded: the legacy scanner
459
- // never discovered them, and naming policy for those shapes is deferred to a separate decision.
460
- function matchPointFor(sourceFile: TsSourceFile, node: TsNode): CallableMatchPoint | undefined {
461
- if (typescriptSyntax.isFunctionDeclaration(node) && node.name) {
462
- return declarationPoint(sourceFile, node.name.getStart(sourceFile), node, node.name.text, node.parameters);
463
- }
464
- if ((typescriptSyntax.isMethodDeclaration(node) || typescriptSyntax.isMethodSignature(node)) && typescriptSyntax.isIdentifier(node.name)) {
465
- return declarationPoint(sourceFile, node.name.getStart(sourceFile), node, node.name.text, node.parameters);
466
- }
467
- if (typescriptSyntax.isConstructorDeclaration(node)) {
468
- // Constructors carry no name node; the parameter-list position sits on the declaration line.
469
- return declarationPoint(sourceFile, node.parameters.pos, node, "constructor", node.parameters);
470
- }
471
- if (typescriptSyntax.isVariableDeclaration(node)) {
472
- return variableInitializerPoint(sourceFile, node);
432
+ /**
433
+ * Checks whether `node` is a `var` declaration list; `const` and `let` lists are excluded because `variableInitializerPoint` already handles them.
434
+ *
435
+ * @param node - AST node tested for a non-block-scoped variable declaration list
436
+ * @returns True when `node` is a `VariableDeclarationList` without `BlockScoped` flags; otherwise false.
437
+ */
438
+ function isVarList(node: TsNode): boolean {
439
+ return typescriptSyntax.isVariableDeclarationList(node) && (node.flags & typescriptSyntax.NodeFlags.BlockScoped) === 0;
440
+ }
441
+
442
+ /**
443
+ * Checks whether `node` is a property or element access, the member targets accepted for function assignments.
444
+ *
445
+ * @param node - AST node tested as an assignment target
446
+ * @returns True when `node` is a `PropertyAccessExpression` or `ElementAccessExpression`; otherwise false.
447
+ */
448
+ function isMember(node: TsNode): boolean {
449
+ return typescriptSyntax.isPropertyAccessExpression(node) || typescriptSyntax.isElementAccessExpression(node);
450
+ }
451
+
452
+ /**
453
+ * Derives an owner label for `objectLiteral` from its enclosing identifier binding or simple `=` assignment target.
454
+ *
455
+ * @param sourceFile - parsed TypeScript source file used to read and compact the assignment target text
456
+ * @param objectLiteral - object literal node whose parent binding or assignment is inspected
457
+ * @returns Identifier name or whitespace-free target label, or undefined when `objectLiteral` has no qualifying owner.
458
+ */
459
+ function objectLiteralName(sourceFile: TsSourceFile, objectLiteral: TsNode): string | undefined {
460
+ const owner = objectLiteral.parent;
461
+ if (typescriptSyntax.isVariableDeclaration(owner) && typescriptSyntax.isIdentifier(owner.name)) {
462
+ return owner.name.text;
473
463
  }
474
- if (typescriptSyntax.isCallExpression(node)) {
475
- return testCallbackPoint(sourceFile, node);
464
+ if (typescriptSyntax.isBinaryExpression(owner) && owner.operatorToken.kind === typescriptSyntax.SyntaxKind.EqualsToken && owner.right === objectLiteral) {
465
+ return compactText(sourceFile, owner.left);
476
466
  }
477
467
  return undefined;
478
468
  }
479
469
 
480
- // Builds the point for a named declaration: the anchor line is the name's line, matching where
481
- // the legacy line-oriented patterns fired; the end line is the declaration's final token.
470
+ /**
471
+ * Reads `node`'s text from `sourceFile` with all whitespace removed, keeping multiline member names on one line.
472
+ *
473
+ * @param sourceFile - parsed TypeScript source file supplying source text
474
+ * @param node - AST node whose text is compacted
475
+ * @returns Source text of `node` with all whitespace stripped.
476
+ */
477
+ function compactText(sourceFile: TsSourceFile, node: TsNode): string {
478
+ return node.getText(sourceFile).replace(/\s+/g, "");
479
+ }
480
+
481
+ /**
482
+ * Unwraps all outer parenthesized expressions from `node`, exposing an immediate call's callee.
483
+ *
484
+ * @param node - AST node to unwrap
485
+ * @returns Inner non-parenthesized node, or `node` itself when it is not parenthesized.
486
+ */
487
+ function withoutParentheses(node: TsNode): TsNode {
488
+ let inner = node;
489
+ while (typescriptSyntax.isParenthesizedExpression(inner)) {
490
+ inner = inner.expression;
491
+ }
492
+ return inner;
493
+ }
494
+
495
+ /**
496
+ * Builds a callable match point with zero-based name, declaration, and end line indexes plus visibility and body flags.
497
+ *
498
+ * @param sourceFile - parsed TypeScript source file used for line lookups and parameter text
499
+ * @param position - zero-based character offset anchoring the reported name line
500
+ * @param callableNode - AST node whose enclosing visibility, final-token line, and body presence are recorded
501
+ * @param name - reported block label for the callable
502
+ * @param parameters - parameter nodes supplying displayed parameter text and count
503
+ * @returns Populated `CallableMatchPoint` with clamped declaration start line and zero-based line indexes.
504
+ */
482
505
  function declarationPoint(sourceFile: TsSourceFile, position: number, callableNode: TsNode, name: string, parameters: readonly TsNode[]): CallableMatchPoint {
483
506
  const visibilityNode = callableVisibilityNode(callableNode);
484
507
  const isDirectlyExported = hasNodeModifier(visibilityNode, typescriptSyntax.SyntaxKind.ExportKeyword);
485
508
  const lineIndex = sourceFile.getLineAndCharacterOfPosition(position).line;
486
- // `getStart` skips leading documentation, so this lands on the first modifier or keyword. Clamped
487
- // to `lineIndex` so the declaration anchor can only ever move earlier than the reported name line.
509
+ // getStart skips leading documentation, so this finds the start of the declaration syntax.
510
+ // Clamp the declaration anchor because a callable expression can start on a later line than its reported label.
488
511
  const declarationStartLine = sourceFile.getLineAndCharacterOfPosition(visibilityNode.getStart(sourceFile)).line;
489
512
  return {
490
- ...callableIdentifierOwner(sourceFile, callableNode),
491
513
  lineIndex,
492
514
  declarationLineIndex: Math.min(declarationStartLine, lineIndex),
493
515
  endLineIndex: sourceFile.getLineAndCharacterOfPosition(callableNode.getEnd()).line,
@@ -499,12 +521,17 @@ function declarationPoint(sourceFile: TsSourceFile, position: number, callableNo
499
521
  isExplicitlyPublic: isDirectlyExported || hasNodeModifier(visibilityNode, typescriptSyntax.SyntaxKind.PublicKeyword),
500
522
  isModuleScoped: visibilityNode.parent === sourceFile,
501
523
  hasBody: callableNodeHasBody(callableNode),
524
+ isOverride: hasNodeModifier(visibilityNode, typescriptSyntax.SyntaxKind.OverrideKeyword),
502
525
  callableNode,
503
526
  };
504
527
  }
505
528
 
506
- // Variable-backed callables inherit export modifiers and module scope from their statement;
507
- // declaration-shaped callables already carry both facts on their own node.
529
+ /**
530
+ * Resolves the enclosing variable statement for a variable-backed `callableNode` so visibility checks see its export and module scope.
531
+ *
532
+ * @param callableNode - callable AST node whose parent chain is inspected
533
+ * @returns Enclosing `VariableStatement` for variable-backed callables, or `callableNode` itself for declarations or missing ancestry.
534
+ */
508
535
  function callableVisibilityNode(callableNode: TsNode): TsNode {
509
536
  const declaration = callableNode.parent;
510
537
  if (!typescriptSyntax.isVariableDeclaration(declaration)) {
@@ -518,21 +545,36 @@ function callableVisibilityNode(callableNode: TsNode): TsNode {
518
545
  return typescriptSyntax.isVariableStatement(statement) ? statement : callableNode;
519
546
  }
520
547
 
521
- // Reads a modifier only when the syntax node can own modifiers.
548
+ /**
549
+ * Checks whether `node` carries a modifier matching `modifierKind`.
550
+ *
551
+ * @param node - AST node whose modifiers are inspected when supported
552
+ * @param modifierKind - TypeScript `SyntaxKind` modifier flag to match
553
+ * @returns True when `node` can hold modifiers and includes `modifierKind`; otherwise false.
554
+ */
522
555
  function hasNodeModifier(node: TsNode, modifierKind: import("typescript").SyntaxKind): boolean {
523
556
  const modifiers = typescriptSyntax.canHaveModifiers(node) ? typescriptSyntax.getModifiers(node) : undefined;
524
557
  return modifiers?.some((modifier) => modifier.kind === modifierKind) === true;
525
558
  }
526
559
 
527
- // Arrow functions and function expressions always carry a body, so only declaration-shaped nodes
528
- // can answer false here: a method signature has no `body` property at all, and an overload or
529
- // abstract member leaves it undefined.
560
+ /**
561
+ * Checks whether `callableNode` has an implementation body. Arrow functions and function expressions always carry a body,
562
+ * whereas method signatures, overloads, and abstract members lack one or leave it undefined.
563
+ *
564
+ * @param callableNode - callable AST node checked for a defined `body` property
565
+ * @returns True when `callableNode` has a defined body; false for signatures, overloads, and abstract members.
566
+ */
530
567
  function callableNodeHasBody(callableNode: TsNode): boolean {
531
568
  return (callableNode as { body?: unknown }).body !== undefined;
532
569
  }
533
570
 
534
- // const/let initializer arrows and function expressions become blocks named after the variable;
535
- // `var` stays excluded because the legacy pattern never matched it.
571
+ /**
572
+ * Extracts a variable-named match point for a `const` or `let` declaration initialized with a function expression or arrow.
573
+ *
574
+ * @param sourceFile - parsed TypeScript source file used for positions and parameter text
575
+ * @param node - variable declaration checked for an identifier binding, block-scoped list, and callable initializer
576
+ * @returns Match point named after the variable, or undefined for `var` declarations, destructured bindings, and other initializers.
577
+ */
536
578
  function variableInitializerPoint(sourceFile: TsSourceFile, node: import("typescript").VariableDeclaration): CallableMatchPoint | undefined {
537
579
  if (!typescriptSyntax.isIdentifier(node.name) || !node.initializer) {
538
580
  return undefined;
@@ -547,8 +589,14 @@ function variableInitializerPoint(sourceFile: TsSourceFile, node: import("typesc
547
589
  return declarationPoint(sourceFile, node.name.getStart(sourceFile), node.initializer, node.name.text, node.initializer.parameters);
548
590
  }
549
591
 
550
- // `test("name", () => …)` / `it("name", …)` callbacks become blocks named by the test title,
551
- // anchored at the call line - the legacy scanner's highest-priority pattern.
592
+ /**
593
+ * Extracts a match point for a bare `test` or `it` call with a literal string or substitution-free template title and a function or arrow callback.
594
+ * Anchors the point at the call line so `recordCallablePoint` gives it priority over other declarations on that line.
595
+ *
596
+ * @param sourceFile - parsed TypeScript source file used for positions and parameter text
597
+ * @param node - call expression inspected for a `test`/`it` identifier, literal title, and callback argument
598
+ * @returns Test-callable match point named after the title, or undefined when the call shape does not match.
599
+ */
552
600
  function testCallbackPoint(sourceFile: TsSourceFile, node: import("typescript").CallExpression): CallableMatchPoint | undefined {
553
601
  if (!typescriptSyntax.isIdentifier(node.expression) || (node.expression.text !== "test" && node.expression.text !== "it")) {
554
602
  return undefined;
@@ -562,9 +610,8 @@ function testCallbackPoint(sourceFile: TsSourceFile, node: import("typescript").
562
610
  }
563
611
  const lineIndex = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line;
564
612
  return {
565
- ...callableIdentifierOwner(sourceFile, callback),
566
613
  lineIndex,
567
- // A test callback is anchored at its call expression, which is already the declaration line.
614
+ // Keep the declaration anchor at the call start when the callback begins on a later line.
568
615
  declarationLineIndex: lineIndex,
569
616
  endLineIndex: sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line,
570
617
  name: title.text,
@@ -575,12 +622,19 @@ function testCallbackPoint(sourceFile: TsSourceFile, node: import("typescript").
575
622
  isExplicitlyPublic: false,
576
623
  isModuleScoped: false,
577
624
  hasBody: true,
625
+ isOverride: false,
578
626
  callableNode: callback,
579
627
  };
580
628
  }
581
629
 
582
- // Joins each AST parameter span without the inter-parameter trivia where an end-of-line comment
583
- // could otherwise swallow the following name after newlines are flattened.
630
+ /**
631
+ * Formats parameter slices from `sourceFile` joined by comma-space with newlines flattened.
632
+ * Omits inter-parameter trivia so a line comment between parameters cannot swallow the next name after flattening.
633
+ *
634
+ * @param sourceFile - parsed TypeScript source file supplying raw parameter spans
635
+ * @param parameters - AST parameter nodes whose trimmed spans are formatted
636
+ * @returns Comma-space joined parameter text with newlines replaced by spaces, or an empty string when `parameters` is empty.
637
+ */
584
638
  function parametersText(sourceFile: TsSourceFile, parameters: readonly TsNode[]): string {
585
639
  return parameters
586
640
  .map((parameter) => sourceFile.text.slice(parameter.getStart(sourceFile), parameter.getEnd()))
@@ -588,33 +642,108 @@ function parametersText(sourceFile: TsSourceFile, parameters: readonly TsNode[])
588
642
  .replace(/\r?\n/g, " ");
589
643
  }
590
644
 
645
+ /**
646
+ * One named import binding extracted from the shared syntax tree for unused-import checks.
647
+ * Preserves the import declaration's one-based start line so finding fingerprints stay stable.
648
+ */
649
+ export interface NamedImportBinding {
650
+ /** Local identifier bound by the specifier (the alias when `as` is used, otherwise the imported name). */
651
+ name: string;
652
+ /** One-based line where the enclosing `import` statement starts. */
653
+ line: number;
654
+ }
655
+
656
+ /**
657
+ * Lists every named import binding in the shared syntax tree, including inline `type` specifiers and aliases.
658
+ * Skips default-only, namespace, and side-effect imports because they bind no `{ ... }` specifier list.
659
+ *
660
+ * @param parsed - shared syntax tree whose top-level statements are inspected for named imports
661
+ * @returns Named import bindings in source order; empty when the script has no named import specifiers.
662
+ */
663
+ export function namedImportBindings(parsed: ParsedScript): NamedImportBinding[] {
664
+ const bindings: NamedImportBinding[] = [];
665
+ for (const statement of parsed.sourceFile.statements) {
666
+ if (!typescriptSyntax.isImportDeclaration(statement)) {
667
+ continue;
668
+ }
669
+ const namedBindings = statement.importClause?.namedBindings;
670
+ if (!namedBindings || !typescriptSyntax.isNamedImports(namedBindings)) {
671
+ continue;
672
+ }
673
+ const line = parsed.sourceFile.getLineAndCharacterOfPosition(statement.getStart(parsed.sourceFile)).line + 1;
674
+ for (const element of namedBindings.elements) {
675
+ bindings.push({ name: element.name.text, line });
676
+ }
677
+ }
678
+ return bindings;
679
+ }
680
+
681
+ /**
682
+ * Metadata for one destructured parameter slot so `docs.stale-param-tag` can validate JSDoc object and dotted property tags.
683
+ */
684
+ export interface DestructuredParameterSlot {
685
+ /** Top-level object keys explicitly named in the destructuring pattern; empty for array or rest-only patterns. */
686
+ keys: string[];
687
+ /** True when a rest element, computed property, or array pattern prevents enumerating all valid sub-keys statically. */
688
+ hasOpenKeys: boolean;
689
+ }
690
+
591
691
  /*
592
- * One exported, documented function declaration as the docblock rules consume it: the JSDoc text
593
- * between its markers, the declared name, identifier parameter names (destructured parameters stay
594
- * intentionally invisible, matching the legacy text splitter), the docblock's one-based start line
595
- * (the docblock rules' stable finding anchor), and the declared return type text ("" when absent).
692
+ * One documented callable projected for docblock tag rules (`docs.missing-param-tag`, `docs.missing-return-tag`, `docs.stale-param-tag`).
693
+ *
694
+ * Covers exported declarations plus constants, methods, and private callables when `everyCallable` is enabled:
695
+ * - `docText` holds JSDoc interior text (empty when `hasJsDoc` is false for `//` or `/* *\/` comments);
696
+ * - `parameterNames` lists identifier parameters while `destructuredParameters` tracks object/array binding patterns separately;
697
+ * - `line` anchors findings on the comment's one-based start line for stable fingerprints.
596
698
  */
597
699
  export interface DocumentedExportFunction {
598
700
  docText: string;
701
+ hasJsDoc: boolean;
599
702
  name: string;
600
703
  parameterNames: string[];
704
+ destructuredParameters: DestructuredParameterSlot[];
601
705
  line: number;
602
- returnTypeText: string;
603
706
  }
604
707
 
605
708
  /**
606
- * Enumerates every exported function declaration that carries a leading JSDoc block. Anchoring to
607
- * the syntax tree means prose containing the word `export` inside a comment can no longer suppress
608
- * detection, and `export async function` plus generic and multi-line signatures are covered.
709
+ * Lists named, non-default exported function declarations with callable JSDoc in the shared syntax tree.
710
+ * Recognises async, generic and multiline declarations without treating comment text as declarations.
609
711
  *
610
- * @param parsed Shared parse result for the script.
712
+ * @param parsed - shared syntax tree searched for qualifying function declarations
611
713
  * @returns Documented exported functions in source order; empty when the file has none.
612
714
  */
613
715
  export function documentedExportFunctions(parsed: ParsedScript): DocumentedExportFunction[] {
716
+ return collectDocumented(parsed, documentedExportFunction);
717
+ }
718
+
719
+ /**
720
+ * Lists exported statements with the parser's const flag and one identifier bound to an arrow or function expression for everyCallable tag checks.
721
+ * The statement supplies its final callable JSDoc. The initializer supplies the parameters and return type.
722
+ *
723
+ * @param parsed - shared syntax tree searched for documented exported callable constants
724
+ * @returns Documented exported callable constants in source order; empty when the file has none.
725
+ */
726
+ export function documentedExportConstants(parsed: ParsedScript): DocumentedExportFunction[] {
727
+ return collectDocumented(parsed, documentedExportConstant);
728
+ }
729
+
730
+ /**
731
+ * Walks the parsed syntax tree at every depth so that namespaced exports keep their docblock coverage.
732
+ *
733
+ * @param parsed - shared script parse whose syntax tree is traversed in source order
734
+ * @param project - callback receiving `(sourceFile, node)` and returning a documentation record to include or undefined to skip
735
+ * @returns Collected documentation records in source order, or an empty array when `project` accepts no nodes.
736
+ */
737
+ function collectDocumented(parsed: ParsedScript, project: (sourceFile: TsSourceFile, node: TsNode) => DocumentedExportFunction | undefined): DocumentedExportFunction[] {
614
738
  const results: DocumentedExportFunction[] = [];
615
- // Full-depth walk so namespaced exported functions keep their docblock coverage too.
739
+ /**
740
+ * Projects `node` and recurses into its children so that nested namespace exports are covered.
741
+ *
742
+ * @param node - AST node evaluated with `project` and traversed recursively
743
+ * @returns Nothing. Appends any non-undefined documentation record to `results` in traversal order.
744
+ */
616
745
  const visit = (node: TsNode): void => {
617
- const documented = documentedExportFunction(parsed.sourceFile, node);
746
+ const documented = project(parsed.sourceFile, node);
618
747
  if (documented) {
619
748
  results.push(documented);
620
749
  }
@@ -624,9 +753,14 @@ export function documentedExportFunctions(parsed: ParsedScript): DocumentedExpor
624
753
  return results;
625
754
  }
626
755
 
627
- // Projects one function declaration into the documented-export shape, or undefined when it is not
628
- // an exported named function with a JSDoc block. `export default function` never matched the
629
- // legacy pattern, so it stays excluded until a deliberate policy change covers it.
756
+ /**
757
+ * Projects `node` into a documentation record for a named, non-default exported function declaration with a leading comment.
758
+ * Default exports stay excluded here; `everyCallable` covers them through `documentedDefaultAndLaterExports`.
759
+ *
760
+ * @param sourceFile - parsed TypeScript source file used for documentation text and locations
761
+ * @param node - AST node checked for a named non-default exported function declaration
762
+ * @returns Documentation record for the exported function, or undefined when `node` fails these conditions.
763
+ */
630
764
  function documentedExportFunction(sourceFile: TsSourceFile, node: TsNode): DocumentedExportFunction | undefined {
631
765
  if (!typescriptSyntax.isFunctionDeclaration(node) || !node.name) {
632
766
  return undefined;
@@ -635,18 +769,438 @@ function documentedExportFunction(sourceFile: TsSourceFile, node: TsNode): Docum
635
769
  if ((flags & typescriptSyntax.ModifierFlags.Export) === 0 || (flags & typescriptSyntax.ModifierFlags.Default) !== 0) {
636
770
  return undefined;
637
771
  }
638
- const jsDocs = (node as { jsDoc?: readonly import("typescript").JSDoc[] }).jsDoc;
772
+ return documentedCallable(sourceFile, node, node.name.text, node);
773
+ }
774
+
775
+ /**
776
+ * Extracts a documentation record for an exported `const` statement with one identifier bound to an arrow or function expression.
777
+ *
778
+ * @param sourceFile - parsed TypeScript source file used for the statement's comment text and positions
779
+ * @param node - AST node inspected as a single-binding exported `const` statement
780
+ * @returns Documentation record for the constant callable, or undefined for other shapes or missing usable comments.
781
+ */
782
+ function documentedExportConstant(sourceFile: TsSourceFile, node: TsNode): DocumentedExportFunction | undefined {
783
+ const declaration = soleConstDeclaration(node);
784
+ return declaration && hasExportFlag(declaration) ? documentedConstantCallable(sourceFile, node, declaration) : undefined;
785
+ }
786
+
787
+ /**
788
+ * Builds a documentation row for `declaration`'s identifier-bound arrow or function initializer, using `statement` as the comment host.
789
+ * Callers supply the sole `const` binding for the statement.
790
+ *
791
+ * @param sourceFile - parsed TypeScript source file supplying comment text and positions
792
+ * @param statement - enclosing variable statement hosting the leading comment
793
+ * @param declaration - sole variable declaration whose identifier name and callable initializer are inspected
794
+ * @returns Documentation record for the initializer callable, or undefined for missing callable shape or unusable comments.
795
+ */
796
+ function documentedConstantCallable(sourceFile: TsSourceFile, statement: TsNode, declaration: import("typescript").VariableDeclaration): DocumentedExportFunction | undefined {
797
+ const initializer = declaration.initializer;
798
+ if (!initializer || !typescriptSyntax.isIdentifier(declaration.name)) {
799
+ return undefined;
800
+ }
801
+ if (!typescriptSyntax.isArrowFunction(initializer) && !typescriptSyntax.isFunctionExpression(initializer)) {
802
+ return undefined;
803
+ }
804
+ return documentedCallable(sourceFile, statement, declaration.name.text, initializer);
805
+ }
806
+
807
+ /**
808
+ * Extracts the single variable declaration from a `const` statement; a shared docblock cannot distinguish several declarations.
809
+ *
810
+ * @param node - AST node inspected for a `VariableStatement` with the `Const` flag and exactly one declarator
811
+ * @returns Sole `VariableDeclaration`, or undefined for non-`const` nodes or multi-declarator statements.
812
+ */
813
+ function soleConstDeclaration(node: TsNode): import("typescript").VariableDeclaration | undefined {
814
+ if (!typescriptSyntax.isVariableStatement(node) || (node.declarationList.flags & typescriptSyntax.NodeFlags.Const) === 0) {
815
+ return undefined;
816
+ }
817
+ const [declaration, ...others] = node.declarationList.declarations;
818
+ return declaration && others.length === 0 ? declaration : undefined;
819
+ }
820
+
821
+ /**
822
+ * Checks whether `declaration` carries its own `export` modifier, directly or through its statement.
823
+ *
824
+ * @param declaration - TypeScript declaration node whose combined modifier flags are checked
825
+ * @returns True when `ModifierFlags.Export` is set on `declaration`; otherwise false.
826
+ */
827
+ function hasExportFlag(declaration: import("typescript").Declaration): boolean {
828
+ return (typescriptSyntax.getCombinedModifierFlags(declaration) & typescriptSyntax.ModifierFlags.Export) !== 0;
829
+ }
830
+
831
+ /**
832
+ * Returns documented default function declarations, bare default arrows and qualifying top-level local callables named by separate exports.
833
+ * Anonymous default functions and default arrows are named default; separately exported bindings keep their local names.
834
+ * Separate exports match named functions or single const-flagged callable bindings. An export modifier rules out this match.
835
+ *
836
+ * @param parsed - script tree whose module-level statements and exports are inspected
837
+ * @returns - documentation rows in source order; empty when no eligible callable has usable JSDoc
838
+ */
839
+ export function documentedDefaultAndLaterExports(parsed: ParsedScript): DocumentedExportFunction[] {
840
+ const laterExportedNames = laterExportedLocalNames(parsed.sourceFile);
841
+ const results: DocumentedExportFunction[] = [];
842
+ // Default exports and export lists are module-level syntax, so only top-level statements count.
843
+ for (const statement of parsed.sourceFile.statements) {
844
+ const documented = documentedDefaultExport(parsed.sourceFile, statement) ?? documentedLaterExport(parsed.sourceFile, statement, laterExportedNames);
845
+ if (documented) {
846
+ results.push(documented);
847
+ }
848
+ }
849
+ return results;
850
+ }
851
+
852
+ /**
853
+ * Extracts a documentation record when `statement` is a default function declaration or bare default arrow export.
854
+ *
855
+ * @param sourceFile - parsed TypeScript source file supplying comment text and positions
856
+ * @param statement - top-level statement inspected for a default function or non-parenthesised arrow export assignment
857
+ * @returns Documentation record named after the function or `"default"`, or undefined for other shapes or missing usable comments.
858
+ */
859
+ function documentedDefaultExport(sourceFile: TsSourceFile, statement: TsNode): DocumentedExportFunction | undefined {
860
+ if (typescriptSyntax.isFunctionDeclaration(statement)) {
861
+ const isDefault = (typescriptSyntax.getCombinedModifierFlags(statement) & typescriptSyntax.ModifierFlags.Default) !== 0;
862
+ return isDefault ? documentedCallable(sourceFile, statement, statement.name?.text ?? "default", statement) : undefined;
863
+ }
864
+ if (!typescriptSyntax.isExportAssignment(statement) || statement.isExportEquals || !typescriptSyntax.isArrowFunction(statement.expression)) {
865
+ return undefined;
866
+ }
867
+ return documentedCallable(sourceFile, statement, "default", statement.expression);
868
+ }
869
+
870
+ /**
871
+ * Projects a top-level `statement` into a documentation record for a function or single-binding `const` callable named in `laterExportedNames`.
872
+ * Declarations with their own `export` modifiers are excluded because the exported-callable passes handle them.
873
+ *
874
+ * @param sourceFile - parsed TypeScript source file supplying text and locations
875
+ * @param statement - top-level statement checked for a non-exported function or single-binding `const` declaration
876
+ * @param laterExportedNames - local binding names exported later by default, export-equals, or `export { ... }` statements
877
+ * @returns Documentation record for the separately exported callable, or undefined when ineligible or missing a usable comment.
878
+ */
879
+ function documentedLaterExport(sourceFile: TsSourceFile, statement: TsNode, laterExportedNames: ReadonlySet<string>): DocumentedExportFunction | undefined {
880
+ if (typescriptSyntax.isFunctionDeclaration(statement)) {
881
+ const name = statement.name?.text;
882
+ return name !== undefined && laterExportedNames.has(name) && !hasExportFlag(statement) ? documentedCallable(sourceFile, statement, name, statement) : undefined;
883
+ }
884
+ const declaration = soleConstDeclaration(statement);
885
+ if (!declaration || hasExportFlag(declaration) || !typescriptSyntax.isIdentifier(declaration.name) || !laterExportedNames.has(declaration.name.text)) {
886
+ return undefined;
887
+ }
888
+ return documentedConstantCallable(sourceFile, statement, declaration);
889
+ }
890
+
891
+ /**
892
+ * Collects local names exposed by `sourceFile`'s top-level identifier default exports, export-equals assignments, and value export lists.
893
+ * Reads exports before matching declarations so statement order does not hide a binding.
894
+ *
895
+ * @param sourceFile - parsed TypeScript source file whose top-level statements are scanned
896
+ * @returns Set of locally bound names exported via separate export statements; empty when none qualify.
897
+ */
898
+ function laterExportedLocalNames(sourceFile: TsSourceFile): Set<string> {
899
+ const names = new Set<string>();
900
+ for (const statement of sourceFile.statements) {
901
+ if (typescriptSyntax.isExportAssignment(statement) && typescriptSyntax.isIdentifier(statement.expression)) {
902
+ names.add(statement.expression.text);
903
+ }
904
+ for (const name of localExportListNames(statement)) {
905
+ names.add(name);
906
+ }
907
+ }
908
+ return names;
909
+ }
910
+
911
+ /**
912
+ * Extracts original local names from a value `export { ... }` statement, using the local binding name for each alias.
913
+ * Type-only lists, type-only specifiers, re-exports, and other statement forms contribute no names.
914
+ *
915
+ * @param statement - AST statement inspected for a local named export declaration
916
+ * @returns Array of local value binding names from `statement`, or an empty array when none apply.
917
+ */
918
+ function localExportListNames(statement: TsNode): string[] {
919
+ if (!typescriptSyntax.isExportDeclaration(statement) || statement.moduleSpecifier || statement.isTypeOnly || !statement.exportClause || !typescriptSyntax.isNamedExports(statement.exportClause)) {
920
+ return [];
921
+ }
922
+ return statement.exportClause.elements.filter((element) => !element.isTypeOnly).map((element) => (element.propertyName ?? element.name).text);
923
+ }
924
+
925
+ /**
926
+ * Lists private and nested functions and single-binding const arrow or function-expression callables with JSDoc for everyCallable checks.
927
+ * Excludes direct exports and top-level names from local value export lists or bare-identifier export assignments.
928
+ * Exported forms belong to the exported-callable passes so each declaration is documented once.
929
+ *
930
+ * @param parsed - shared syntax tree searched for eligible declarations
931
+ * @returns Documented private and nested callables in source order; empty when the file has none.
932
+ */
933
+ export function documentedPrivateCallables(parsed: ParsedScript): DocumentedExportFunction[] {
934
+ const laterExportedNames = laterExportedLocalNames(parsed.sourceFile);
935
+ return collectDocumented(parsed, (sourceFile, node) => documentedPrivateCallable(sourceFile, node, laterExportedNames));
936
+ }
937
+
938
+ /**
939
+ * Extracts a documentation record for a private function declaration or single-binding `const` callable with a usable leading comment.
940
+ * A nested binding can reuse a top-level export's name while remaining private.
941
+ *
942
+ * @param sourceFile - parsed TypeScript source file supplying text and identifying top-level parents
943
+ * @param node - AST node inspected as a non-exported function or single-binding `const` callable
944
+ * @param laterExportedNames - top-level binding names already handled by `documentedLaterExport`
945
+ * @returns Documentation record for the private or nested callable, or undefined for ineligible nodes or missing usable comments.
946
+ */
947
+ function documentedPrivateCallable(sourceFile: TsSourceFile, node: TsNode, laterExportedNames: ReadonlySet<string>): DocumentedExportFunction | undefined {
948
+ /**
949
+ * Checks whether `name` refers to a top-level binding handled by a separate export; nested names are independent bindings for private checks.
950
+ *
951
+ * @param name - declared identifier name to test against top-level separate exports
952
+ * @returns True when `node` is top-level in `sourceFile` and `name` is in `laterExportedNames`; otherwise false.
953
+ */
954
+ const isLaterExported = (name: string): boolean => node.parent === sourceFile && laterExportedNames.has(name);
955
+ if (typescriptSyntax.isFunctionDeclaration(node)) {
956
+ const name = node.name?.text;
957
+ return name !== undefined && !hasExportFlag(node) && !isLaterExported(name) ? documentedCallable(sourceFile, node, name, node) : undefined;
958
+ }
959
+ const declaration = soleConstDeclaration(node);
960
+ if (!declaration || hasExportFlag(declaration) || !typescriptSyntax.isIdentifier(declaration.name) || isLaterExported(declaration.name.text)) {
961
+ return undefined;
962
+ }
963
+ return documentedConstantCallable(sourceFile, node, declaration);
964
+ }
965
+
966
+ /**
967
+ * Lists class and object-literal methods with identifier or private-identifier names and callable JSDoc for everyCallable tag checks.
968
+ * Includes static and private methods; excludes constructors, accessors, arrow-valued properties, and computed or literal names.
969
+ * Bare method names use the declaration ordinal to distinguish same-named methods in one file.
970
+ *
971
+ * @param parsed - shared syntax tree searched for qualifying methods
972
+ * @returns Documented methods in source order; empty when the file has none.
973
+ */
974
+ export function documentedMethods(parsed: ParsedScript): DocumentedExportFunction[] {
975
+ return collectDocumented(parsed, documentedMethod);
976
+ }
977
+
978
+ /**
979
+ * Recognizes methods on class declarations with their own export modifier, excluding private, protected and private-identifier methods.
980
+ * The missing-function-documentation check uses this classification to apply exported severity when either everyCallable tag switch is enabled.
981
+ *
982
+ * @param callableNode - shared-parse node inspected for public exported-method status
983
+ * @returns True when the method qualifies for exported severity under these syntax checks.
984
+ */
985
+ export function isPublicExportedClassMethod(callableNode: TsNode): boolean {
986
+ if (!typescriptSyntax.isMethodDeclaration(callableNode) || typescriptSyntax.isPrivateIdentifier(callableNode.name)) {
987
+ return false;
988
+ }
989
+ if (hasNodeModifier(callableNode, typescriptSyntax.SyntaxKind.PrivateKeyword) || hasNodeModifier(callableNode, typescriptSyntax.SyntaxKind.ProtectedKeyword)) {
990
+ return false;
991
+ }
992
+ return typescriptSyntax.isClassDeclaration(callableNode.parent) && hasNodeModifier(callableNode.parent, typescriptSyntax.SyntaxKind.ExportKeyword);
993
+ }
994
+
995
+ /**
996
+ * Projects `node` into a documentation record for an identifier-named or private-identifier method with a usable leading comment.
997
+ *
998
+ * @param sourceFile - parsed TypeScript source file used for comment text and locations
999
+ * @param node - AST node checked for a `MethodDeclaration` with an identifier or private-identifier name
1000
+ * @returns Documentation record for the method, or undefined for other nodes, computed or literal names, or missing usable comments.
1001
+ */
1002
+ function documentedMethod(sourceFile: TsSourceFile, node: TsNode): DocumentedExportFunction | undefined {
1003
+ if (!typescriptSyntax.isMethodDeclaration(node) || (!typescriptSyntax.isIdentifier(node.name) && !typescriptSyntax.isPrivateIdentifier(node.name))) {
1004
+ return undefined;
1005
+ }
1006
+ // Use the unqualified name so identifier-named methods match the names used by the size and missing-doc rules.
1007
+ // The finding fingerprint uses the JSDoc line to distinguish same-named methods documented on different lines.
1008
+ return documentedCallable(sourceFile, node, node.name.text, node);
1009
+ }
1010
+
1011
+ /**
1012
+ * Builds a documentation row from `docHost`'s leading comment and `callable`'s signature.
1013
+ * Prefers a usable `/** ... *\/` JSDoc block (`hasJsDoc: true`), falling back to leading `//` or `/* *\/` comments (`hasJsDoc: false`)
1014
+ * so tag rules can enforce JSDoc contracts instead of letting slash or block comments bypass them.
1015
+ *
1016
+ * @param sourceFile - parsed TypeScript source file supplying comment text and line numbers
1017
+ * @param docHost - AST declaration or statement hosting the leading comment
1018
+ * @param name - callable display name recorded in the returned row
1019
+ * @param callable - signature node supplying identifier and destructured parameters
1020
+ * @returns Documentation record for `docHost`, or undefined when it has no leading comment or only a file overview or section divider.
1021
+ */
1022
+ function documentedCallable(sourceFile: TsSourceFile, docHost: TsNode, name: string, callable: import("typescript").SignatureDeclarationBase): DocumentedExportFunction | undefined {
1023
+ const jsDocs = (docHost as { jsDoc?: readonly import("typescript").JSDoc[] }).jsDoc;
639
1024
  const jsDoc = jsDocs?.[jsDocs.length - 1];
640
- if (!jsDoc) {
1025
+ if (jsDoc && !isOverviewOrDividerJsDoc(sourceFile, docHost, jsDoc)) {
1026
+ return buildDocumentedCallableRecord(sourceFile, name, callable, sourceFile.text.slice(jsDoc.getStart(sourceFile) + 3, jsDoc.getEnd() - 2), true, jsDoc.getStart(sourceFile));
1027
+ }
1028
+ const nonJsDocStart = leadingNonJsDocCommentStart(sourceFile, docHost);
1029
+ if (nonJsDocStart === undefined) {
641
1030
  return undefined;
642
1031
  }
1032
+ return buildDocumentedCallableRecord(sourceFile, name, callable, "", false, nonJsDocStart);
1033
+ }
1034
+
1035
+ /**
1036
+ * Builds one `DocumentedExportFunction` record from an already-resolved leading comment anchor and callable signature.
1037
+ *
1038
+ * @param sourceFile - parsed TypeScript source file supplying text and line numbers
1039
+ * @param name - callable display name used in finding messages and fingerprints
1040
+ * @param callable - signature node supplying declared and destructured parameters
1041
+ * @param docText - JSDoc body text between markers, or empty string for non-JSDoc comments
1042
+ * @param hasJsDoc - true when the comment is a `/** ... *\/` JSDoc block; false for `//` or `/* *\/` comments
1043
+ * @param commentStartPos - zero-based character offset where the leading comment begins
1044
+ * @returns Populated `DocumentedExportFunction` record ready for doc-rule evaluation.
1045
+ */
1046
+ function buildDocumentedCallableRecord(
1047
+ sourceFile: TsSourceFile,
1048
+ name: string,
1049
+ callable: import("typescript").SignatureDeclarationBase,
1050
+ docText: string,
1051
+ hasJsDoc: boolean,
1052
+ commentStartPos: number,
1053
+ ): DocumentedExportFunction {
643
1054
  return {
644
- docText: sourceFile.text.slice(jsDoc.getStart(sourceFile) + 3, jsDoc.getEnd() - 2),
645
- name: node.name.text,
646
- parameterNames: node.parameters
1055
+ docText,
1056
+ hasJsDoc,
1057
+ name,
1058
+ parameterNames: callable.parameters
647
1059
  .map((parameter) => (typescriptSyntax.isIdentifier(parameter.name) ? parameter.name.text : undefined))
648
- .filter((name): name is string => name !== undefined),
649
- line: sourceFile.getLineAndCharacterOfPosition(jsDoc.getStart(sourceFile)).line + 1,
650
- returnTypeText: node.type ? node.type.getText(sourceFile).replace(/\s+/g, " ").trim() : "",
1060
+ .filter((parameterName): parameterName is string => parameterName !== undefined),
1061
+ destructuredParameters: callable.parameters
1062
+ .map((parameter) => destructuredParameterSlot(parameter.name))
1063
+ .filter((slot): slot is DestructuredParameterSlot => slot !== undefined),
1064
+ line: sourceFile.getLineAndCharacterOfPosition(commentStartPos).line + 1,
651
1065
  };
652
1066
  }
1067
+
1068
+ /**
1069
+ * Finds the start offset of a leading `//` or `/* *\/` comment attached to `docHost` when no usable JSDoc block is present.
1070
+ * Ignores file overviews, section dividers, empty comments, and rejected `/** *\/` blocks so missing-doc rules own those declarations.
1071
+ *
1072
+ * @param sourceFile - parsed TypeScript source file supplying text and statement order
1073
+ * @param docHost - declaration or statement carrying the leading trivia
1074
+ * @returns Zero-based character offset where the non-JSDoc comment block starts, or undefined if none qualifies.
1075
+ */
1076
+ function leadingNonJsDocCommentStart(sourceFile: TsSourceFile, docHost: TsNode): number | undefined {
1077
+ const ranges = typescriptSyntax.getLeadingCommentRanges(sourceFile.text, docHost.getFullStart());
1078
+ if (!ranges || ranges.length === 0) {
1079
+ return undefined;
1080
+ }
1081
+ const lastRange = ranges[ranges.length - 1];
1082
+ if (!lastRange) {
1083
+ return undefined;
1084
+ }
1085
+ const lastText = sourceFile.text.slice(lastRange.pos, lastRange.end);
1086
+ if (lastText.startsWith("/**") || isDividerComment(lastText)) {
1087
+ return undefined;
1088
+ }
1089
+ const blockStartPos = contiguousCommentBlockStart(sourceFile.text, ranges, ranges.length - 1);
1090
+ const rawComment = sourceFile.text.slice(blockStartPos, lastRange.end);
1091
+ if (rawComment.replace(/\/\/|\/\*|\*\/|\*/g, "").trim() === "" || isDividerComment(rawComment)) {
1092
+ return undefined;
1093
+ }
1094
+ const gapLines = sourceFile.text.slice(lastRange.end, docHost.getStart(sourceFile)).split(/\r?\n/).slice(1, -1);
1095
+ if (sourceFile.statements[0] === docHost && isFileOverviewComment(rawComment, gapLines)) {
1096
+ return undefined;
1097
+ }
1098
+ return blockStartPos;
1099
+ }
1100
+
1101
+ /**
1102
+ * Walks backward through contiguous `//` line comments ending at `lastIndex` so multi-line slash blocks anchor on their first line.
1103
+ *
1104
+ * @param text - full script text
1105
+ * @param ranges - leading comment trivia ranges returned by TypeScript
1106
+ * @param lastIndex - index of the final leading comment range before the declaration
1107
+ * @returns Zero-based start offset of the contiguous comment block.
1108
+ */
1109
+ function contiguousCommentBlockStart(text: string, ranges: readonly import("typescript").CommentRange[], lastIndex: number): number {
1110
+ const lastRange = ranges[lastIndex];
1111
+ if (!lastRange || lastRange.kind !== typescriptSyntax.SyntaxKind.SingleLineCommentTrivia) {
1112
+ return lastRange?.pos ?? 0;
1113
+ }
1114
+ let startIndex = lastIndex;
1115
+ while (startIndex > 0) {
1116
+ const previous = ranges[startIndex - 1];
1117
+ const current = ranges[startIndex];
1118
+ if (!previous || !current || previous.kind !== typescriptSyntax.SyntaxKind.SingleLineCommentTrivia) {
1119
+ break;
1120
+ }
1121
+ const between = text.slice(previous.end, current.pos);
1122
+ if (/\r?\n\s*\r?\n/.test(between)) {
1123
+ break;
1124
+ }
1125
+ startIndex -= 1;
1126
+ }
1127
+ return ranges[startIndex]?.pos ?? lastRange.pos;
1128
+ }
1129
+
1130
+ /**
1131
+ * Extracts destructured parameter metadata for one object or array binding pattern so stale-tag checks accept standard JSDoc object tags.
1132
+ *
1133
+ * @param parameterName - binding name node from one callable parameter declaration
1134
+ * @returns Destructured slot metadata for object or array patterns, or undefined for ordinary identifier parameters.
1135
+ */
1136
+ function destructuredParameterSlot(parameterName: import("typescript").BindingName): DestructuredParameterSlot | undefined {
1137
+ if (typescriptSyntax.isIdentifier(parameterName)) {
1138
+ return undefined;
1139
+ }
1140
+ if (typescriptSyntax.isArrayBindingPattern(parameterName)) {
1141
+ return { keys: [], hasOpenKeys: true };
1142
+ }
1143
+ const keys: string[] = [];
1144
+ let hasOpenKeys = false;
1145
+ for (const element of parameterName.elements) {
1146
+ if (element.dotDotDotToken) {
1147
+ hasOpenKeys = true;
1148
+ continue;
1149
+ }
1150
+ const keyName = destructuredElementKey(element);
1151
+ if (keyName === undefined) {
1152
+ hasOpenKeys = true;
1153
+ } else {
1154
+ keys.push(keyName);
1155
+ }
1156
+ }
1157
+ return { keys, hasOpenKeys };
1158
+ }
1159
+
1160
+ /**
1161
+ * Reads the static property key bound by one object destructuring element.
1162
+ *
1163
+ * @param element - object binding element whose property name or shorthand identifier is inspected
1164
+ * @returns The static key string when known syntactically, or undefined for computed property keys.
1165
+ */
1166
+ function destructuredElementKey(element: import("typescript").BindingElement): string | undefined {
1167
+ if (element.propertyName) {
1168
+ if (typescriptSyntax.isIdentifier(element.propertyName) || typescriptSyntax.isStringLiteral(element.propertyName) || typescriptSyntax.isNumericLiteral(element.propertyName)) {
1169
+ return element.propertyName.text;
1170
+ }
1171
+ return undefined;
1172
+ }
1173
+ return typescriptSyntax.isIdentifier(element.name) ? element.name.text : undefined;
1174
+ }
1175
+
1176
+ /**
1177
+ * Checks whether `jsDoc` is a section divider or a file overview attached to the first statement, excluding it as callable documentation.
1178
+ *
1179
+ * @param sourceFile - parsed TypeScript source file used for comment text, intervening lines, and first-statement identity
1180
+ * @param docHost - declaration or statement carrying `jsDoc`
1181
+ * @param jsDoc - TypeScript JSDoc node attached to `docHost`
1182
+ * @returns True when `jsDoc` is a divider comment or the file's leading overview block; otherwise false.
1183
+ */
1184
+ function isOverviewOrDividerJsDoc(sourceFile: TsSourceFile, docHost: TsNode, jsDoc: import("typescript").JSDoc): boolean {
1185
+ const commentText = sourceFile.text.slice(jsDoc.getStart(sourceFile), jsDoc.getEnd());
1186
+ if (isDividerComment(commentText)) {
1187
+ return true;
1188
+ }
1189
+ const gapLines = sourceFile.text.slice(jsDoc.getEnd(), docHost.getStart(sourceFile)).split(/\r?\n/).slice(1, -1);
1190
+ return sourceFile.statements[0] === docHost && isFileOverviewComment(commentText, gapLines);
1191
+ }
1192
+
1193
+ /**
1194
+ * Reports whether `callableNode` requires a return description in missing-doc hints.
1195
+ * Every function-like declaration other than constructors and `set` accessors requires an explicit `@returns` contract, including `void`.
1196
+ *
1197
+ * @param callableNode - AST node inspected by the missing-function-documentation message builder
1198
+ * @returns True for functions, methods, arrows, and getters; false for non-callables, constructors, and setters.
1199
+ */
1200
+ export function isCallableReturningValue(callableNode: TsNode): boolean {
1201
+ return (
1202
+ typescriptSyntax.isFunctionLike(callableNode) &&
1203
+ !typescriptSyntax.isConstructorDeclaration(callableNode) &&
1204
+ !typescriptSyntax.isSetAccessorDeclaration(callableNode)
1205
+ );
1206
+ }