@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,340 @@
1
+ // Applies supported ESLint, Biome, and zizmor inline suppressions to a user's scan.
2
+ //
3
+ // A developer can keep an existing tool directive where the corresponding Gruff finding appears.
4
+ // The report records each accepted suppression and combines duplicate findings about one call.
5
+ import { commentRecords } from "./comment-scanner.ts";
6
+ import { stripYamlComment } from "./config-parse.ts";
7
+ import type { SourceFile } from "./discovery.ts";
8
+ import type { Finding, SuppressedFinding, SuppressionSummary } from "./types.ts";
9
+
10
+ // Reason on each inline audit row; every port publishes these exact words (FAMILY-CONTRACT.md section 13c).
11
+ export const INLINE_SUPPRESSION_REASON = "Another tool's suppression comment names this check, so the finding is suppressed where it was written.";
12
+
13
+ // Reason on each repeated-claim audit row; every port publishes these exact words (FAMILY-CONTRACT.md section 13c).
14
+ export const DUPLICATE_SUPPRESSION_REASON = "Another rule reports the same claim on this line, so the line reports it once.";
15
+
16
+ // eslint rules section 13c names for gruff-ts, each with the rule that makes the same claim.
17
+ const ESLINT_RULES: ReadonlyMap<string, string> = new Map([
18
+ ["no-eval", "security.eval-call"],
19
+ ["no-new-func", "security.new-function"],
20
+ ]);
21
+
22
+ // biome rules section 13c names, each with the rule that makes the same claim.
23
+ const BIOME_RULES: ReadonlyMap<string, string> = new Map([
24
+ ["lint/security/noGlobalEval", "security.eval-call"],
25
+ ["lint/correctness/noUnusedImports", "waste.unused-import"],
26
+ ]);
27
+
28
+ // zizmor audits section 13c names, each with the workflow rule that makes the same claim.
29
+ const ZIZMOR_AUDITS: ReadonlyMap<string, string> = new Map([
30
+ ["unpinned-uses", "security.github-actions-unpinned-action"],
31
+ ["dangerous-triggers", "security.github-actions-pull-request-target"],
32
+ ]);
33
+
34
+ // Reads the scope and listed rules from an ESLint per-line directive before its written reason.
35
+ const ESLINT_DIRECTIVE = /^\s*(?:\/\/|\/\*)?\s*eslint-disable-(next-)?line\b([^\n]*)/;
36
+
37
+ // Captures the category after biome's ignore comment, such as `lint/security/noGlobalEval`, up to its `:` explanation.
38
+ const BIOME_DIRECTIVE = /^\s*(?:\/\/|\/\*)?\s*biome-ignore\s+([\w/]+)/;
39
+
40
+ // Captures zizmor's audit list in `# zizmor: ignore[unpinned-uses]`.
41
+ const ZIZMOR_DIRECTIVE = /#\s*zizmor:\s*ignore\[([^\]]*)\]/g;
42
+
43
+ // Matches an `eval(` call, the call on which security.unsafe-deserialization repeats security.eval-call's claim.
44
+ const EVAL_CALL = /\beval\s*\(/;
45
+
46
+ // Union of every rule that inline directives or duplicate eval-claim merging can touch,
47
+ // so full scans do not need to retain raw source text for files emitting only unrelated rules.
48
+ const INLINE_SUPPRESSION_RELEVANT_RULES: ReadonlySet<string> = new Set([
49
+ ...ESLINT_RULES.values(),
50
+ ...BIOME_RULES.values(),
51
+ ...ZIZMOR_AUDITS.values(),
52
+ "security.unsafe-deserialization",
53
+ ]);
54
+
55
+ /**
56
+ * Reports whether `ruleId` can ever be suppressed by a supported inline directive or merged as a duplicate eval claim.
57
+ *
58
+ * @param ruleId - native gruff rule identifier to check
59
+ * @returns True when inline-suppression or duplicate-claim checks may inspect the file's source text for this rule.
60
+ */
61
+ export function isInlineSuppressionRelevantRule(ruleId: string): boolean {
62
+ return INLINE_SUPPRESSION_RELEVANT_RULES.has(ruleId);
63
+ }
64
+
65
+ // A parsed comment and whether the line contains only that comment.
66
+ interface InlineComment {
67
+ text: string;
68
+ standsAlone: boolean;
69
+ }
70
+
71
+ // The lines and indexed comment tokens from one already scanned source snapshot.
72
+ interface InlineSource {
73
+ lines: string[];
74
+ comments: Map<number, InlineComment[]>;
75
+ }
76
+
77
+ /**
78
+ * Applies inline suppressions after sensitive exclusions and test-path skips, then combines overlapping findings.
79
+ * Invariant: the directive applies to the selected line only (for example, an ESLint next-line directive covers the line below).
80
+ * The audit records each removed finding so SARIF can still show it as suppressed.
81
+ *
82
+ * @param findings - Candidate findings from the scan to evaluate against inline directives and duplicate eval claims.
83
+ * @param suppressions - Existing suppression summary rows whose built-in count sets the starting index for new audit rows.
84
+ * @param sources - Scanned file snapshots keyed by file path so directives and source lines match the analysed text.
85
+ * @returns Kept findings, combined suppression summary rows, and suppressed finding records with justifications.
86
+ */
87
+ export function applyInlineSuppressions(
88
+ findings: readonly Finding[],
89
+ suppressions: readonly SuppressionSummary[],
90
+ sources: ReadonlyMap<string, { file: SourceFile; source: string }>,
91
+ ): { findings: Finding[]; suppressions: SuppressionSummary[]; suppressed: SuppressedFinding[] } {
92
+ const sourceCache = new Map<string, InlineSource>();
93
+ const kept: Finding[] = [];
94
+ const suppressed: SuppressedFinding[] = [];
95
+ // A finding leaves only when a comment on its line, or alone on the line above, names a check making its claim.
96
+ for (const finding of findings) {
97
+ if (!isInlineSuppressionRelevantRule(finding.ruleId)) {
98
+ kept.push(finding);
99
+ continue;
100
+ }
101
+ let source = sourceCache.get(finding.filePath);
102
+ const snapshot = sources.get(finding.filePath);
103
+ // Use the scanned snapshot so an editor save during the run cannot move a directive onto a different finding.
104
+ if (source === undefined && snapshot !== undefined) {
105
+ source = collectInlineSource(snapshot.source, snapshot.file);
106
+ sourceCache.set(finding.filePath, source);
107
+ }
108
+ // With no source snapshot or matching directive, leave the finding visible.
109
+ if (source && isCoveredByComment(source.comments, finding)) {
110
+ suppressed.push({ finding, justification: INLINE_SUPPRESSION_REASON });
111
+ continue;
112
+ }
113
+ kept.push(finding);
114
+ }
115
+ // Without recorded source lines, there is nothing to check for an overlapping claim on that line.
116
+ const merged = mergeRepeatedClaims(kept, (path) => sourceCache.get(path)?.lines ?? []);
117
+ // Built-in rows number among themselves; section 13c's rows continue that numbering.
118
+ const nextIndex = suppressions.filter((summary) => summary.source === "built-in").length;
119
+ const inlineRows = auditRows(suppressed, "inline", INLINE_SUPPRESSION_REASON, nextIndex);
120
+ const duplicateRows = auditRows(merged.removed, "duplicate", DUPLICATE_SUPPRESSION_REASON, nextIndex + inlineRows.length);
121
+ return {
122
+ findings: merged.kept,
123
+ suppressions: [...suppressions, ...inlineRows, ...duplicateRows],
124
+ suppressed: [...suppressed, ...merged.removed],
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Finds actual directives in the scanned text so a string containing an example cannot hide a finding.
130
+ * An empty comment map means the user's file supplies no supported inline directives.
131
+ *
132
+ * @param source - Raw scanned file text to split into lines and inspect for directive comments.
133
+ * @param file - Source file metadata indicating whether script comments or YAML workflow comments apply.
134
+ * @returns Split source lines paired with parsed inline comments indexed by 1-based line number.
135
+ */
136
+ function collectInlineSource(source: string, file: SourceFile): InlineSource {
137
+ const lines = source.split(/\r?\n/u);
138
+ const comments = new Map<number, InlineComment[]>();
139
+ // Most files contain no directive text. Their findings need no comment lookup.
140
+ if (!/eslint-disable-|biome-ignore|zizmor:/u.test(source)) {
141
+ return { lines, comments };
142
+ }
143
+ // Script comments can occur beside code or on their own line.
144
+ if (file.isScript) {
145
+ // Index each parsed comment by the line where the developer finished writing it.
146
+ for (const comment of commentRecords(source)) {
147
+ const startOfLine = source.lastIndexOf("\n", comment.startIndex - 1) + 1;
148
+ const endOfComment = comment.kind === "block" ? comment.endIndex + 1 : comment.endIndex;
149
+ const nextNewline = source.indexOf("\n", endOfComment);
150
+ // A comment at end of file can still belong to the final line.
151
+ const endOfLine = nextNewline < 0 ? source.length : nextNewline;
152
+ const standsAlone = source.slice(startOfLine, comment.startIndex).trim().length === 0
153
+ && source.slice(endOfComment, endOfLine).trim().length === 0;
154
+ // A line can have multiple comments. Keep each one so a later directive does not erase an earlier one.
155
+ const entries = comments.get(comment.endLine) ?? [];
156
+ entries.push({ text: comment.text, standsAlone });
157
+ comments.set(comment.endLine, entries);
158
+ }
159
+ // Workflow YAML can carry zizmor directives after a real comment marker.
160
+ } else if (/\.ya?ml$/iu.test(file.displayPath)) {
161
+ lines.forEach((line, index) => {
162
+ const content = stripYamlComment(line);
163
+ // A hash inside a quoted value remains part of the value.
164
+ if (content.length !== line.length) {
165
+ comments.set(index + 1, [{ text: line.slice(content.length), standsAlone: content.trim().length === 0 }]);
166
+ }
167
+ });
168
+ }
169
+ return { lines, comments };
170
+ }
171
+
172
+ /**
173
+ * Reports whether the finding's line, or a comment-only line directly above it, names a check making its claim.
174
+ * Invariant: only those two lines are read, so a comment never reaches past the line below it.
175
+ *
176
+ * @param comments - Parsed inline comments indexed by 1-based line number.
177
+ * @param finding - Finding whose line and ruleId are checked for a matching suppression directive.
178
+ * @returns True if a comment on the finding's line or a standalone comment on the preceding line covers its ruleId.
179
+ */
180
+ function isCoveredByComment(comments: ReadonlyMap<number, InlineComment[]>, finding: Finding): boolean {
181
+ // A finding with no line has no local directive to apply. Lines with no comments supply no matches.
182
+ const line = finding.line ?? 0;
183
+ return (comments.get(line) ?? []).some((comment) => hasCoveringComment(comment.text, finding.ruleId, false))
184
+ || (comments.get(line - 1) ?? []).some((comment) => comment.standsAlone && hasCoveringComment(comment.text, finding.ruleId, true));
185
+ }
186
+
187
+ /**
188
+ * Matches the developer's existing directive to the equivalent Gruff finding on the covered line.
189
+ *
190
+ * @param line - Comment text from the candidate line to test against supported directive formats.
191
+ * @param ruleId - Gruff rule identifier of the finding being evaluated.
192
+ * @param isPreviousLine - Whether the comment came from the line immediately preceding the finding.
193
+ * @returns True if an ESLint, Biome, or zizmor directive in the comment suppresses the given rule.
194
+ */
195
+ function hasCoveringComment(line: string, ruleId: string, isPreviousLine: boolean): boolean {
196
+ return isDisabledByEslint(line, ruleId, isPreviousLine)
197
+ || isIgnoredByBiome(line, ruleId, isPreviousLine)
198
+ || isIgnoredByZizmor(line, ruleId);
199
+ }
200
+
201
+ /**
202
+ * Applies the developer's ESLint directive on its intended line; an empty rule list covers every supported ESLint rule.
203
+ *
204
+ * @param line - Comment text tested for an ESLint line or next-line directive.
205
+ * @param ruleId - Gruff rule identifier to match against `ESLINT_RULES`.
206
+ * @param isPreviousLine - True when evaluating a standalone comment on the line above the finding, requiring a next-line directive.
207
+ * @returns True if the directive matches the line position and covers the given rule.
208
+ */
209
+ function isDisabledByEslint(line: string, ruleId: string, isPreviousLine: boolean): boolean {
210
+ const match = ESLINT_DIRECTIVE.exec(line);
211
+ // A same-line directive applies there. A next-line directive applies only one line down.
212
+ if (match === null || Boolean(match[1]) !== isPreviousLine) {
213
+ return false;
214
+ }
215
+ // The developer's reason after "--" is free text and cannot add a rule to the exclusion list.
216
+ const listed = (match[2] ?? "").split(/\s--|\*\//)[0] ?? "";
217
+ const names = listed.split(",").map((name) => name.trim()).filter((name) => name.length > 0);
218
+ return names.length === 0 ? [...ESLINT_RULES.values()].includes(ruleId) : names.some((name) => ESLINT_RULES.get(name) === ruleId);
219
+ }
220
+
221
+ /**
222
+ * Applies a developer's Biome ignore to the matching Gruff rule when the comment sits alone on the preceding line and names that rule or group.
223
+ * Biome directives apply only to the following node/line, so same-line trailing Biome ignore comments do not suppress findings.
224
+ *
225
+ * @param line - Comment text tested for a Biome ignore directive and rule category.
226
+ * @param ruleId - Gruff rule identifier to match against mapped Biome rules.
227
+ * @param isPreviousLine - True only when evaluating a standalone comment on the line directly above the finding.
228
+ * @returns True if the Biome ignore stands on the preceding line and matches the mapped rule or a parent group prefix.
229
+ */
230
+ function isIgnoredByBiome(line: string, ruleId: string, isPreviousLine: boolean): boolean {
231
+ if (!isPreviousLine) {
232
+ return false;
233
+ }
234
+ const category = BIOME_DIRECTIVE.exec(line)?.[1];
235
+ // Compare supported rule pairs so a group directive covers only the findings linked to that group.
236
+ for (const [biomeRule, gruffRule] of BIOME_RULES) {
237
+ // A missing Biome category leaves the finding visible. A group such as lint/security can cover multiple rules.
238
+ if (category && gruffRule === ruleId && (biomeRule === category || biomeRule.startsWith(`${category}/`))) {
239
+ return true;
240
+ }
241
+ }
242
+ return false;
243
+ }
244
+
245
+ /**
246
+ * Reports whether a `# zizmor: ignore[...]` directive names an audit mapped to the rule.
247
+ *
248
+ * @param line - Comment text scanned for `# zizmor: ignore[...]` directives.
249
+ * @param ruleId - Gruff rule identifier to match against `ZIZMOR_AUDITS`.
250
+ * @returns True if any listed zizmor audit maps to the given Gruff rule.
251
+ */
252
+ function isIgnoredByZizmor(line: string, ruleId: string): boolean {
253
+ for (const match of line.matchAll(ZIZMOR_DIRECTIVE)) {
254
+ if ((match[1] ?? "").split(",").some((audit) => ZIZMOR_AUDITS.get(audit.trim()) === ruleId)) {
255
+ return true;
256
+ }
257
+ }
258
+ return false;
259
+ }
260
+
261
+ /**
262
+ * Returns kept findings and justified removals after checking for duplicate claims about eval calls.
263
+ * A repeat stays in kept if its line is missing or fails the eval call pattern.
264
+ * Invariant: each security.eval-call finding stays in kept and can justify one security.unsafe-deserialization removal on its file and line.
265
+ *
266
+ * @param findings - Remaining findings after inline directive filtering.
267
+ * @param lines - Callback returning source lines by display path to verify `eval(` calls on the finding's line.
268
+ * @returns Object containing the kept findings and the removed duplicate-claim records.
269
+ */
270
+ function mergeRepeatedClaims(
271
+ findings: readonly Finding[],
272
+ lines: (displayPath: string) => readonly string[],
273
+ ): { kept: Finding[]; removed: SuppressedFinding[] } {
274
+ const evalCalls = new Map<string, number>();
275
+ // Count the eval-call findings per file and line, so each merges at most one repeat.
276
+ for (const finding of findings) {
277
+ if (finding.ruleId === "security.eval-call") {
278
+ const key = `${finding.filePath}\u0000${finding.line}`;
279
+ evalCalls.set(key, (evalCalls.get(key) ?? 0) + 1);
280
+ }
281
+ }
282
+ const kept: Finding[] = [];
283
+ const removed: SuppressedFinding[] = [];
284
+ for (const finding of findings) {
285
+ const key = `${finding.filePath}\u0000${finding.line}`;
286
+ // When the flow scanner records `sinkForm`, only merge `eval()` deserialization hits so a co-located `vm.runInNewContext()` survives.
287
+ const isEvalDeserialization = finding.metadata.sinkForm !== undefined
288
+ ? finding.metadata.sinkForm === "eval"
289
+ : EVAL_CALL.test(lines(finding.filePath)[(finding.line ?? 0) - 1] ?? "");
290
+ const isRepeat = finding.ruleId === "security.unsafe-deserialization" && (evalCalls.get(key) ?? 0) > 0 && isEvalDeserialization;
291
+ if (isRepeat) {
292
+ evalCalls.set(key, (evalCalls.get(key) ?? 0) - 1);
293
+ removed.push({ finding, justification: DUPLICATE_SUPPRESSION_REASON });
294
+ continue;
295
+ }
296
+ kept.push(finding);
297
+ }
298
+ return { kept, removed };
299
+ }
300
+
301
+ /**
302
+ * Folds removed findings into one audit row per file and rule, in UTF-8 byte order of path and then rule.
303
+ * Invariant: the rows are deterministic, and their indexes run contiguously from firstIndex.
304
+ *
305
+ * @param removed - Suppressed findings to aggregate by file path and rule identifier.
306
+ * @param source - Origin label (`"inline"` or `"duplicate"`) recorded on each generated summary row.
307
+ * @param reason - Justification text attached to every generated audit row.
308
+ * @param firstIndex - Zero-based starting index assigned to the first emitted summary row.
309
+ * @returns Deterministic list of suppression summary rows, or an empty list when no findings were removed.
310
+ */
311
+ function auditRows(removed: readonly SuppressedFinding[], source: "inline" | "duplicate", reason: string, firstIndex: number): SuppressionSummary[] {
312
+ const counts = new Map<string, { path: string; rule: string; count: number }>();
313
+ for (const { finding } of removed) {
314
+ const key = `${finding.filePath}\u0000${finding.ruleId}`;
315
+ const row = counts.get(key) ?? { path: finding.filePath, rule: finding.ruleId, count: 0 };
316
+ row.count += 1;
317
+ counts.set(key, row);
318
+ }
319
+ const sorted = [...counts.values()].sort((left, right) => compareUtf8Bytes(left.path, right.path) || compareUtf8Bytes(left.rule, right.rule));
320
+ return sorted.map((row, offset) => ({
321
+ index: firstIndex + offset,
322
+ rule: row.rule,
323
+ paths: [row.path],
324
+ symbol: null,
325
+ reason,
326
+ suppressed: row.count,
327
+ source,
328
+ }));
329
+ }
330
+
331
+ /**
332
+ * Returns a negative, zero, or positive number when left sorts before, equals, or follows right by UTF-8 bytes for audit ordering.
333
+ *
334
+ * @param left - First string to encode as UTF-8 and compare.
335
+ * @param right - Second string to encode as UTF-8 and compare.
336
+ * @returns Negative, zero, or positive byte comparison result from `Buffer.compare`.
337
+ */
338
+ function compareUtf8Bytes(left: string, right: string): number {
339
+ return Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8"));
340
+ }
@@ -0,0 +1,56 @@
1
+ // Splits size and complexity findings into lower and upper severity bands (FAMILY-CONTRACT.md section 12).
2
+ //
3
+ // A unit over its limit but under 1.5x receives an advisory notice not to grow; at 1.5x or above it keeps full severity and split advice.
4
+ // Finding messages stay identical across bands so baseline identities never churn when a unit crosses the boundary.
5
+
6
+ import type { Severity } from "./types.ts";
7
+
8
+ // The fixed ratio at which a finding moves into the upper band; no option changes it.
9
+ const UPPER_BAND_RATIO = 1.5;
10
+
11
+ export const LOWER_BAND_FUNCTION = "Do not add to this function; put new code in a new function.";
12
+ export const LOWER_BAND_FILE = "Do not add to this file; put new code in a new file.";
13
+ export const LOWER_BAND_PARAMETER = "Do not add another parameter to this function.";
14
+ export const SPLIT_FILE = "Split this file by responsibility, one responsibility per file.";
15
+ export const SPLIT_FUNCTION = "Split this function at its steps, one step per function.";
16
+ export const GROUP_PARAMETERS = "Group the parameters that travel together into one object, or split the function by caller.";
17
+ export const SIMPLIFY_PATH = "Simplify the execution path: return early, merge branches that lead to the same result, and drop flags that steer later branches. Moving branches into helpers leaves the path as hard to follow.";
18
+
19
+ /** The value of a banded finding's `limitBand` metadata key. */
20
+ export type LimitBand = "lower" | "upper";
21
+
22
+ // The severity, advice and band key one banded finding carries.
23
+ export interface BandedFields {
24
+ severity: Severity;
25
+ remediation: string;
26
+ limitBand: LimitBand;
27
+ }
28
+
29
+ /**
30
+ * Names the band a measured value falls in against the limit in force, compared without rounding.
31
+ *
32
+ * @param measured - Observed size or complexity value for the unit under analysis.
33
+ * @param limit - Threshold in force against which `measured` is compared at `UPPER_BAND_RATIO`.
34
+ * @returns `"upper"` when `measured` is at least `UPPER_BAND_RATIO * limit`, otherwise `"lower"`.
35
+ */
36
+ export function limitBand(measured: number, limit: number): LimitBand {
37
+ return measured >= UPPER_BAND_RATIO * limit ? "upper" : "lower";
38
+ }
39
+
40
+ /**
41
+ * Returns severity, remediation and band fields by comparing `measured` with `limit` for a size or complexity finding.
42
+ * The lower band uses `"advisory"` and `lowerAdvice`; the upper band uses `configuredSeverity` and `upperAdvice`.
43
+ *
44
+ * @param measured - Observed size or complexity value for the unit under analysis.
45
+ * @param limit - Threshold in force passed to `limitBand` to select `"lower"` or `"upper"`.
46
+ * @param configuredSeverity - Severity applied when the finding lands in the upper band.
47
+ * @param lowerAdvice - Remediation message used when the finding lands in the lower band.
48
+ * @param upperAdvice - Remediation message used when the finding lands in the upper band.
49
+ * @returns Banded fields containing the selected severity, remediation text, and `limitBand`.
50
+ */
51
+ export function bandedFields(measured: number, limit: number, configuredSeverity: Severity, lowerAdvice: string, upperAdvice: string): BandedFields {
52
+ const band = limitBand(measured, limit);
53
+ return band === "lower"
54
+ ? { severity: "advisory", remediation: lowerAdvice, limitBand: band }
55
+ : { severity: configuredSeverity, remediation: upperAdvice, limitBand: band };
56
+ }