@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,7 +1,7 @@
1
- // Syntax-aware complexity measurement for each callable discovered by the shared script parse.
2
- // It turns real decision nodes into the values shown in CLI and JSON findings while leaving
3
- // defaulting, optional access, presentation objects, and ordinary blocks out of the score.
4
- // Nested callable ownership follows the same M07 block inventory, so every body counts once.
1
+ // Measures syntax-aware cyclomatic and cognitive complexity for each callable in the shared script parse.
2
+ //
3
+ // Feeds `complexity.cyclomatic` findings and the `docs.missing-why-for-complex-code` threshold without re-parsing files.
4
+ // Leaves defaulting (`??`), optional access (`?.`), object literals, and owned nested callables out of the enclosing score.
5
5
  import { createRequire } from "node:module";
6
6
 
7
7
  // TypeScript is CommonJS at runtime; this module only walks nodes from the existing shared parse.
@@ -14,9 +14,11 @@ const typescriptSyntax = require("typescript") as typeof import("typescript");
14
14
  type TypeScriptNode = import("typescript").Node;
15
15
 
16
16
  /**
17
- * Stable per-kind decision counts attached to complexity findings for report consumers.
18
- * Every key is always present, including zero values, so JSON comparisons stay deterministic.
19
- * `maxNesting` describes control-flow nesting only, never object or callback braces.
17
+ * Stable per-kind decision counts attached to complexity findings for CLI and JSON report consumers.
18
+ *
19
+ * Every key is always emitted (including zeros) so JSON snapshots stay deterministic:
20
+ * - `case` counts one decision per switch with a non-default case, regardless of case count;
21
+ * - `maxNesting` measures control-flow nesting only, never object or callback braces.
20
22
  */
21
23
  export interface ComplexityBreakdown {
22
24
  if: number;
@@ -59,7 +61,7 @@ interface ComplexityAccumulator {
59
61
 
60
62
  /**
61
63
  * Context threaded through the recursive walk so nested callable bodies keep one owner.
62
- * `callableNode` is the block being measured; `ownedCallableNodes` are sibling report blocks.
64
+ * `callableNode` is the node being measured; `ownedCallableNodes` includes nested callables measured separately.
63
65
  * The shared accumulator becomes metadata visible to report and hook consumers.
64
66
  */
65
67
  interface ComplexityWalkContext {
@@ -68,7 +70,11 @@ interface ComplexityWalkContext {
68
70
  accumulator: ComplexityAccumulator;
69
71
  }
70
72
 
71
- // Returns the base measurement used only when a caller has no parsed script, such as a legacy span probe.
73
+ /**
74
+ * Base measurement used only when a caller has no parsed script, such as a legacy span probe.
75
+ *
76
+ * @returns Base complexity metrics with cyclomatic and cognitive complexity of 1, 0 nesting, and a zeroed breakdown.
77
+ */
72
78
  export function baseComplexityMetrics(): ComplexityMetrics {
73
79
  return {
74
80
  cyclomatic: 1,
@@ -78,8 +84,13 @@ export function baseComplexityMetrics(): ComplexityMetrics {
78
84
  };
79
85
  }
80
86
 
81
- // Measures one parsed callable without reparsing the source or walking another reported callable.
82
- // It reports one deterministic breakdown to CLI complexity findings and documentation checks.
87
+ /**
88
+ * Measures the supplied parsed callable for complexity findings and documentation checks.
89
+ *
90
+ * @param callableNode - Root parsed callable syntax node to measure.
91
+ * @param ownedCallableNodes - Ownership set identifying separately reported nested callables to skip.
92
+ * @returns Cyclomatic and cognitive complexity, maximum nesting, and a breakdown of the counts.
93
+ */
83
94
  export function complexityMetrics(callableNode: TypeScriptNode, ownedCallableNodes: ReadonlySet<TypeScriptNode>): ComplexityMetrics {
84
95
  const accumulator: ComplexityAccumulator = {
85
96
  ifCount: 0,
@@ -120,13 +131,21 @@ export function complexityMetrics(callableNode: TypeScriptNode, ownedCallableNod
120
131
  };
121
132
  }
122
133
 
123
- // Walks one node using the counting law, carrying only control-flow depth between syntax children.
134
+ /**
135
+ * Measures the supplied syntax node and its owned descendants from the current control-flow depth,
136
+ * pruning reported nested callables to preserve separate totals.
137
+ *
138
+ * @param node - Current syntax node being visited during traversal.
139
+ * @param controlFlowDepth - Current control-flow nesting depth at this node.
140
+ * @param context - Walk state carrying the root callable, ownership set, and mutable accumulator.
141
+ * @returns Nothing. Updates counts and maximum nesting in the walk context.
142
+ */
124
143
  function walkComplexityNode(node: TypeScriptNode, controlFlowDepth: number, context: ComplexityWalkContext): void {
125
- // When M07 reports a nested callable separately, its body belongs to that report block, not this parent.
144
+ // A separately reported nested callable contributes to its own measurements.
126
145
  if (node !== context.callableNode && context.ownedCallableNodes.has(node)) {
127
146
  return;
128
147
  }
129
- // A user's if statement adds one decision and one control-flow nesting level.
148
+ // An if adds one decision; an early-exit guard keeps the current nesting level.
130
149
  if (typescriptSyntax.isIfStatement(node)) {
131
150
  walkIfStatement(node, controlFlowDepth, context);
132
151
  return;
@@ -137,8 +156,11 @@ function walkComplexityNode(node: TypeScriptNode, controlFlowDepth: number, cont
137
156
  walkNestedControlFlow(node, controlFlowDepth, context);
138
157
  return;
139
158
  }
140
- // A switch adds nesting for its choices but no decision beyond its non-default cases.
159
+ // A switch adds one nesting level. A switch with any case clause also adds one dispatch decision.
141
160
  if (typescriptSyntax.isSwitchStatement(node)) {
161
+ if (node.caseBlock.clauses.some((clause) => typescriptSyntax.isCaseClause(clause))) {
162
+ context.accumulator.caseCount += 1;
163
+ }
142
164
  walkNestedControlFlow(node, controlFlowDepth, context);
143
165
  return;
144
166
  }
@@ -148,19 +170,13 @@ function walkComplexityNode(node: TypeScriptNode, controlFlowDepth: number, cont
148
170
  walkNestedControlFlow(node, controlFlowDepth, context);
149
171
  return;
150
172
  }
151
- // Each explicit case adds a decision; default and the case wrapper add no nesting.
152
- if (typescriptSyntax.isCaseClause(node)) {
153
- context.accumulator.caseCount += 1;
154
- walkChildrenAtDepth(node, controlFlowDepth, context);
155
- return;
156
- }
157
173
  // A conditional expression adds one decision and one control-flow nesting level.
158
174
  if (typescriptSyntax.isConditionalExpression(node)) {
159
175
  context.accumulator.ternaryCount += 1;
160
176
  walkNestedControlFlow(node, controlFlowDepth, context);
161
177
  return;
162
178
  }
163
- // Logical operators count as decisions but do not deepen control flow.
179
+ // Logical AND and OR add decisions at the current nesting depth.
164
180
  if (typescriptSyntax.isBinaryExpression(node)) {
165
181
  walkBinaryExpression(node, controlFlowDepth, context);
166
182
  return;
@@ -169,17 +185,24 @@ function walkComplexityNode(node: TypeScriptNode, controlFlowDepth: number, cont
169
185
  walkChildrenAtDepth(node, controlFlowDepth, context);
170
186
  }
171
187
 
172
- // Counts an if and keeps an `else if` at peer depth while ordinary else bodies stay nested.
188
+ /**
189
+ * Records the supplied if statement and its branches in the walk context's complexity totals.
190
+ * Uses the incoming depth for an early-exit guard and else-if peers; other branch bodies add a nesting level.
191
+ *
192
+ * @param node - Parsed `if` statement whose condition and branches are visited.
193
+ * @param controlFlowDepth - Incoming control-flow nesting depth before entering this statement.
194
+ * @param context - Walk state holding the mutable complexity accumulator and ownership set.
195
+ * @returns Nothing. Increments `ifCount` and recurses through the condition, then, and else branches.
196
+ */
173
197
  function walkIfStatement(node: import("typescript").IfStatement, controlFlowDepth: number, context: ComplexityWalkContext): void {
174
198
  context.accumulator.ifCount += 1;
175
- const nestedDepth = enterControlFlow(controlFlowDepth, context.accumulator);
199
+ const nestedDepth = isEarlyExitGuard(node) ? controlFlowDepth : enterControlFlow(controlFlowDepth, context.accumulator);
176
200
  walkComplexityNode(node.expression, nestedDepth, context);
177
201
  walkComplexityNode(node.thenStatement, nestedDepth, context);
178
- // A source without an else branch has no further control-flow subtree for the user to review.
179
202
  if (!node.elseStatement) {
180
203
  return;
181
204
  }
182
- // An `else if` is another peer decision, not an extra nesting layer created by AST parentage.
205
+ // Visit an else-if at the incoming depth so the chain stays a set of peer decisions.
183
206
  if (typescriptSyntax.isIfStatement(node.elseStatement)) {
184
207
  walkComplexityNode(node.elseStatement, controlFlowDepth, context);
185
208
  return;
@@ -187,39 +210,89 @@ function walkIfStatement(node: import("typescript").IfStatement, controlFlowDept
187
210
  walkComplexityNode(node.elseStatement, nestedDepth, context);
188
211
  }
189
212
 
190
- // Counts each logical binary node once; all other binary operators, including `??`, stay neutral.
213
+ /**
214
+ * Counts a logical AND or OR in the supplied walk context and visits both operands at the supplied depth.
215
+ * Other binary operators add no decision of their own.
216
+ *
217
+ * @param node - Binary expression syntax node to inspect for logical operators.
218
+ * @param controlFlowDepth - Current control-flow nesting depth passed to both operands.
219
+ * @param context - Walk state holding the accumulator updated with logical operator counts.
220
+ * @returns Nothing. Updates `logicalAndCount` or `logicalOrCount` in `context` and walks child operands.
221
+ */
191
222
  function walkBinaryExpression(node: import("typescript").BinaryExpression, controlFlowDepth: number, context: ComplexityWalkContext): void {
192
- // A user's logical AND adds one decision without changing nesting depth.
193
223
  if (node.operatorToken.kind === typescriptSyntax.SyntaxKind.AmpersandAmpersandToken) {
194
224
  context.accumulator.logicalAndCount += 1;
195
225
  }
196
- // A user's logical OR adds one decision without changing nesting depth.
197
226
  if (node.operatorToken.kind === typescriptSyntax.SyntaxKind.BarBarToken) {
198
227
  context.accumulator.logicalOrCount += 1;
199
228
  }
200
229
  walkChildrenAtDepth(node, controlFlowDepth, context);
201
230
  }
202
231
 
203
- // Enters one control construct, records the deepest user-visible level, and walks its children there.
232
+ /**
233
+ * Visits a control-flow construct's children one level deeper than the supplied depth.
234
+ *
235
+ * @param node - Control-flow construct whose children execute at increased nesting depth.
236
+ * @param controlFlowDepth - Control-flow nesting depth prior to entering this construct.
237
+ * @param context - Walk state whose accumulator tracks maximum nesting and child decisions.
238
+ * @returns Nothing. Updates maximum nesting and accumulates the children's decisions in the walk context.
239
+ */
204
240
  function walkNestedControlFlow(node: TypeScriptNode, controlFlowDepth: number, context: ComplexityWalkContext): void {
205
241
  const nestedDepth = enterControlFlow(controlFlowDepth, context.accumulator);
206
242
  walkChildrenAtDepth(node, nestedDepth, context);
207
243
  }
208
244
 
209
- // Visits every syntax child at an unchanged depth so punctuation and ordinary braces stay free.
245
+ /**
246
+ * Visits the supplied node's children at the given depth so ordinary braces add no nesting.
247
+ *
248
+ * @param node - Parent syntax node whose direct children are traversed.
249
+ * @param controlFlowDepth - Control-flow nesting depth preserved across the child traversal.
250
+ * @param context - Walk state used to enforce callable ownership and accumulate child measurements.
251
+ * @returns Nothing. Accumulates the children's measurements into the supplied walk context.
252
+ */
210
253
  function walkChildrenAtDepth(node: TypeScriptNode, controlFlowDepth: number, context: ComplexityWalkContext): void {
211
254
  // Every child stays with the nearest reported callable unless the ownership guard prunes it.
212
255
  node.forEachChild((child) => walkComplexityNode(child, controlFlowDepth, context));
213
256
  }
214
257
 
215
- // Advances and records control-flow depth for an if, loop, switch, catch, or ternary.
258
+ /**
259
+ * Enters a nested control-flow level and raises the supplied accumulator's maximum if the new depth exceeds it.
260
+ *
261
+ * @param controlFlowDepth - Current control-flow nesting depth before entering the construct.
262
+ * @param accumulator - Mutable complexity accumulator whose `maximumControlFlowNesting` is updated.
263
+ * @returns Current control-flow depth plus one.
264
+ */
216
265
  function enterControlFlow(controlFlowDepth: number, accumulator: ComplexityAccumulator): number {
217
266
  const nestedDepth = controlFlowDepth + 1;
218
267
  accumulator.maximumControlFlowNesting = Math.max(accumulator.maximumControlFlowNesting, nestedDepth);
219
268
  return nestedDepth;
220
269
  }
221
270
 
222
- // Recognizes every loop syntax counted by the public complexity policy.
271
+ /**
272
+ * Determines whether an `if` statement is an early-exit guard clause.
273
+ * A guard clause has no else and a body of one return, throw, break, or continue, braced or not.
274
+ *
275
+ * @param node - Parsed `if` statement to check for early-exit guard structure.
276
+ * @returns True when `node` has no `elseStatement` and a single exit statement body; otherwise false.
277
+ */
278
+ function isEarlyExitGuard(node: import("typescript").IfStatement): boolean {
279
+ if (node.elseStatement) {
280
+ return false;
281
+ }
282
+ const body = typescriptSyntax.isBlock(node.thenStatement) ? node.thenStatement.statements : [node.thenStatement];
283
+ const exit = body.length === 1 ? body[0] : undefined;
284
+ return exit !== undefined && (typescriptSyntax.isReturnStatement(exit)
285
+ || typescriptSyntax.isThrowStatement(exit)
286
+ || typescriptSyntax.isBreakStatement(exit)
287
+ || typescriptSyntax.isContinueStatement(exit));
288
+ }
289
+
290
+ /**
291
+ * Recognizes every loop syntax counted by the public complexity policy.
292
+ *
293
+ * @param node - Syntax node to test against `for`, `for..in`, `for..of`, `while`, and `do..while` forms.
294
+ * @returns True when `node` is one of the counted loop statement kinds; otherwise false.
295
+ */
223
296
  function isLoopStatement(node: TypeScriptNode): boolean {
224
297
  return typescriptSyntax.isForStatement(node)
225
298
  || typescriptSyntax.isForInStatement(node)
@@ -228,8 +301,11 @@ function isLoopStatement(node: TypeScriptNode): boolean {
228
301
  || typescriptSyntax.isDoStatement(node);
229
302
  }
230
303
 
231
- // Builds the fixed zero-valued metadata shape used when a source has no decisions.
232
- // It never throws because no source or parser state is read here.
304
+ /**
305
+ * Creates a fresh zeroed breakdown for the base measurement used when a callable has no computed metrics.
306
+ *
307
+ * @returns Fresh breakdown with every decision counter and `maxNesting` set to zero.
308
+ */
233
309
  function emptyBreakdown(): ComplexityBreakdown {
234
310
  return {
235
311
  if: 0,
@@ -1,18 +1,27 @@
1
1
  /*
2
- * Error class for user-facing config-load failures. CLI action handlers catch this specifically so
3
- * a malformed `.gruff-ts.yaml` produces a clean stderr message and exit code 2, instead of a raw
4
- * Node stack trace. The `suggestion` field carries the user-actionable next step (run init --force,
5
- * edit a specific value, etc.) so the CLI layer can format it consistently across all throw sites.
6
- * Reports a tagged error that the CLI layer recognises via `instanceof`.
2
+ * User-facing configuration and flag-conflict error caught by CLI command handlers to exit 2 cleanly.
3
+ *
4
+ * Carries a structured `suggestion` alongside the message so broken `.gruff-ts.yaml` files or invalid selectors print actionable guidance
5
+ * instead of a raw Node stack trace, and lets machine consumers distinguish load failures from CLI flag refusals via `isConfigLoadFailure`.
7
6
  */
8
7
  export class ConfigLoadError extends Error {
9
8
  readonly suggestion: string;
10
9
 
11
- // Stores the suggested fix alongside the message so the CLI formatter can render both without
12
- // re-deriving the suggestion from the error text. Throws nothing; this is a plain data wrapper.
13
- constructor(message: string, suggestion: string) {
10
+ /*
11
+ * True when the configuration itself could not be loaded, which is what a machine caller reads as a
12
+ * `config-error` diagnostic.
13
+ *
14
+ * False marks a refusal the caller asked for by combining flags. Nothing failed to load there, so there is no
15
+ * run-invalidating diagnostic to publish, and a report the run did produce must not be replaced by an empty one.
16
+ */
17
+ readonly isConfigLoadFailure: boolean;
18
+
19
+ // Creates the CLI error from the display message and suggested next step.
20
+ // The failure flag defaults to true. Pass false for a flag-related refusal that should omit the config-error diagnostic.
21
+ constructor(message: string, suggestion: string, isConfigLoadFailure = true) {
14
22
  super(message);
15
23
  this.name = "ConfigLoadError";
16
24
  this.suggestion = suggestion;
25
+ this.isConfigLoadFailure = isConfigLoadFailure;
17
26
  }
18
27
  }