@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
@@ -4,17 +4,19 @@
4
4
  import { type SourceFile } from "./discovery.ts";
5
5
  import { makeFinding } from "./findings.ts";
6
6
  import { escapeRegex, finding } from "./findings-helpers.ts";
7
+ import { namedImportBindings, type ParsedScript } from "./parsed-script.ts";
7
8
  import { byteLine, countMatches } from "./text-scans.ts";
8
9
  import type { Finding } from "./types.ts";
9
10
 
10
- /*
11
- * Single-file, low-confidence dead-code pass. Contract invariant: removal candidates stay advisory
12
- * because tests, decorators, framework hooks, or reflection may still reach a private method. It
13
- * reports findings only and never throws for malformed snippets. Why two evidence counts:
14
- * declarations contribute to `name(` matches, while bare method references such as `items.map(this.double)`
15
- * appear only as `this.name` / `this?.name`, and either shape is enough usage evidence to suppress
16
- * the finding. The reference count requires a `this` receiver so unrelated properties that share
17
- * the name (for example `settings.refresh`) cannot mask a genuinely unused private method.
11
+ /**
12
+ * Scans for likely unused private methods. The declaration counts as one call-shaped match.
13
+ * Another call-shaped match or a matching this.name or this?.name reference suppresses the finding because even a bare reference may be used.
14
+ * The advisory contract allows for real uses that the scan can miss.
15
+ *
16
+ * @param file - supplies the display path for each finding
17
+ * @param source - masked source used to count call-shaped matches and references
18
+ * @param findings - accumulator that receives the low-confidence advisories
19
+ * @returns Nothing. Appends an advisory finding for each private method that appears unused.
18
20
  */
19
21
  export function analyseDeadCode(file: SourceFile, source: string, findings: Finding[]): void {
20
22
  for (const match of source.matchAll(/\bprivate\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/g)) {
@@ -38,12 +40,15 @@ export function analyseDeadCode(file: SourceFile, source: string, findings: Find
38
40
  }
39
41
  }
40
42
 
41
- /*
42
- * Line-by-line walker that resets the terminator flag at every `case:` / `default:` because
43
- * dead-code detection must respect control-flow boundaries. Each line is walked once in source
44
- * order; the per-line state-machine update is extracted into `advanceUnreachableState` to keep
45
- * this loop's branching low. Reports `waste.unreachable-code` with stable, deterministic
46
- * fingerprint anchors so baselines and report snapshots round-trip without churn.
43
+ /**
44
+ * Scans masked source line by line for statements after terminating statements and appends unreachable-code findings.
45
+ * Case and default labels reset prior termination so a previous branch's terminator cannot make the new branch appear unreachable.
46
+ * Uses stable finding anchors so baselines and report snapshots can match results across runs.
47
+ *
48
+ * @param file - provides the file path metadata for emitted findings
49
+ * @param source - comment- and literal-masked script text scanned line by line
50
+ * @param findings - accumulator that receives emitted unreachable-code findings
51
+ * @returns Nothing. Appends `waste.unreachable-code` findings to `findings`.
47
52
  */
48
53
  export function analyseUnreachable(file: SourceFile, source: string, findings: Finding[]): void {
49
54
  let state: UnreachableScanState = { didPreviousTerminate: false, conditionalParenDepth: 0, isConsequentPending: false };
@@ -67,12 +72,13 @@ interface UnreachableScanState {
67
72
  isConsequentPending: boolean;
68
73
  }
69
74
 
70
- /*
71
- * Computes the next walker state from the current line. The conditional-context check (inside the
72
- * predicate parens, or on the consequent line) drives whether a terminator on this line counts as
73
- * unconditional. Branching is intentional here because the multi-line predicate has three discrete
74
- * cases: opener line, inside-predicate continuation, and "no longer in a predicate." Splitting
75
- * them inline would invariably reintroduce the npath the wrapper was trying to avoid.
75
+ /**
76
+ * Computes the next unreachable-code walker state after processing one trimmed masked line.
77
+ * Carries predicate depth and a pending-consequent flag so terminators inside those conditional contexts are not treated as unconditional.
78
+ *
79
+ * @param trimmed - current trimmed masked source line being evaluated
80
+ * @param state - prior walker state carrying termination and conditional-branch context
81
+ * @returns Updated walker state for the subsequent line.
76
82
  */
77
83
  function advanceUnreachableState(trimmed: string, state: UnreachableScanState): UnreachableScanState {
78
84
  const isInConditionalBranch = state.conditionalParenDepth > 0 || state.isConsequentPending;
@@ -89,14 +95,25 @@ function advanceUnreachableState(trimmed: string, state: UnreachableScanState):
89
95
  return { didPreviousTerminate, conditionalParenDepth: 0, isConsequentPending: false };
90
96
  }
91
97
 
92
- // Net paren balance for one line of masked code (opens minus closes). String-literal parens are
93
- // already blanked upstream by the masker, so the count is reliable for predicate-depth tracking.
98
+ /**
99
+ * Computes the net parenthesis balance (opens minus closes) for one line of masked code.
100
+ * String-literal parens are already blanked upstream by the masker, so the count is reliable for predicate-depth tracking.
101
+ *
102
+ * @param text - masked code fragment whose parentheses are counted
103
+ * @returns Net count of opening minus closing parentheses in `text`.
104
+ */
94
105
  function parenBalance(text: string): number {
95
106
  return countChar(text, "(") - countChar(text, ")");
96
107
  }
97
108
 
98
- // Counts a single character's occurrences without allocating a match array. Used to balance parens
99
- // across the lines of a multi-line conditional predicate in `analyseUnreachable`.
109
+ /**
110
+ * Counts occurrences of a single character without allocating a match array.
111
+ * Used to balance parens across the lines of a multi-line conditional predicate in `analyseUnreachable`.
112
+ *
113
+ * @param text - input text scanned character by character
114
+ * @param character - target character to count within `text`
115
+ * @returns Total number of positions where `text` matches `character`.
116
+ */
100
117
  function countChar(text: string, character: string): number {
101
118
  let count = 0;
102
119
  for (const char of text) {
@@ -107,8 +124,13 @@ function countChar(text: string, character: string): number {
107
124
  return count;
108
125
  }
109
126
 
110
- // Detects single-line conditional/loop openers that begin a one-statement body (no `{`). The next
111
- // line is the conditional body, so any terminator there is conditional rather than unconditional.
127
+ /**
128
+ * Detects single-line conditional or loop openers that begin a one-statement body without a brace.
129
+ * The next line is the conditional body, so any terminator there is conditional rather than unconditional.
130
+ *
131
+ * @param trimmed - trimmed masked source line to inspect
132
+ * @returns True when `trimmed` opens a braceless conditional or loop header; false otherwise.
133
+ */
112
134
  function isBracelessConditionalOpener(trimmed: string): boolean {
113
135
  if (trimmed.endsWith("{") || trimmed.endsWith("}")) {
114
136
  return false;
@@ -116,41 +138,67 @@ function isBracelessConditionalOpener(trimmed: string): boolean {
116
138
  return /^(?:if|else\s+if|for|while)\s*\(/.test(trimmed) || /^else\b/.test(trimmed) || /^do\b/.test(trimmed);
117
139
  }
118
140
 
119
- // `case X:` / `default:` open a new control path, so the unreachable walker must reset its
120
- // terminator flag here - otherwise the first statement in a fallthrough case looks dead.
141
+ /**
142
+ * Checks whether a trimmed line is a `case` or `default` label followed only by an optional opening brace.
143
+ * The walker resets its terminator flag there because a switch can enter that case directly.
144
+ *
145
+ * @param trimmedLine - trimmed masked source line under inspection
146
+ * @returns True when `trimmedLine` matches a switch `case` or `default` branch label; false otherwise.
147
+ */
121
148
  function isBranchLabel(trimmedLine: string): boolean {
122
- return /^(?:case\b.*:|default\s*:)$/.test(trimmedLine);
149
+ return /^(?:case\b.*|default\s*):\s*\{?$/.test(trimmedLine);
123
150
  }
124
151
 
125
- // Three conditions must hold to flag a line: the prior statement terminated, this line has real
126
- // content, and it's not a `}` closer or a branch label. The `}` exclusion matters because the
127
- // closing brace of the terminating block looks like a statement to a naive walker.
152
+ /**
153
+ * Determines whether a line should be flagged as unreachable after a terminating statement.
154
+ * Three conditions must hold: prior termination, non-whitespace content, and not a `}` closer or branch label,
155
+ * because a closing brace looks like a statement to a naive walker.
156
+ *
157
+ * @param trimmedLine - trimmed masked source line being evaluated
158
+ * @param didPreviousTerminate - whether the preceding control path ended unconditionally
159
+ * @param isBranchLabel - whether the current line starts a switch `case` or `default` branch
160
+ * @returns True when all three unreachability conditions hold; false otherwise.
161
+ */
128
162
  function isUnreachableStatement(trimmedLine: string, didPreviousTerminate: boolean, isBranchLabel: boolean): boolean {
129
163
  return didPreviousTerminate && /\S/.test(trimmedLine) && !trimmedLine.startsWith(String.fromCharCode(125)) && !isBranchLabel;
130
164
  }
131
165
 
132
- // `return`, `throw`, and `process.exit(...)` exit the current control path. The trailing `;`
133
- // requirement filters out expressions like `return foo()` split across lines - without it the
134
- // walker would falsely flag the continuation as unreachable.
166
+ /**
167
+ * Checks whether a trimmed line is a complete `return`, `throw`, or `process.exit(...)` terminator ending in `;`.
168
+ * The trailing `;` requirement filters out multi-line expressions like `return foo()` so continuations are not falsely flagged.
169
+ *
170
+ * @param trimmedLine - trimmed masked source line to check
171
+ * @returns True when `trimmedLine` begins with a terminator keyword and ends with `;`; false otherwise.
172
+ */
135
173
  function isTerminatingStatement(trimmedLine: string): boolean {
136
174
  return /^(?:return|throw|process\.exit)\b/.test(trimmedLine) && trimmedLine.endsWith(";");
137
175
  }
138
176
 
139
- /*
140
- * Reports `waste.unused-import` for every named specifier whose local name appears nowhere else
141
- * in the file. Default imports and namespace imports are out of scope because the regex anchors
142
- * on `{ … }`; walking lines in source order keeps the reports stable and deterministic. Receives
143
- * both the masked code and the raw source so identifiers referenced inside template-literal
144
- * `${...}` interpolations (which the mask would otherwise blank out) still count as used. Never
145
- * throws - every regex is anchored and the input shape is validated upstream by the analyser; the
146
- * helper writes to `findings` and returns void. Part of the public per-file rule contract that
147
- * baselines depend on, so finding ordering and message shape are intentionally stable across releases.
177
+ /**
178
+ * Reports `waste.unused-import` for named specifiers unused elsewhere, preferring the shared AST (`parsed`) over masked text scanning.
179
+ * Checks both masked code and raw template-literal `${...}` interpolations so interpolated identifiers still count as used.
180
+ * Never throws; writes to `findings` under the public per-file rule contract so finding order and message shape remain stable.
181
+ *
182
+ * @param file - provides the file path metadata for emitted findings
183
+ * @param source - masked code used for fallback import scanning and identifier reference counts
184
+ * @param rawSource - unmasked source inspected for template-literal `${...}` interpolations
185
+ * @param findings - accumulator that receives `waste.unused-import` findings
186
+ * @param parsed - optional shared TypeScript AST that resolves inline `type` modifiers, aliases, and multiline lists
187
+ * @returns Nothing. Writes `waste.unused-import` findings to `findings` in stable order.
148
188
  */
149
- export function analyseUnusedImports(file: SourceFile, source: string, rawSource: string, findings: Finding[]): void {
189
+ export function analyseUnusedImports(file: SourceFile, source: string, rawSource: string, findings: Finding[], parsed?: ParsedScript): void {
190
+ if (parsed) {
191
+ for (const binding of namedImportBindings(parsed)) {
192
+ if (isUnusedImportBinding(source, rawSource, binding.name)) {
193
+ findings.push(unusedImportFinding(file, binding.name, binding.line));
194
+ }
195
+ }
196
+ return;
197
+ }
150
198
  for (const statement of namedImportStatements(source)) {
151
199
  for (const specifier of namedImportSpecifiers(statement.source)) {
152
- const name = unusedImportName(source, rawSource, specifier);
153
- if (!name) {
200
+ const name = localImportName(specifier);
201
+ if (!name || !isUnusedImportBinding(source, rawSource, name)) {
154
202
  continue;
155
203
  }
156
204
  findings.push(unusedImportFinding(file, name, statement.line));
@@ -165,15 +213,24 @@ interface NamedImportStatement {
165
213
  line: number;
166
214
  }
167
215
 
168
- // Finds only named import declarations and spans across newlines until the matching `from` source.
169
- // The non-greedy body keeps adjacent imports from merging into one statement.
216
+ /**
217
+ * Extracts named-import declarations and their starting line numbers from masked source text.
218
+ * Matches `import { ... } from "..."` and `import type { ... } from "..."` statements, including multiline lists.
219
+ *
220
+ * @param source - comment- and literal-masked script text to scan for named imports
221
+ * @returns Matched statement fragments with 1-based starting line numbers, or an empty array if none match.
222
+ */
170
223
  function namedImportStatements(source: string): NamedImportStatement[] {
171
224
  return [...source.matchAll(/\bimport\s+(?:type\s+)?\{[\s\S]*?\}\s+from\s*["'][^"']+["']/g)].map((match) => ({ source: match[0] ?? "", line: byteLine(source, match.index ?? 0) }));
172
225
  }
173
226
 
174
- // Slices the `{ a, b as c }` body out of a named-import statement and splits on commas. No AST: a
175
- // regex-light approach is sufficient because `analyseUnusedImports` runs after the comment mask,
176
- // so commas inside string defaults never reach this function.
227
+ /**
228
+ * Splits the brace-enclosed list of a masked named-import statement into comma-separated specifier fragments.
229
+ * Braces with no specifiers yield one fragment, preserving whitespace; masking keeps string commas from splitting specifiers.
230
+ *
231
+ * @param source - masked import statement text containing the named specifier list
232
+ * @returns Raw comma-separated specifier fragments, or an empty array when no complete brace pair is found.
233
+ */
177
234
  function namedImportSpecifiers(source: string): string[] {
178
235
  const trimmed = source.trim();
179
236
  const openBrace = trimmed.indexOf(String.fromCharCode(123));
@@ -184,33 +241,49 @@ function namedImportSpecifiers(source: string): string[] {
184
241
  return trimmed.slice(openBrace + 1, closeBrace).split(",");
185
242
  }
186
243
 
187
- // Both braces present and well-ordered. Indexes come from raw `indexOf` calls, so this guards
188
- // against the malformed slice that would otherwise feed an empty or reversed specifier list.
244
+ /**
245
+ * Validates `indexOf` brace positions before slicing a named-import specifier list.
246
+ *
247
+ * @param openBrace - zero-based index of `{`, or `-1` when absent
248
+ * @param closeBrace - zero-based index of `}` after `openBrace`, or `-1` when absent
249
+ * @returns True when both braces exist and `closeBrace` follows `openBrace`; false otherwise.
250
+ */
189
251
  function hasNamedImportBraces(openBrace: number, closeBrace: number): boolean {
190
252
  return openBrace !== -1 && closeBrace !== -1 && closeBrace > openBrace;
191
253
  }
192
254
 
193
- // The local binding (after `as`, if present) must appear in the source exactly once - the
194
- // declaration itself. More than one match in the masked code, OR a `${...name...}` template-literal
195
- // interpolation in the raw source, counts as a real reference. Returning undefined suppresses the finding.
196
- function unusedImportName(source: string, rawSource: string, specifier: string): string | undefined {
197
- const name = localImportName(specifier);
198
- if (!name) {
199
- return undefined;
200
- }
201
- const escaped = escapeRegex(name);
202
- if (countMatches(source, new RegExp(`\\b${escaped}\\b`, "g")) > 1) {
203
- return undefined;
255
+ /**
256
+ * Checks whether a local import binding appears only at its declaration site across masked code and raw template interpolations.
257
+ * Uses JavaScript identifier boundaries (`[A-Za-z0-9_$]`) rather than `\b` so `$`-bearing bindings such as Bun's `$`, `$state`,
258
+ * and RxJS `events$` are recognised without letting `${...}` template interpolations count as uses of `$`.
259
+ *
260
+ * @param source - comment- and literal-masked script source for identifier reference counts
261
+ * @param rawSource - unmasked script source inspected for `${...}` template interpolations
262
+ * @param bindingName - local identifier bound by one named import specifier
263
+ * @returns True when no usage outside the import declaration is found; false when at least one reference exists.
264
+ */
265
+ function isUnusedImportBinding(source: string, rawSource: string, bindingName: string): boolean {
266
+ const escaped = escapeRegex(bindingName);
267
+ const trailingGuard = bindingName.endsWith("$") ? "(?![A-Za-z0-9_$]|\\{)" : "(?![A-Za-z0-9_$])";
268
+ const boundaryPattern = `(?<![A-Za-z0-9_$])${escaped}${trailingGuard}`;
269
+ if (countMatches(source, new RegExp(boundaryPattern, "g")) > 1) {
270
+ return false;
204
271
  }
205
- if (new RegExp(`\\$\\{[^}]*\\b${escaped}\\b[^}]*\\}`).test(rawSource)) {
206
- return undefined;
272
+ if (new RegExp(`\\$\\{[^}]*${boundaryPattern}[^}]*\\}`).test(rawSource)) {
273
+ return false;
207
274
  }
208
- return name;
275
+ return true;
209
276
  }
210
277
 
211
- // Single makeFinding factory for `waste.unused-import`. The local binding name lands in both the
212
- // message and `metadata.importName` so downstream tooling can group by symbol while the stable
213
- // fingerprint identity remains (ruleId, filePath, line).
278
+ /**
279
+ * Builds a `waste.unused-import` advisory finding for an unused local import binding.
280
+ * Places `name` in the message, `symbol`, and `metadata.importName` for grouping; its fingerprint uses rule ID, file path, line, and symbol.
281
+ *
282
+ * @param file - source file providing `displayPath` for the finding location and fingerprint
283
+ * @param name - unused local identifier bound by the import specifier
284
+ * @param line - 1-based line number of the import declaration or binding
285
+ * @returns Structured `Finding` object with rule ID `waste.unused-import`.
286
+ */
214
287
  function unusedImportFinding(file: SourceFile, name: string, line: number): Finding {
215
288
  return makeFinding({
216
289
  ruleId: "waste.unused-import",
@@ -226,10 +299,16 @@ function unusedImportFinding(file: SourceFile, name: string, line: number): Find
226
299
  });
227
300
  }
228
301
 
229
- // Returns the right-hand side of `as` when present, otherwise the specifier itself. The trailing
230
- // identifier regex protects against type-only specifiers that include extra tokens.
302
+ /**
303
+ * Resolves the local identifier bound by one named-import specifier fragment.
304
+ * Returns the right-hand side of `as` when aliased, or the specifier without any leading inline `type` modifier; used only by the fallback path.
305
+ *
306
+ * @param specifier - raw specifier fragment extracted from inside import braces
307
+ * @returns Local identifier string, or `undefined` when no valid identifier is present.
308
+ */
231
309
  function localImportName(specifier: string): string | undefined {
232
- const parts = specifier.trim().split(/\s+as\s+/);
310
+ const stripped = specifier.trim().replace(/^type\s+/, "");
311
+ const parts = stripped.split(/\s+as\s+/);
233
312
  const candidate = parts[1] ?? parts[0] ?? "";
234
313
  const match = candidate.trim().match(/^[A-Za-z_$][A-Za-z0-9_$]*/);
235
314
  return match?.[0];