@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
@@ -0,0 +1,1206 @@
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
+ import { createRequire } from "node:module";
7
+ import { commentRecords, isDividerComment, isFileOverviewComment } from "./comment-scanner.ts";
8
+ import type { RunDiagnostic } from "./types.ts";
9
+
10
+ // Loaded via createRequire because typescript ships as CommonJS; usage stays bounded to syntax
11
+ // walking - no type checker, program, language service, or emit (ADR-012).
12
+ const require = createRequire(import.meta.url);
13
+ const typescriptSyntax = require("typescript") as typeof import("typescript");
14
+
15
+ type TsSourceFile = import("typescript").SourceFile;
16
+ type TsNode = import("typescript").Node;
17
+ type TsDiagnostic = import("typescript").DiagnosticWithLocation;
18
+
19
+ // Minimal file identity the parser needs: the display path picks the grammar and labels
20
+ // diagnostics; the script flag keeps config/text inputs from ever paying parser cost.
21
+ export interface ParsedScriptInput {
22
+ displayPath: string;
23
+ isScript: boolean;
24
+ }
25
+
26
+ // One parse result shared by every downstream consumer within a single analysis run.
27
+ export interface ParsedScript {
28
+ sourceFile: TsSourceFile;
29
+ diagnostics: RunDiagnostic[];
30
+ }
31
+
32
+ /*
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.
35
+ */
36
+ interface ParsedSyntaxIndex {
37
+ callablePoints: CallableMatchPoint[];
38
+ // Callables only the size and complexity rules measure; every other block rule reads `callablePoints` alone.
39
+ measuredOnlyPoints: CallableMatchPoint[];
40
+ }
41
+
42
+ const parsedSyntaxIndexes = new WeakMap<ParsedScript, ParsedSyntaxIndex>();
43
+
44
+ // `createSourceFile` recovers from syntax errors and records them on an internal field; this
45
+ // narrow extension types that field without widening the public TypeScript surface.
46
+ interface ParsedSourceFileWithDiagnostics extends TsSourceFile {
47
+ parseDiagnostics: TsDiagnostic[];
48
+ }
49
+
50
+ // Test-visible parse counter backing the one-parse-per-script assertion; never drives behavior.
51
+ let parseCount = 0;
52
+
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
+ */
59
+ export function parsedScriptParseCount(): number {
60
+ return parseCount;
61
+ }
62
+
63
+ /**
64
+ * Parses one script into the shared boundary result. Non-script inputs return undefined so a
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.
67
+ *
68
+ * @param file - display path plus the script flag from discovery; a false script flag skips parsing
69
+ * @param source - decoded file text; empty script text produces a source file with no diagnostics
70
+ * @returns - shared parse result. No diagnostics means a clean parse. Undefined means the script flag was false.
71
+ */
72
+ export function parseScript(file: ParsedScriptInput, source: string): ParsedScript | undefined {
73
+ // Config and text inputs do not enter the script parser, so callers receive no parse result.
74
+ if (!file.isScript) {
75
+ return undefined;
76
+ }
77
+ parseCount += 1;
78
+ const parsedSourceFile = typescriptSyntax.createSourceFile(file.displayPath, source, typescriptSyntax.ScriptTarget.Latest, true, scriptKindFor(file.displayPath)) as ParsedSourceFileWithDiagnostics;
79
+ const firstParseError = parsedSourceFile.parseDiagnostics[0];
80
+ return {
81
+ sourceFile: parsedSourceFile,
82
+ // One report entry per malformed file keeps diagnostics proportional to affected files.
83
+ diagnostics: firstParseError
84
+ ? [summarizeParseErrors(file, parsedSourceFile, firstParseError, parsedSourceFile.parseDiagnostics.length)]
85
+ : [],
86
+ };
87
+ }
88
+
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
+ */
158
+ export function scriptKindFor(path: string): import("typescript").ScriptKind {
159
+ if (path.endsWith(".tsx")) {
160
+ return typescriptSyntax.ScriptKind.TSX;
161
+ }
162
+ if (path.endsWith(".jsx")) {
163
+ return typescriptSyntax.ScriptKind.JSX;
164
+ }
165
+ if (path.endsWith(".js") || path.endsWith(".mjs") || path.endsWith(".cjs")) {
166
+ return typescriptSyntax.ScriptKind.JS;
167
+ }
168
+ return typescriptSyntax.ScriptKind.TS;
169
+ }
170
+
171
+ /**
172
+ * Builds the single parse-error entry reported for a source file.
173
+ * Multiple parser errors retain their count and first location so one malformed file cannot flood the report.
174
+ *
175
+ * @param file - discovered source metadata used for the reported path
176
+ * @param sourceFile - parser output used to translate the first error offset into a source line
177
+ * @param firstParseError - first parser error; a missing offset falls back to line 1
178
+ * @param parseErrorCount - total errors in this file; callers provide at least one
179
+ * @returns one diagnostic for the file; reports parser errors without throwing
180
+ */
181
+ function summarizeParseErrors(file: ParsedScriptInput, sourceFile: TsSourceFile, firstParseError: TsDiagnostic, parseErrorCount: number): RunDiagnostic {
182
+ // TypeScript can omit an offset for malformed input; line 1 remains a usable report anchor.
183
+ const firstErrorLine = firstParseError.start === undefined
184
+ ? 1
185
+ : sourceFile.getLineAndCharacterOfPosition(firstParseError.start).line + 1;
186
+ const firstErrorMessage = typescriptSyntax.flattenDiagnosticMessageText(firstParseError.messageText, " ");
187
+ // A single error keeps the established wording; larger sets expose their count without repeated entries.
188
+ const parseErrorMessage = parseErrorCount === 1
189
+ ? `TypeScript syntax error: ${firstErrorMessage}`
190
+ : `TypeScript syntax errors: ${parseErrorCount} diagnostics in this file; first: ${firstErrorMessage}`;
191
+ return {
192
+ diagnosticType: "parse-error",
193
+ message: parseErrorMessage,
194
+ filePath: file.displayPath,
195
+ line: firstErrorLine,
196
+ };
197
+ }
198
+
199
+ /*
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.
203
+ */
204
+ export interface CallableMatchPoint {
205
+ lineIndex: number;
206
+ // Zero-based first line of the declaration (modifiers included, docs excluded) so split headers keep doc lookup intact.
207
+ declarationLineIndex: number;
208
+ // Zero-based line of the callable's final token, preferred over brace walking so `{}` in defaults cannot truncate bodies.
209
+ endLineIndex: number;
210
+ name: string;
211
+ params: string;
212
+ parameterCount: number;
213
+ isTestCallable: boolean;
214
+ // Syntax-backed visibility keeps split-line modifiers and file-level re-exports scoped to the
215
+ // declaration that owns them without moving the legacy name-line finding anchor.
216
+ isDirectlyExported: boolean;
217
+ isExplicitlyPublic: boolean;
218
+ isModuleScoped: boolean;
219
+ // False for signature-only declarations: interface and type-literal methods, overload
220
+ // signatures, and abstract or ambient members. The block rules use this instead of guessing
221
+ // from text, because a multi-line signature reads like an implementation on its first line.
222
+ hasBody: boolean;
223
+ // True only for a declaration carrying the `override` modifier: its base class chose the name.
224
+ isOverride: boolean;
225
+ // Shared-parse node whose parameters and body belong to this stable analysed block.
226
+ callableNode: TsNode;
227
+ }
228
+
229
+ /**
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.
233
+ *
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
236
+ */
237
+ export function callableMatchPoints(parsed: ParsedScript): CallableMatchPoint[] {
238
+ return parsedSyntaxIndex(parsed).callablePoints;
239
+ }
240
+
241
+ /**
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
248
+ */
249
+ export function measuredOnlyCallablePoints(parsed: ParsedScript): CallableMatchPoint[] {
250
+ return parsedSyntaxIndex(parsed).measuredOnlyPoints;
251
+ }
252
+
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
+ */
260
+ function parsedSyntaxIndex(parsed: ParsedScript): ParsedSyntaxIndex {
261
+ const cachedIndex = parsedSyntaxIndexes.get(parsed);
262
+ // Multiple rule consumers reach the same file, so a completed projection is reused verbatim.
263
+ if (cachedIndex) {
264
+ return cachedIndex;
265
+ }
266
+ const callablePointsByLine = new Map<number, CallableMatchPoint>();
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 => {
275
+ recordCallablePoint(callablePointsByLine, matchPointFor(parsed.sourceFile, node));
276
+ const measuredOnlyPoint = measuredOnlyPointFor(parsed.sourceFile, node);
277
+ if (measuredOnlyPoint) {
278
+ measuredOnlyPoints.push(measuredOnlyPoint);
279
+ }
280
+ node.forEachChild(visitSyntaxNode);
281
+ };
282
+ parsed.sourceFile.forEachChild(visitSyntaxNode);
283
+ const syntaxIndex: ParsedSyntaxIndex = {
284
+ callablePoints: [...callablePointsByLine.values()].sort((left, right) => left.lineIndex - right.lineIndex),
285
+ measuredOnlyPoints,
286
+ };
287
+ parsedSyntaxIndexes.set(parsed, syntaxIndex);
288
+ return syntaxIndex;
289
+ }
290
+
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
+ */
298
+ function recordCallablePoint(callablePointsByLine: Map<number, CallableMatchPoint>, callablePoint: CallableMatchPoint | undefined): void {
299
+ // Most syntax nodes are not callable declarations, so they add no report block.
300
+ if (!callablePoint) {
301
+ return;
302
+ }
303
+ const existingPoint = callablePointsByLine.get(callablePoint.lineIndex);
304
+ // A test callback replaces a non-test point on the same line. Otherwise the first recorded point stays.
305
+ if (!existingPoint || (callablePoint.isTestCallable && !existingPoint.isTestCallable)) {
306
+ callablePointsByLine.set(callablePoint.lineIndex, callablePoint);
307
+ }
308
+ }
309
+
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.
317
+ */
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);
321
+ }
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);
324
+ }
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);
328
+ }
329
+ if (typescriptSyntax.isVariableDeclaration(node)) {
330
+ return variableInitializerPoint(sourceFile, node);
331
+ }
332
+ if (typescriptSyntax.isCallExpression(node)) {
333
+ return testCallbackPoint(sourceFile, node);
334
+ }
335
+ return undefined;
336
+ }
337
+
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);
347
+ }
348
+
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)) {
358
+ return undefined;
359
+ }
360
+ const initializer = node.initializer ? withoutParentheses(node.initializer) : undefined;
361
+ if (!isFunctionValue(initializer)) {
362
+ return undefined;
363
+ }
364
+ return declarationPoint(sourceFile, node.name.getStart(sourceFile), initializer, node.name.text, initializer.parameters);
365
+ }
366
+
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;
378
+ }
379
+ const initializer = withoutParentheses(node.initializer);
380
+ if (!isFunctionValue(initializer)) {
381
+ return undefined;
382
+ }
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);
386
+ }
387
+
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)) {
397
+ return undefined;
398
+ }
399
+ const right = withoutParentheses(node.right);
400
+ if (!isFunctionValue(right)) {
401
+ return undefined;
402
+ }
403
+ return declarationPoint(sourceFile, node.left.getStart(sourceFile), right, compactText(sourceFile, node.left), right.parameters);
404
+ }
405
+
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;
417
+ }
418
+ const name = typescriptSyntax.isFunctionExpression(callee) && callee.name ? callee.name.text : "<iife>";
419
+ return declarationPoint(sourceFile, callee.getStart(sourceFile), callee, name, callee.parameters);
420
+ }
421
+
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));
430
+ }
431
+
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;
463
+ }
464
+ if (typescriptSyntax.isBinaryExpression(owner) && owner.operatorToken.kind === typescriptSyntax.SyntaxKind.EqualsToken && owner.right === objectLiteral) {
465
+ return compactText(sourceFile, owner.left);
466
+ }
467
+ return undefined;
468
+ }
469
+
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
+ */
505
+ function declarationPoint(sourceFile: TsSourceFile, position: number, callableNode: TsNode, name: string, parameters: readonly TsNode[]): CallableMatchPoint {
506
+ const visibilityNode = callableVisibilityNode(callableNode);
507
+ const isDirectlyExported = hasNodeModifier(visibilityNode, typescriptSyntax.SyntaxKind.ExportKeyword);
508
+ const lineIndex = sourceFile.getLineAndCharacterOfPosition(position).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.
511
+ const declarationStartLine = sourceFile.getLineAndCharacterOfPosition(visibilityNode.getStart(sourceFile)).line;
512
+ return {
513
+ lineIndex,
514
+ declarationLineIndex: Math.min(declarationStartLine, lineIndex),
515
+ endLineIndex: sourceFile.getLineAndCharacterOfPosition(callableNode.getEnd()).line,
516
+ name,
517
+ params: parametersText(sourceFile, parameters),
518
+ parameterCount: parameters.length,
519
+ isTestCallable: false,
520
+ isDirectlyExported,
521
+ isExplicitlyPublic: isDirectlyExported || hasNodeModifier(visibilityNode, typescriptSyntax.SyntaxKind.PublicKeyword),
522
+ isModuleScoped: visibilityNode.parent === sourceFile,
523
+ hasBody: callableNodeHasBody(callableNode),
524
+ isOverride: hasNodeModifier(visibilityNode, typescriptSyntax.SyntaxKind.OverrideKeyword),
525
+ callableNode,
526
+ };
527
+ }
528
+
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
+ */
535
+ function callableVisibilityNode(callableNode: TsNode): TsNode {
536
+ const declaration = callableNode.parent;
537
+ if (!typescriptSyntax.isVariableDeclaration(declaration)) {
538
+ return callableNode;
539
+ }
540
+ const declarationList = declaration.parent;
541
+ if (!typescriptSyntax.isVariableDeclarationList(declarationList)) {
542
+ return callableNode;
543
+ }
544
+ const statement = declarationList.parent;
545
+ return typescriptSyntax.isVariableStatement(statement) ? statement : callableNode;
546
+ }
547
+
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
+ */
555
+ function hasNodeModifier(node: TsNode, modifierKind: import("typescript").SyntaxKind): boolean {
556
+ const modifiers = typescriptSyntax.canHaveModifiers(node) ? typescriptSyntax.getModifiers(node) : undefined;
557
+ return modifiers?.some((modifier) => modifier.kind === modifierKind) === true;
558
+ }
559
+
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
+ */
567
+ function callableNodeHasBody(callableNode: TsNode): boolean {
568
+ return (callableNode as { body?: unknown }).body !== undefined;
569
+ }
570
+
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
+ */
578
+ function variableInitializerPoint(sourceFile: TsSourceFile, node: import("typescript").VariableDeclaration): CallableMatchPoint | undefined {
579
+ if (!typescriptSyntax.isIdentifier(node.name) || !node.initializer) {
580
+ return undefined;
581
+ }
582
+ if (!typescriptSyntax.isArrowFunction(node.initializer) && !typescriptSyntax.isFunctionExpression(node.initializer)) {
583
+ return undefined;
584
+ }
585
+ const declarationList = node.parent;
586
+ if (!typescriptSyntax.isVariableDeclarationList(declarationList) || (declarationList.flags & typescriptSyntax.NodeFlags.Const) === 0 && (declarationList.flags & typescriptSyntax.NodeFlags.Let) === 0) {
587
+ return undefined;
588
+ }
589
+ return declarationPoint(sourceFile, node.name.getStart(sourceFile), node.initializer, node.name.text, node.initializer.parameters);
590
+ }
591
+
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
+ */
600
+ function testCallbackPoint(sourceFile: TsSourceFile, node: import("typescript").CallExpression): CallableMatchPoint | undefined {
601
+ if (!typescriptSyntax.isIdentifier(node.expression) || (node.expression.text !== "test" && node.expression.text !== "it")) {
602
+ return undefined;
603
+ }
604
+ const [title, callback] = node.arguments;
605
+ if (!title || !typescriptSyntax.isStringLiteralLike(title) || !callback) {
606
+ return undefined;
607
+ }
608
+ if (!typescriptSyntax.isArrowFunction(callback) && !typescriptSyntax.isFunctionExpression(callback)) {
609
+ return undefined;
610
+ }
611
+ const lineIndex = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line;
612
+ return {
613
+ lineIndex,
614
+ // Keep the declaration anchor at the call start when the callback begins on a later line.
615
+ declarationLineIndex: lineIndex,
616
+ endLineIndex: sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line,
617
+ name: title.text,
618
+ params: parametersText(sourceFile, callback.parameters),
619
+ parameterCount: callback.parameters.length,
620
+ isTestCallable: true,
621
+ isDirectlyExported: false,
622
+ isExplicitlyPublic: false,
623
+ isModuleScoped: false,
624
+ hasBody: true,
625
+ isOverride: false,
626
+ callableNode: callback,
627
+ };
628
+ }
629
+
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
+ */
638
+ function parametersText(sourceFile: TsSourceFile, parameters: readonly TsNode[]): string {
639
+ return parameters
640
+ .map((parameter) => sourceFile.text.slice(parameter.getStart(sourceFile), parameter.getEnd()))
641
+ .join(", ")
642
+ .replace(/\r?\n/g, " ");
643
+ }
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
+
691
+ /*
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.
698
+ */
699
+ export interface DocumentedExportFunction {
700
+ docText: string;
701
+ hasJsDoc: boolean;
702
+ name: string;
703
+ parameterNames: string[];
704
+ destructuredParameters: DestructuredParameterSlot[];
705
+ line: number;
706
+ }
707
+
708
+ /**
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.
711
+ *
712
+ * @param parsed - shared syntax tree searched for qualifying function declarations
713
+ * @returns Documented exported functions in source order; empty when the file has none.
714
+ */
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[] {
738
+ const results: DocumentedExportFunction[] = [];
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
+ */
745
+ const visit = (node: TsNode): void => {
746
+ const documented = project(parsed.sourceFile, node);
747
+ if (documented) {
748
+ results.push(documented);
749
+ }
750
+ node.forEachChild(visit);
751
+ };
752
+ parsed.sourceFile.forEachChild(visit);
753
+ return results;
754
+ }
755
+
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
+ */
764
+ function documentedExportFunction(sourceFile: TsSourceFile, node: TsNode): DocumentedExportFunction | undefined {
765
+ if (!typescriptSyntax.isFunctionDeclaration(node) || !node.name) {
766
+ return undefined;
767
+ }
768
+ const flags = typescriptSyntax.getCombinedModifierFlags(node);
769
+ if ((flags & typescriptSyntax.ModifierFlags.Export) === 0 || (flags & typescriptSyntax.ModifierFlags.Default) !== 0) {
770
+ return undefined;
771
+ }
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;
1024
+ const jsDoc = jsDocs?.[jsDocs.length - 1];
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) {
1030
+ return undefined;
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 {
1054
+ return {
1055
+ docText,
1056
+ hasJsDoc,
1057
+ name,
1058
+ parameterNames: callable.parameters
1059
+ .map((parameter) => (typescriptSyntax.isIdentifier(parameter.name) ? parameter.name.text : undefined))
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,
1065
+ };
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
+ }