@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,5 +1,5 @@
1
1
  // Type-safety and reliability rule packs: TS directive rationales, non-null assertions, double
2
- // casts, exported `any`, async forEach, floating promises, non-Error throws, useless catches,
2
+ // casts, exported `any`, async forEach, non-Error throws, useless catches,
3
3
  // swallowed catches. Each rule emits findings in the stable, deterministic per-line/per-source order.
4
4
  import { hasSuppressionRationale } from "./comment-rules.ts";
5
5
  import { type SourceFile } from "./discovery.ts";
@@ -7,26 +7,46 @@ import { makeFinding } from "./findings.ts";
7
7
  import { byteLine } from "./text-scans.ts";
8
8
  import type { Finding } from "./types.ts";
9
9
 
10
- // Four-rule TypeScript safety pass: directive comment, non-null assertion, double cast, exported any.
11
- // Stable, deterministic ordering keeps the per-line findings in a known sequence.
12
- export function analyseTypeSafetyLine(file: SourceFile, line: string, codeLine: string, lineNumber: number, findings: Finding[]): void {
13
- pushTsDirectiveFinding(file, line, lineNumber, findings);
10
+ /**
11
+ * Check a TypeScript line for directive rationale, non-null assertions, double casts, and exported any in that stable order.
12
+ *
13
+ * @param file - Source file supplying the location path for emitted findings.
14
+ * @param line - Raw source line inspected for directive and cast rationale comments.
15
+ * @param codeLine - Stripped code text checked for assertions, double casts, and exported any.
16
+ * @param lineNumber - One-based line number used for finding locations and preceding comment lookup.
17
+ * @param findings - Caller-owned array that receives appended findings.
18
+ * @param sourceLines - Raw file lines used to inspect preceding comments when supplied.
19
+ * @param trackingTokens - Extra patterns that add accepted rationale tokens.
20
+ * @returns Nothing. Appends matching findings to the supplied findings array.
21
+ */
22
+ export function analyseTypeSafetyLine(file: SourceFile, line: string, codeLine: string, lineNumber: number, findings: Finding[], sourceLines: readonly string[] = [], trackingTokens: readonly RegExp[] = []): void {
23
+ pushTsDirectiveFinding(file, line, lineNumber, findings, sourceLines, trackingTokens);
14
24
  pushNonNullAssertionFindings(file, codeLine, lineNumber, findings);
15
25
  pushDoubleCastFindings(file, line, codeLine, lineNumber, findings);
16
26
  pushExportedAnyFinding(file, codeLine, lineNumber, findings);
17
27
  }
18
28
 
19
- // Three reliability rules per line: async-forEach, floating-promise, non-Error throw. Order is
20
- // the stable contract - reshuffling shifts per-block emission and churns baselines.
29
+ /**
30
+ * Check a code line for async forEach callbacks and non-Error throws in order for stable emission.
31
+ *
32
+ * @param file - Source file supplying the reported display path.
33
+ * @param codeLine - Stripped code line scanned for async forEach and non-Error throws.
34
+ * @param lineNumber - One-based line number attached to any emitted finding.
35
+ * @param findings - Caller-owned array that receives appended findings.
36
+ * @returns Nothing. Appends matching findings to findings.
37
+ */
21
38
  export function analyseReliabilityLine(file: SourceFile, codeLine: string, lineNumber: number, findings: Finding[]): void {
22
39
  pushAsyncForEachFinding(file, codeLine, lineNumber, findings);
23
- pushFloatingPromiseFinding(file, codeLine, lineNumber, findings);
24
40
  pushNonErrorThrowFinding(file, codeLine, lineNumber, findings);
25
41
  }
26
42
 
27
- /*
28
- * `catch (e) { throw e; }` patterns. The backreference enforces "same binding name" so a real
29
- * `catch (e) { throw new Wrapped(e); }` does not trip. Reports the stable `waste.useless-catch` finding.
43
+ /**
44
+ * Flag catches that only rethrow their untyped identifier binding because they add no handling; wrapped rethrows do not match.
45
+ *
46
+ * @param file - Source file supplying the display path for each finding.
47
+ * @param source - Source text scanned for catch text and byte-line offsets.
48
+ * @param findings - Caller-owned array that receives a stable waste.useless-catch finding for each match.
49
+ * @returns Nothing. Appends a stable waste.useless-catch finding for each match.
30
50
  */
31
51
  export function analyseUselessCatches(file: SourceFile, source: string, findings: Finding[]): void {
32
52
  for (const match of source.matchAll(/\bcatch\s*\(\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\)\s*\{\s*throw\s+\1\s*;?\s*\}/g)) {
@@ -47,16 +67,21 @@ export function analyseUselessCatches(file: SourceFile, source: string, findings
47
67
  }
48
68
  }
49
69
 
50
- /*
51
- * Empty / comment-only catch bodies. Strips comments before testing, because a catch body with
52
- * only `// intentional` is still a swallowed catch but a real `console.error` is not. Reports
53
- * the stable `waste.swallowed-catch` finding.
70
+ /**
71
+ * Flag empty or comment-only catches because a discarded error can hide a failure unless the comment explains the ignore.
72
+ *
73
+ * @param file - Source file supplying the display path for each finding.
74
+ * @param rawSource - Original source used to read catch comments and locate matches.
75
+ * @param codeSource - Corresponding code text used to locate catches and check their bodies.
76
+ * @param findings - Caller-owned array that receives stable waste.swallowed-catch findings.
77
+ * @param trackingTokens - Extra patterns for rationale references. Omit to use the built-in heuristic alone.
78
+ * @returns Nothing. Appends a finding for each matching catch without a recognised rationale.
54
79
  */
55
- export function analyseSwallowedCatches(file: SourceFile, rawSource: string, codeSource: string, findings: Finding[]): void {
80
+ export function analyseSwallowedCatches(file: SourceFile, rawSource: string, codeSource: string, findings: Finding[], trackingTokens: readonly RegExp[] = []): void {
56
81
  for (const match of codeSource.matchAll(/\bcatch\s*(?:\(([^)]*)\))?\s*\{([\s\S]*?)\}/g)) {
57
82
  const body = match[2] ?? "";
58
83
  const rawBody = rawCatchBody(rawSource, codeSource, match);
59
- if (!isSwallowedCatchBody(body) || hasIntentionalCatchRationale(rawBody)) {
84
+ if (!isSwallowedCatchBody(body) || hasIntentionalCatchRationale(rawBody, trackingTokens)) {
60
85
  continue;
61
86
  }
62
87
  const binding = (match[1] ?? "").trim();
@@ -76,7 +101,14 @@ export function analyseSwallowedCatches(file: SourceFile, rawSource: string, cod
76
101
  }
77
102
  }
78
103
 
79
- // Maps a catch-body match from masked code back to raw source so rationale comments remain visible.
104
+ /**
105
+ * Map a catch-body match from masked code back to raw source so rationale comments remain visible.
106
+ *
107
+ * @param rawSource - Original source text that must share offsets with codeSource.
108
+ * @param codeSource - Masked code text that must share offsets with rawSource.
109
+ * @param match - Regex match selecting the catch block whose braces bound the body.
110
+ * @returns Raw catch body slice, or empty text when the brace range is invalid or empty.
111
+ */
80
112
  function rawCatchBody(rawSource: string, codeSource: string, match: RegExpMatchArray): string {
81
113
  const start = match.index ?? 0;
82
114
  const openBrace = codeSource.indexOf("{", start);
@@ -84,29 +116,38 @@ function rawCatchBody(rawSource: string, codeSource: string, match: RegExpMatchA
84
116
  return openBrace === -1 || closeBrace <= openBrace ? "" : rawSource.slice(openBrace + 1, closeBrace);
85
117
  }
86
118
 
87
- // Comment-only catches are acceptable when the comment gives a rationale such as "already closed",
88
- // "cache write failure is non-fatal", or "composition continues"; placeholders still surface.
89
- // The bare-token alternatives (`ignore`, `ignored`, `cleanup`, `teardown`, `noop`, `no-op`) match
90
- // the most common idioms for documented teardown swallows. `silent` is deliberately NOT included -
91
- // real swallowed-error defects in goat-flow's dashboard-projects.ts use `/* silent */` and must
92
- // continue to fire. Deferred-work markers are also excluded - that flavour of placeholder is not
93
- // "intentional swallow."
94
- function hasIntentionalCatchRationale(body: string): boolean {
95
- return (
96
- /(?:\/\/|\/\*)/.test(body) &&
97
- (hasSuppressionRationale(body) ||
98
- /\b(?:already (?:closed|dead|gone)|optional|best effort|missing|unreadable|not a directory|doesn't exist|not available|non-fatal|cache write failure|composition continues|try next location|server unavailable|must not affect|explicit launch|malformed messages|template missing|sets [A-Za-z_$][A-Za-z0-9_$]* = false|skip agents? that fail|ignored?|cleanup|teardown|noop|no-op)\b/i.test(body))
99
- );
119
+ /**
120
+ * Check a catch body's comments for signs of intent; a bare one-word block comment needs a rationale match to qualify.
121
+ *
122
+ * @param body - Raw catch body whose line and block comments are inspected for intent.
123
+ * @param trackingTokens - Extra patterns used to recognise tracking references in comment text.
124
+ * @returns True for a rationale match, at least two words, or a recognised intent marker; false for blank text or TODO/FIXME/XXX.
125
+ */
126
+ function hasIntentionalCatchRationale(body: string, trackingTokens: readonly RegExp[]): boolean {
127
+ const commentText = (body.match(/\/\/[^\n]*|\/\*[\s\S]*?\*\//g) ?? []).map((comment) => comment.replace(/^\/\/+|^\/\*+|\*+\/$/g, "")).join(" ");
128
+ // Reject placeholder markers regardless of letter case so `// todo: retry later` never counts as an intentional catch rationale.
129
+ if (commentText.trim() === "" || /\b(?:TODO|FIXME|XXX)\b/i.test(commentText)) {
130
+ return false;
131
+ }
132
+ const words = commentText.match(/[A-Za-z][A-Za-z'-]*/g) ?? [];
133
+ return hasSuppressionRationale(commentText, trackingTokens) || words.length >= 2 || /\b(?:ignored?|no-?op|cleanup|teardown|best[- ]effort|non[- ]fatal|optional)\b/i.test(commentText);
100
134
  }
101
135
 
102
- /*
103
- * `@ts-ignore` / `@ts-expect-error` without an explanatory note. `tsDirectiveWithoutRationale`
104
- * applies the rationale heuristic. Reports the stable `modernisation.ts-comment-without-rationale`
105
- * finding.
136
+ /**
137
+ * Flag @ts-ignore and @ts-expect-error without a recognised reason on the line or in the line comments directly above it.
138
+ *
139
+ * @param file - Source file supplying the display path for the finding.
140
+ * @param line - Raw source line to check for a directive and its suffix rationale.
141
+ * @param lineNumber - Source line used to locate the directive and look up preceding comments.
142
+ * @param findings - Caller-owned array that receives the stable modernisation.ts-comment-without-rationale finding.
143
+ * @param sourceLines - Raw file lines used to check comments immediately above the directive.
144
+ * @param trackingTokens - Additional patterns accepted as tracking references in the rationale.
145
+ * @returns Nothing. Appends a finding only when a directive lacks a recognised rationale.
106
146
  */
107
- function pushTsDirectiveFinding(file: SourceFile, line: string, lineNumber: number, findings: Finding[]): void {
108
- const directive = tsDirectiveWithoutRationale(line);
109
- if (!directive) {
147
+ function pushTsDirectiveFinding(file: SourceFile, line: string, lineNumber: number, findings: Finding[], sourceLines: readonly string[], trackingTokens: readonly RegExp[]): void {
148
+ const directive = tsDirectiveWithoutRationale(line, trackingTokens);
149
+ // A recognised rationale in the contiguous line comments above the directive suppresses this finding.
150
+ if (!directive || hasDirectiveRationale(lineCommentsAbove(sourceLines, lineNumber - 1), trackingTokens)) {
110
151
  return;
111
152
  }
112
153
  findings.push(
@@ -118,14 +159,21 @@ function pushTsDirectiveFinding(file: SourceFile, line: string, lineNumber: numb
118
159
  severity: "warning",
119
160
  pillar: "modernisation",
120
161
  confidence: "medium",
121
- remediation: "Add a short reason after the directive or remove the suppression.",
162
+ remediation: "Add a short reason on the directive line or in the `//` comment lines directly above it, or remove the suppression.",
122
163
  metadata: { directive: directive.directive },
123
164
  }),
124
165
  );
125
166
  }
126
167
 
127
- // Walks every `foo.bar!` non-null assertion on the line. The lookahead enforces a real expression
128
- // boundary so `!=` doesn't get misread. Reports `modernisation.non-null-assertion` with stable metadata.
168
+ /**
169
+ * Scan codeLine for identifier and dotted-property assertions at recognised boundaries to avoid reading != as an assertion.
170
+ *
171
+ * @param file - Source file supplying the display path for each finding.
172
+ * @param codeLine - Code text scanned for non-null assertion operators.
173
+ * @param lineNumber - One-based line number used for each finding location.
174
+ * @param findings - Caller-owned array receiving a stable modernisation.non-null-assertion finding per match.
175
+ * @returns Nothing. Appends a stable modernisation.non-null-assertion finding to findings per match.
176
+ */
129
177
  function pushNonNullAssertionFindings(file: SourceFile, codeLine: string, lineNumber: number, findings: Finding[]): void {
130
178
  for (const match of codeLine.matchAll(/\b([A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*)!(?=\.|\[|\)|,|;|\s+(?:as|in|instanceof)\b|\s*$)/g)) {
131
179
  const expression = match[1] ?? "";
@@ -146,9 +194,16 @@ function pushNonNullAssertionFindings(file: SourceFile, codeLine: string, lineNu
146
194
  }
147
195
  }
148
196
 
149
- // `as unknown as Foo` and `as any as Foo` double-cast patterns. Why: the rationale branch keeps
150
- // boundary casts visible without scoring a documented TS2352/validator hop like an unexplained
151
- // bypass because typed parser migrations often land later; invariant: never throws and emits stable metadata.
197
+ /**
198
+ * Scan codeLine for double casts through unknown or any; a recognised rationale lowers severity to advisory to preserve visibility.
199
+ *
200
+ * @param file - Source file supplying the display path for each finding.
201
+ * @param rawLine - Raw source line inspected for an inline trust-boundary rationale comment.
202
+ * @param codeLine - Stripped code text scanned for double casts through unknown or any.
203
+ * @param lineNumber - One-based line number used for the finding location.
204
+ * @param findings - Caller-owned array receiving a modernisation.double-cast finding with stable metadata per match.
205
+ * @returns Nothing. Appends a modernisation.double-cast finding with stable metadata for each match.
206
+ */
152
207
  function pushDoubleCastFindings(file: SourceFile, rawLine: string, codeLine: string, lineNumber: number, findings: Finding[]): void {
153
208
  for (const match of codeLine.matchAll(/\bas\s+(unknown|any)\s+as\s+([^;,\n]+)/g)) {
154
209
  const sourceType = match[1] ?? "";
@@ -170,7 +225,12 @@ function pushDoubleCastFindings(file: SourceFile, rawLine: string, codeLine: str
170
225
  }
171
226
  }
172
227
 
173
- // Accepts only inline comments that name the trust boundary or validation reason for the cast.
228
+ /**
229
+ * Accept only inline comments that name the trust boundary or validation reason for a double cast.
230
+ *
231
+ * @param rawLine - Raw source line checked for an inline comment and trust-boundary rationale keyword.
232
+ * @returns True when rawLine contains a comment marker and a recognised trust-boundary or validation term.
233
+ */
174
234
  function hasDoubleCastTrustBoundaryRationale(rawLine: string): boolean {
175
235
  return (
176
236
  /(?:\/\/|\/\*)/.test(rawLine) &&
@@ -178,10 +238,14 @@ function hasDoubleCastTrustBoundaryRationale(rawLine: string): boolean {
178
238
  );
179
239
  }
180
240
 
181
- /*
182
- * `any` in an exported declaration's public surface. Only one finding per line because a single
183
- * `export` with multiple any-typed fields is one design problem, not many. Reports the stable
184
- * `waste.exported-any` finding.
241
+ /**
242
+ * Flag possible exported uses of any. Emit one finding per matching line to avoid repeating the same declaration.
243
+ *
244
+ * @param file - Source file supplying the display path for the finding.
245
+ * @param codeLine - Code to check for a named export declaration and an any token on the same line.
246
+ * @param lineNumber - Source line attached to the result.
247
+ * @param findings - Caller-owned array that receives the stable waste.exported-any finding on a match.
248
+ * @returns Nothing. Appends at most one finding and leaves the array alone when no export matches.
185
249
  */
186
250
  function pushExportedAnyFinding(file: SourceFile, codeLine: string, lineNumber: number, findings: Finding[]): void {
187
251
  const exportedAny = exportedAnySymbol(codeLine);
@@ -204,8 +268,15 @@ function pushExportedAnyFinding(file: SourceFile, codeLine: string, lineNumber:
204
268
  );
205
269
  }
206
270
 
207
- // `arr.forEach(async …)` is a near-universal anti-pattern: the array iterator does not await the
208
- // returned promise, so errors swallow silently. Reports the stable `security.async-foreach` finding.
271
+ /**
272
+ * Scan codeLine for async forEach callbacks because forEach does not await them and their rejections can go unhandled.
273
+ *
274
+ * @param file - Source file supplying the display path for the finding.
275
+ * @param codeLine - Stripped code line checked for an async callback passed to forEach.
276
+ * @param lineNumber - One-based line number used to locate the result.
277
+ * @param findings - Caller-owned array receiving a stable security.async-foreach finding on a match.
278
+ * @returns Nothing. Appends a stable security.async-foreach finding to findings on a match.
279
+ */
209
280
  function pushAsyncForEachFinding(file: SourceFile, codeLine: string, lineNumber: number, findings: Finding[]): void {
210
281
  if (!/\.forEach\s*\(\s*async\b/.test(codeLine)) {
211
282
  return;
@@ -225,36 +296,14 @@ function pushAsyncForEachFinding(file: SourceFile, codeLine: string, lineNumber:
225
296
  );
226
297
  }
227
298
 
228
- /*
229
- * A promise-shaped call started as a bare statement, with no `await`, `return`, `void`, or chain.
230
- * Such promises lose their reject path - exceptions land in an unhandled-rejection. Reports
231
- * the stable `security.floating-promise` finding.
232
- */
233
- function pushFloatingPromiseFinding(file: SourceFile, codeLine: string, lineNumber: number, findings: Finding[]): void {
234
- const floating = floatingPromiseCall(codeLine);
235
- if (!floating) {
236
- return;
237
- }
238
- findings.push(
239
- makeFinding({
240
- ruleId: "security.floating-promise",
241
- message: `Promise-like call \`${floating}\` is started without await, return, or void.`,
242
- filePath: file.displayPath,
243
- line: lineNumber,
244
- severity: "warning",
245
- pillar: "security",
246
- confidence: "medium",
247
- symbol: floating,
248
- remediation: "Await it, return it, or prefix with void when fire-and-forget is intentional.",
249
- metadata: { callName: floating },
250
- }),
251
- );
252
- }
253
-
254
- /*
255
- * `throw "string"` / `throw { …object }` / `throw 42`. JavaScript permits it but the stack trace
256
- * is missing and the caller can't pattern-match an Error subclass. Reports the stable
257
- * `security.throw-non-error` finding.
299
+ /**
300
+ * Flag literal non-Error throw candidates because these values lack the usual Error stack and subclass contract.
301
+ *
302
+ * @param file - Source file supplying the display path for the finding.
303
+ * @param codeLine - Code checked for a literal-looking thrown expression.
304
+ * @param lineNumber - One-based source line attached to the finding.
305
+ * @param findings - Accumulator for security.throw-non-error findings.
306
+ * @returns Nothing. Appends one finding on a match and leaves the accumulator unchanged otherwise.
258
307
  */
259
308
  function pushNonErrorThrowFinding(file: SourceFile, codeLine: string, lineNumber: number, findings: Finding[]): void {
260
309
  const thrown = nonErrorThrowExpression(codeLine);
@@ -276,32 +325,69 @@ function pushNonErrorThrowFinding(file: SourceFile, codeLine: string, lineNumber
276
325
  );
277
326
  }
278
327
 
279
- // Returns the directive name only when the suffix following a TypeScript suppression directive
280
- // has no meaningful rationale. Heuristic is intentionally lenient - three real words usually means
281
- // the maintainer wrote a reason.
282
- function tsDirectiveWithoutRationale(line: string): { directive: string } | undefined {
328
+ /**
329
+ * Detect @ts-ignore or @ts-expect-error in line without an accepted suffix rationale.
330
+ *
331
+ * @param line - Raw source line checked for a TypeScript suppression directive and trailing rationale.
332
+ * @param trackingTokens - Extra accepted rationale patterns; testing a stateful pattern may change its lastIndex.
333
+ * @returns Directive-name object when a directive lacks an accepted suffix rationale, or undefined otherwise.
334
+ */
335
+ function tsDirectiveWithoutRationale(line: string, trackingTokens: readonly RegExp[]): { directive: string } | undefined {
283
336
  const match = line.match(/@ts-(ignore|expect-error)\b(.*)$/);
284
337
  if (!match?.[1]) {
285
338
  return undefined;
286
339
  }
287
340
  const rationale = match[2] ?? "";
288
- if (hasDirectiveRationale(rationale)) {
341
+ if (hasDirectiveRationale(rationale, trackingTokens)) {
289
342
  return undefined;
290
343
  }
291
344
  return { directive: `@ts-${match[1]}` };
292
345
  }
293
346
 
294
- // Two-way pass: an explicit suppression rationale token (tracking URL / issue ID / owner / date)
295
- // or at least three real English-shaped words. The disjunction keeps maintainers from having to
296
- // remember a specific format.
297
- function hasDirectiveRationale(directiveSuffix: string): boolean {
347
+ /**
348
+ * Check whether directiveSuffix has a rationale marker or at least three runs of three or more ASCII letters after separator trimming.
349
+ *
350
+ * @param directiveSuffix - Text following the TypeScript suppression directive on the same line.
351
+ * @param trackingTokens - Extra accepted rationale patterns; testing a stateful pattern may change its lastIndex.
352
+ * @returns True when the trimmed suffix matches a rationale marker or has at least three three-letter words.
353
+ */
354
+ function hasDirectiveRationale(directiveSuffix: string, trackingTokens: readonly RegExp[]): boolean {
298
355
  const cleaned = directiveSuffix.replace(/^[-:\s]+/, "").trim();
299
356
  const words = cleaned.match(/[A-Za-z]{3,}/g) ?? [];
300
- return hasSuppressionRationale(cleaned) || words.length >= 3;
357
+ return hasSuppressionRationale(cleaned, trackingTokens) || words.length >= 3;
358
+ }
359
+
360
+ /**
361
+ * Join consecutive prose line comments above the target in source order so a rationale can sit above a TypeScript directive.
362
+ * Skips lint and TypeScript directive-only lines so an adjacent linter suppression comment never substitutes for a rationale.
363
+ *
364
+ * @param lines - Source file lines searched backwards from the target line.
365
+ * @param index - Zero-based position of the target line.
366
+ * @returns Joined preceding prose comment text in source order, or empty text when no qualifying comments exist.
367
+ */
368
+ function lineCommentsAbove(lines: readonly string[], index: number): string {
369
+ const texts: string[] = [];
370
+ for (let current = index - 1; current >= 0; current -= 1) {
371
+ const trimmed = (lines[current] ?? "").trim();
372
+ if (!trimmed.startsWith("//")) {
373
+ break;
374
+ }
375
+ const body = trimmed.replace(/^\/\/+\s*/, "");
376
+ // Another tool's suppression directive (ESLint, Biome, or TypeScript) explains nothing on its own; skip it and keep checking above.
377
+ if (/^(?:eslint-disable(?:-(?:next-)?line)?|biome-ignore|@ts-(?:expect-error|ignore|nocheck))\b/i.test(body)) {
378
+ continue;
379
+ }
380
+ texts.unshift(body);
381
+ }
382
+ return texts.join(" ");
301
383
  }
302
384
 
303
- // Two-shot scan: line must have both `export` and `any` before the regex is invoked, because the
304
- // regex is expensive and most lines do not have both.
385
+ /**
386
+ * Extract an export declaration's name from codeLine only when it also contains any; does not establish whether any is in the public type.
387
+ *
388
+ * @param codeLine - Stripped code line checked for both an export declaration and an any token.
389
+ * @returns Exported symbol name when both match, or undefined when no such match exists.
390
+ */
305
391
  function exportedAnySymbol(codeLine: string): string | undefined {
306
392
  if (!/\bexport\b/.test(codeLine) || !/\bany\b/.test(codeLine)) {
307
393
  return undefined;
@@ -310,42 +396,12 @@ function exportedAnySymbol(codeLine: string): string | undefined {
310
396
  return match?.[1];
311
397
  }
312
398
 
313
- // Two predicates compose: must be a bare statement (not handled), and must be a promise-shaped
314
- // call. Returning undefined keeps the per-line emission stable when either gate fails.
315
- function floatingPromiseCall(codeLine: string): string | undefined {
316
- const trimmed = codeLine.trim();
317
- if (isHandledPromiseStatement(trimmed)) {
318
- return undefined;
319
- }
320
- const callName = leadingCallName(trimmed);
321
- if (!callName) {
322
- return undefined;
323
- }
324
- return isPromiseLikeCall(callName) ? callName : undefined;
325
- }
326
-
327
- // Five "this is intentional" forms: await, return, void, throw, yield, or a binding. Any one keeps
328
- // the line out of floating-promise reporting.
329
- function isHandledPromiseStatement(trimmedLine: string): boolean {
330
- return trimmedLine.length === 0 || /^(?:await|return|void|throw|yield)\b/.test(trimmedLine) || /^(?:const|let|var)\s+/.test(trimmedLine);
331
- }
332
-
333
- // Picks the dotted callable name at the start of the line. Empty string for non-call statements
334
- // signals "not a candidate" to the caller without throwing.
335
- function leadingCallName(trimmedLine: string): string {
336
- const match = trimmedLine.match(/^([A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*)\s*\(/);
337
- return match?.[1] ?? "";
338
- }
339
-
340
- // Heuristic: `fetch`, anything ending in `Async`, or anything ending in `Promise`. False positives
341
- // are tolerated because the rule's remediation ("await or void it") is also the universal best practice.
342
- function isPromiseLikeCall(callName: string): boolean {
343
- const localName = callName.split(".").at(-1) ?? callName;
344
- return callName === "fetch" || /(?:Async|Promise)$/.test(localName);
345
- }
346
-
347
- // Allow `throw new XxxError(...)` and `throw e` (bare identifier - usually a rethrow), reject literals.
348
- // Returns a truncated preview because the full expression can be arbitrarily long.
399
+ /**
400
+ * Extract literal non-Error throw expressions while allowing `throw new XxxError(...)` and bare identifier throws.
401
+ *
402
+ * @param codeLine - Stripped code line inspected for a thrown expression.
403
+ * @returns Truncated expression preview up to 40 characters because the full expression can be arbitrarily long, or undefined.
404
+ */
349
405
  function nonErrorThrowExpression(codeLine: string): string | undefined {
350
406
  const match = codeLine.match(/\bthrow\s+(.+?);?$/);
351
407
  const expression = (match?.[1] ?? "").trim();
@@ -358,9 +414,12 @@ function nonErrorThrowExpression(codeLine: string): string | undefined {
358
414
  return /^(?:["'`]|\d|\{|\[|true\b|false\b|null\b|undefined\b)/.test(expression) ? expression.slice(0, 40) : undefined;
359
415
  }
360
416
 
361
- // Strips both line and block comments before testing for emptiness. A catch body holding only a
362
- // throwaway placeholder comment reads as a deliberate swallow but documents nothing about the
363
- // recovery path - that is still the rule's signal.
417
+ /**
418
+ * Check whether body is empty after removing line and block comments and whitespace, treating placeholder-only comments as swallowed.
419
+ *
420
+ * @param body - Catch block body text stripped of comments and whitespace to check for meaningful statements.
421
+ * @returns True when body contains no meaningful code after stripping comments and whitespace.
422
+ */
364
423
  function isSwallowedCatchBody(body: string): boolean {
365
424
  const meaningful = body
366
425
  .replace(/\/\/.*$/gm, "")