@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.
- package/CHANGELOG.md +123 -1
- package/CONTRIBUTING.md +32 -25
- package/README.md +55 -46
- package/SECURITY.md +18 -30
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -13
- package/docs/agent-hook.md +33 -24
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +173 -71
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -157
- package/docs/rules.md +140 -106
- package/package.json +10 -8
- package/src/analyser.ts +886 -282
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +85 -55
- package/src/blocks.ts +579 -364
- package/src/changed-regions.ts +414 -65
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +461 -302
- package/src/cli-program.ts +956 -166
- package/src/cli.ts +9 -2
- package/src/comment-rules.ts +277 -414
- package/src/comment-scanner.ts +363 -44
- package/src/complexity-metrics.ts +320 -0
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +778 -210
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +188 -61
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +521 -148
- package/src/doc-rules.ts +592 -147
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +240 -89
- package/src/findings.ts +48 -24
- package/src/fixture-purpose-rules.ts +226 -48
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +336 -106
- package/src/hook-contract.ts +708 -211
- package/src/init-config.ts +169 -114
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -419
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +33 -107
- package/src/parsed-script.ts +1206 -0
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +97 -71
- package/src/project-config-rules.ts +335 -146
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +284 -0
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +864 -195
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +255 -52
- package/src/security-flow-rules.ts +930 -109
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +502 -375
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +380 -148
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +422 -228
- package/src/text-scans.ts +67 -9
- package/src/types.ts +222 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -153
- package/src/test-fixtures.ts +0 -668
package/src/findings-helpers.ts
CHANGED
|
@@ -3,13 +3,182 @@
|
|
|
3
3
|
// on it without forming a cycle.
|
|
4
4
|
import { execFileSync } from "node:child_process";
|
|
5
5
|
import { basename } from "node:path";
|
|
6
|
+
import { ruleSeverity } from "./config.ts";
|
|
6
7
|
import type { SourceFile } from "./discovery.ts";
|
|
7
8
|
import { makeFinding } from "./findings.ts";
|
|
8
|
-
import type { Finding, Pillar, Severity } from "./types.ts";
|
|
9
|
+
import type { Config, Finding, Pillar, Severity } from "./types.ts";
|
|
9
10
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Extracts named entries from parameter-list text for per-parameter rules, omitting destructured or unrecognized entries.
|
|
13
|
+
* Each entry has name, raw text without supported modifiers or rest dots, and isParameterProperty set when a modifier was removed.
|
|
14
|
+
*
|
|
15
|
+
* @param params - raw parameter-list text inside a signature's parentheses
|
|
16
|
+
* @returns matching parameter entries with stripped raw text and parameter-property flags, or an empty array on empty input
|
|
17
|
+
*/
|
|
18
|
+
export function parameterNames(params: string): Array<{ name: string; raw: string; isParameterProperty: boolean }> {
|
|
19
|
+
return splitTopLevelParameters(params)
|
|
20
|
+
.map((parameter) => parameter.trim())
|
|
21
|
+
.filter(Boolean)
|
|
22
|
+
.map((raw) => {
|
|
23
|
+
const modifiers = raw.match(/^(?:(?:public|private|protected|readonly|override)\s+)*/)?.[0] ?? "";
|
|
24
|
+
const stripped = raw.slice(modifiers.length).replace(/^\.\.\./, "");
|
|
25
|
+
const name = stripped.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\s*(?=[?:=]|$)/)?.[1] ?? "";
|
|
26
|
+
return { name, raw: stripped, isParameterProperty: modifiers !== "" };
|
|
27
|
+
})
|
|
28
|
+
.filter((parameter) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(parameter.name));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Nesting and quote context for the parameter splitter. Kept as one mutable record so the
|
|
32
|
+
// per-character helpers stay small enough to read at a glance.
|
|
33
|
+
interface ParameterSplitState {
|
|
34
|
+
parenthesisDepth: number;
|
|
35
|
+
bracketDepth: number;
|
|
36
|
+
braceDepth: number;
|
|
37
|
+
angleDepth: number;
|
|
38
|
+
quote: string;
|
|
39
|
+
isEscaped: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Splits parameter-list text into original substrings at top-level commas, keeping quoted and nested commas within each parameter.
|
|
44
|
+
* Preserves whitespace and empty segments so `parameterNames` can filter them out.
|
|
45
|
+
*
|
|
46
|
+
* @param params - raw parameter-list text to split at top-level commas
|
|
47
|
+
* @returns original parameter substrings, or a single empty string on empty input
|
|
48
|
+
*/
|
|
49
|
+
function splitTopLevelParameters(params: string): string[] {
|
|
50
|
+
const parameters: string[] = [];
|
|
51
|
+
const state: ParameterSplitState = { parenthesisDepth: 0, bracketDepth: 0, braceDepth: 0, angleDepth: 0, quote: "", isEscaped: false };
|
|
52
|
+
let start = 0;
|
|
53
|
+
for (let index = 0; index < params.length; index += 1) {
|
|
54
|
+
const character = params[index] ?? "";
|
|
55
|
+
if (advanceParameterQuoteState(state, character)) {
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (character === "," && isTopLevelParameterPosition(state)) {
|
|
59
|
+
parameters.push(params.slice(start, index));
|
|
60
|
+
start = index + 1;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
advanceParameterDepths(state, params, index, start);
|
|
64
|
+
}
|
|
65
|
+
parameters.push(params.slice(start));
|
|
66
|
+
return parameters;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Updates quote and escape tracking in place so string contents are not treated as parameter structure.
|
|
71
|
+
*
|
|
72
|
+
* @param state - mutable splitter state whose `quote` and `isEscaped` fields are updated
|
|
73
|
+
* @param character - current character being scanned from the parameter list
|
|
74
|
+
* @returns true when `character` belongs to quoted text or opens a quote, or false when the caller should inspect it as a delimiter
|
|
75
|
+
*/
|
|
76
|
+
function advanceParameterQuoteState(state: ParameterSplitState, character: string): boolean {
|
|
77
|
+
if (state.quote !== "") {
|
|
78
|
+
if (state.isEscaped) {
|
|
79
|
+
state.isEscaped = false;
|
|
80
|
+
} else if (character === "\\") {
|
|
81
|
+
state.isEscaped = true;
|
|
82
|
+
} else if (character === state.quote) {
|
|
83
|
+
state.quote = "";
|
|
84
|
+
}
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
if (character === '"' || character === "'" || character === "`") {
|
|
88
|
+
state.quote = character;
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Updates nesting depths in place for the character at `index` so nested commas do not split parameters.
|
|
96
|
+
* Uses `start` as the current parameter's starting offset when recognizing type arguments.
|
|
97
|
+
*
|
|
98
|
+
* @param state - mutable splitter state whose parenthesis, bracket, brace, and angle depths are updated
|
|
99
|
+
* @param params - full parameter-list text being scanned
|
|
100
|
+
* @param index - zero-based character offset in `params` to inspect
|
|
101
|
+
* @param start - zero-based starting offset of the current parameter segment in `params`
|
|
102
|
+
* @returns Nothing. Mutates `state` nesting depths in place.
|
|
103
|
+
*/
|
|
104
|
+
function advanceParameterDepths(state: ParameterSplitState, params: string, index: number, start: number): void {
|
|
105
|
+
const character = params[index] ?? "";
|
|
106
|
+
if (character === "(") state.parenthesisDepth += 1;
|
|
107
|
+
else if (character === ")") state.parenthesisDepth = Math.max(0, state.parenthesisDepth - 1);
|
|
108
|
+
else if (character === "[") state.bracketDepth += 1;
|
|
109
|
+
else if (character === "]") state.bracketDepth = Math.max(0, state.bracketDepth - 1);
|
|
110
|
+
else if (character === "{") state.braceDepth += 1;
|
|
111
|
+
else if (character === "}") state.braceDepth = Math.max(0, state.braceDepth - 1);
|
|
112
|
+
else if (character === "<" && opensTypeArgumentList(params, index, start)) state.angleDepth += 1;
|
|
113
|
+
else if (character === ">" && state.angleDepth > 0 && params[index - 1] !== "=") state.angleDepth -= 1;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Checks whether the splitter sits outside every nesting kind, because a comma splits parameters only at top level.
|
|
118
|
+
*
|
|
119
|
+
* @param state - current splitter nesting depths to inspect
|
|
120
|
+
* @returns true only when parenthesis, bracket, brace, and angle depths are all zero
|
|
121
|
+
*/
|
|
122
|
+
function isTopLevelParameterPosition(state: ParameterSplitState): boolean {
|
|
123
|
+
return state.parenthesisDepth === 0 && state.bracketDepth === 0 && state.braceDepth === 0 && state.angleDepth === 0;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Determines whether the `<` at `index` opens a type-argument list so its commas stay within the parameter.
|
|
128
|
+
* A colon without `=` marks type context; otherwise the matching `>` must precede optional space and `(`.
|
|
129
|
+
* Rejects unrecognized prefixes and unmatched brackets to avoid treating comparison operators as type delimiters.
|
|
130
|
+
*
|
|
131
|
+
* @param params - full parameter-list text being scanned
|
|
132
|
+
* @param index - zero-based offset of the `<` character in `params`
|
|
133
|
+
* @param parameterStart - zero-based starting offset of the current parameter segment bounding the prefix
|
|
134
|
+
* @returns true when the prefix and matching `>` indicate a type-argument list, or false otherwise
|
|
135
|
+
*/
|
|
136
|
+
function opensTypeArgumentList(params: string, index: number, parameterStart: number): boolean {
|
|
137
|
+
const prefix = params.slice(parameterStart, index);
|
|
138
|
+
const previousCharacter = params[index - 1] ?? "";
|
|
139
|
+
const isTypeContext = prefix.includes(":") && !prefix.includes("=");
|
|
140
|
+
const followsTokenWithoutWhitespace = previousCharacter !== "" && !/\s/.test(previousCharacter);
|
|
141
|
+
const startsGenericArrowDefault = /=\s*$/.test(prefix);
|
|
142
|
+
if (!isTypeContext && !followsTokenWithoutWhitespace && !startsGenericArrowDefault) {
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
let depth = 1;
|
|
146
|
+
for (let cursor = index + 1; cursor < params.length; cursor += 1) {
|
|
147
|
+
const character = params[cursor] ?? "";
|
|
148
|
+
if (character === "<") depth += 1;
|
|
149
|
+
else if (character === ">" && params[cursor - 1] !== "=") {
|
|
150
|
+
depth -= 1;
|
|
151
|
+
if (depth === 0) {
|
|
152
|
+
const isFollowedByCallParameters = /^\s*\(/.test(params.slice(cursor + 1));
|
|
153
|
+
return isTypeContext || isFollowedByCallParameters;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Applies rules.<id>.severity while preserving the finding's stable fingerprint.
|
|
162
|
+
* Lower-band notices and unbuilt build-output bin advisories keep their assigned severity so starter configs do not promote them.
|
|
163
|
+
*
|
|
164
|
+
* @param config - effective configuration supplying any override for this finding's rule
|
|
165
|
+
* @param finding - scanner result to check. Lower-band and unbuilt-output advisories keep their assigned severity.
|
|
166
|
+
* @returns - the original finding if its severity stands, or a copy carrying the configured severity
|
|
167
|
+
*/
|
|
168
|
+
export function applyConfiguredSeverity(config: Config, finding: Finding): Finding {
|
|
169
|
+
// A lower-band size or complexity finding is advisory whatever severity the user configured (FAMILY-CONTRACT.md
|
|
170
|
+
// section 12, search `Size and complexity findings in two bands`). Unbuilt dist/build/lib bin targets keep advisory
|
|
171
|
+
// severity for the same reason: starter configs pin `design.package-bin-missing` to `warning`.
|
|
172
|
+
if (finding.metadata.limitBand === "lower" || finding.metadata.unbuiltOutput === true) {
|
|
173
|
+
return finding;
|
|
174
|
+
}
|
|
175
|
+
const severity = ruleSeverity(config, finding.ruleId, finding.severity);
|
|
176
|
+
return severity === finding.severity ? finding : { ...finding, severity };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Input bundle for `finding()`, defining the stable contract for line-anchored findings.
|
|
180
|
+
//
|
|
181
|
+
// Defaults (`confidence: "high"`, empty `metadata`) are filled inside `finding()`, and analysis then stamps each rule's catalogue confidence.
|
|
13
182
|
export interface LineFindingArgs {
|
|
14
183
|
ruleId: string;
|
|
15
184
|
message: string;
|
|
@@ -17,19 +186,31 @@ export interface LineFindingArgs {
|
|
|
17
186
|
line: number;
|
|
18
187
|
severity: Severity;
|
|
19
188
|
pillar: Pillar;
|
|
189
|
+
// The rule's advice; omitted, the finding carries none and consumers fall back to the catalogue.
|
|
190
|
+
remediation?: string | undefined;
|
|
20
191
|
}
|
|
21
192
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
193
|
+
/**
|
|
194
|
+
* Builds a high-confidence, symbol-free finding for a per-line report entry.
|
|
195
|
+
* Uses `args.file.displayPath` and `args.line` for location and omits empty remediation text.
|
|
196
|
+
*
|
|
197
|
+
* @param args - rule, message, file, line, severity, pillar, and optional remediation fields
|
|
198
|
+
* @returns finding whose fingerprint hashes ruleId, filePath, line, and an empty symbol slot
|
|
199
|
+
*/
|
|
25
200
|
export function finding(args: LineFindingArgs): Finding {
|
|
26
|
-
return makeFinding({
|
|
201
|
+
return makeFinding({
|
|
202
|
+
ruleId: args.ruleId, message: args.message, filePath: args.file.displayPath, line: args.line, severity: args.severity, pillar: args.pillar,
|
|
203
|
+
confidence: "high", ...(args.remediation ? { remediation: args.remediation } : {}),
|
|
204
|
+
});
|
|
27
205
|
}
|
|
28
206
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
207
|
+
/**
|
|
208
|
+
* Collects slash-normalized Git paths for `staged`, `unstaged`, `working-tree`, or a revision compared with the working tree.
|
|
209
|
+
* Spawns Git without a shell and places revision arguments after `--end-of-options`; command failures propagate to the caller.
|
|
210
|
+
*
|
|
211
|
+
* @param mode - diff selection mode (`staged`, `unstaged`, `working-tree`, or a Git revision)
|
|
212
|
+
* @returns set of matching slash-normalized paths (including non-ignored untracked paths in working-tree mode), or an empty set when none match
|
|
213
|
+
*/
|
|
33
214
|
export function changedFiles(mode: string): Set<string> {
|
|
34
215
|
if (mode === "staged") {
|
|
35
216
|
return gitPathSet(["diff", "--name-only", "--cached"]);
|
|
@@ -43,28 +224,45 @@ export function changedFiles(mode: string): Set<string> {
|
|
|
43
224
|
return gitPathSet(["diff", "--name-only", "--end-of-options", mode]);
|
|
44
225
|
}
|
|
45
226
|
|
|
46
|
-
|
|
47
|
-
|
|
227
|
+
/**
|
|
228
|
+
* Spawns Git through `execFileSync` without a shell and normalizes output paths; Git failures propagate to the caller.
|
|
229
|
+
*
|
|
230
|
+
* @param args - Git subcommand and option arguments passed directly without shell interpolation
|
|
231
|
+
* @returns set of non-empty output paths with backslashes converted to slashes, or an empty set when Git emits no paths
|
|
232
|
+
*/
|
|
48
233
|
function gitPathSet(args: string[]): Set<string> {
|
|
49
234
|
return new Set(execFileSync("git", args, { encoding: "utf8" }).split(/\r?\n/).filter(Boolean).map((line) => line.replaceAll("\\", "/")));
|
|
50
235
|
}
|
|
51
236
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
237
|
+
/**
|
|
238
|
+
* Strips directory segments and any trailing extension so `naming.class-file-mismatch` can normalize file stems.
|
|
239
|
+
* Both sides must agree on this canonical form for the deterministic comparison to be meaningful.
|
|
240
|
+
*
|
|
241
|
+
* @param path - source file path whose base stem is extracted
|
|
242
|
+
* @returns file name without parent directories or its final dot extension
|
|
243
|
+
*/
|
|
55
244
|
export function fileBaseName(path: string): string {
|
|
56
245
|
return basename(path).replace(/\.[^.]+$/, "");
|
|
57
246
|
}
|
|
58
247
|
|
|
59
|
-
|
|
60
|
-
|
|
248
|
+
/**
|
|
249
|
+
* Normalizes an identifier to a lowercase ASCII alphanumeric key so naming rules can compare across case styles.
|
|
250
|
+
* Treats `FooBar`, `foo_bar`, and `foo-bar` as the same key.
|
|
251
|
+
*
|
|
252
|
+
* @param identifier - source identifier to strip and lowercase
|
|
253
|
+
* @returns lowercase ASCII alphanumeric key, or an empty string when `identifier` contains no ASCII letters or digits
|
|
254
|
+
*/
|
|
61
255
|
export function normalizedIdentifier(identifier: string): string {
|
|
62
256
|
return identifier.replace(/[^A-Za-z0-9]/g, "").toLowerCase();
|
|
63
257
|
}
|
|
64
258
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
259
|
+
/**
|
|
260
|
+
* Splits an identifier into lowercase ASCII word tokens for naming comparisons.
|
|
261
|
+
* Splits where an ASCII lowercase letter or digit precedes an uppercase letter and at non-alphanumeric runs, keeping uppercase runs together.
|
|
262
|
+
*
|
|
263
|
+
* @param identifier - source identifier to tokenize into lowercase words
|
|
264
|
+
* @returns lowercase word tokens (for example `HTTPServer` yields `["httpserver"]`), or an empty array when no ASCII letters or digits exist
|
|
265
|
+
*/
|
|
68
266
|
export function splitIdentifierWords(identifier: string): string[] {
|
|
69
267
|
return identifier
|
|
70
268
|
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
@@ -73,81 +271,34 @@ export function splitIdentifierWords(identifier: string): string[] {
|
|
|
73
271
|
.filter(Boolean);
|
|
74
272
|
}
|
|
75
273
|
|
|
76
|
-
|
|
77
|
-
|
|
274
|
+
/**
|
|
275
|
+
* Computes the zero-based line number at a character offset in source text.
|
|
276
|
+
* Negative offsets select the first line so they cannot index from the end, and offsets beyond the end select the final line.
|
|
277
|
+
*
|
|
278
|
+
* @param source - full text in which lines are counted by newline characters
|
|
279
|
+
* @param index - zero-based character offset clamped at zero
|
|
280
|
+
* @returns zero-based line number containing the clamped offset
|
|
281
|
+
*/
|
|
78
282
|
export function lineOffset(source: string, index: number): number {
|
|
79
283
|
return source.slice(0, Math.max(0, index)).split("\n").length - 1;
|
|
80
284
|
}
|
|
81
285
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
}
|
|
89
|
-
const uncommented = trimmed.replace(/^\/\/+\s?/, "");
|
|
90
|
-
if (isCommentSeparatorOrAnchor(uncommented)) {
|
|
91
|
-
return false;
|
|
92
|
-
}
|
|
93
|
-
return isDisabledDeclaration(uncommented) || isDisabledControlFlow(uncommented) || isDisabledCall(uncommented);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// Skips prose examples, labels, search anchors, and section dividers that often begin with code words.
|
|
97
|
-
function isCommentSeparatorOrAnchor(uncommented: string): boolean {
|
|
98
|
-
const text = uncommented.trim();
|
|
99
|
-
return (
|
|
100
|
-
text === "" ||
|
|
101
|
-
/^[-=*_#]{3,}$/.test(text) ||
|
|
102
|
-
/^[A-Za-z_$][A-Za-z0-9_$]*\s*:\s*['"`[{]/.test(text) ||
|
|
103
|
-
/\b(?:search|grep|anchor|example|for example|e\.g\.)\s*:/.test(text) ||
|
|
104
|
-
/^(?!(?:if|for|while|switch)\b)[A-Za-z_$][A-Za-z0-9_$]*\s+\([^;{}]*[A-Za-z][^;{}]*\)$/.test(text) ||
|
|
105
|
-
/^[A-Z][A-Za-z0-9_$]*(?:\s|\s*\([^)]*\)$)/.test(text)
|
|
106
|
-
);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// Declarations must carry their syntactic partner (`=`, `{`, `from`, etc.) to count as disabled code.
|
|
110
|
-
function isDisabledDeclaration(uncommented: string): boolean {
|
|
111
|
-
return (
|
|
112
|
-
/^(?:const|let|var)\s+[A-Za-z_$][A-Za-z0-9_$]*\s*=/.test(uncommented) ||
|
|
113
|
-
/^(?:async\s+)?function\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\(/.test(uncommented) ||
|
|
114
|
-
/^class\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s+extends\s+[A-Za-z_$][A-Za-z0-9_$]*)?\s*\{?/.test(uncommented) ||
|
|
115
|
-
/^interface\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{?/.test(uncommented) ||
|
|
116
|
-
/^type\s+[A-Za-z_$][A-Za-z0-9_$]*\s*=/.test(uncommented) ||
|
|
117
|
-
/^enum\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{?/.test(uncommented) ||
|
|
118
|
-
/^import\s+(?:["'][^"']+["']|.+\s+from\s+["'][^"']+["'])/.test(uncommented) ||
|
|
119
|
-
/^export\s+(?:\{|\*|(?:default\s+)?(?:const|let|var|function|class|interface|type|enum)\b)/.test(uncommented)
|
|
120
|
-
);
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
// Control-flow comments need real syntax such as parentheses or an expression after `return`/`throw`.
|
|
124
|
-
function isDisabledControlFlow(uncommented: string): boolean {
|
|
125
|
-
return /^(?:if|for|while|switch)\s*\(/.test(uncommented) || /^(?:return|throw|await)\s+\S/.test(uncommented);
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
// Keep single-line disabled calls; heading/prose guards above filter labels such as `Rules (...)`.
|
|
129
|
-
function isDisabledCall(uncommented: string): boolean {
|
|
130
|
-
return /^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)?\s*\([^)]*\);?$/.test(uncommented);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// Lowercase membership test against the configured banned-names set. Drives the
|
|
134
|
-
// `naming.identifier-quality` predicate so the rule stays a single Set lookup per identifier.
|
|
135
|
-
export function isGenericName(name: string, bannedNames: Set<string>): boolean {
|
|
136
|
-
return bannedNames.has(name.toLowerCase());
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
// Escapes the standard regex metacharacters so user-supplied strings (rule IDs, identifiers,
|
|
140
|
-
// paths) can be embedded in dynamic patterns without altering their meaning. Hot path -
|
|
141
|
-
// used by every rule that builds a per-source RegExp.
|
|
286
|
+
/**
|
|
287
|
+
* Escapes standard regex metacharacters so user-supplied strings (rule IDs, identifiers, paths) can be embedded in dynamic patterns literally.
|
|
288
|
+
*
|
|
289
|
+
* @param source - raw string to escape for safe inclusion in a `RegExp` pattern
|
|
290
|
+
* @returns string with regex metacharacters backslash-escaped
|
|
291
|
+
*/
|
|
142
292
|
export function escapeRegex(source: string): string {
|
|
143
293
|
return source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
144
294
|
}
|
|
145
295
|
|
|
146
|
-
|
|
147
|
-
*
|
|
148
|
-
*
|
|
149
|
-
*
|
|
150
|
-
*
|
|
296
|
+
/**
|
|
297
|
+
* Accumulates rule counts so that summary rows can be rendered without scanning the findings again.
|
|
298
|
+
* Each total must equal the sum of errors, warnings and advisories.
|
|
299
|
+
*
|
|
300
|
+
* @param findings - report results to group by rule and count by severity
|
|
301
|
+
* @returns a map of totals and severity counts keyed by rule ID, or an empty map when there are no findings
|
|
151
302
|
*/
|
|
152
303
|
export function countRuleSeverities(findings: Finding[]): Map<string, { total: number; error: number; warning: number; advisory: number }> {
|
|
153
304
|
const counts = new Map<string, { total: number; error: number; warning: number; advisory: number }>();
|
package/src/findings.ts
CHANGED
|
@@ -1,15 +1,22 @@
|
|
|
1
|
-
// Finding
|
|
1
|
+
// Finding construction keeps report fields, baseline fingerprints, and cross-edit identities consistent.
|
|
2
|
+
//
|
|
3
|
+
// Rules provide user-facing evidence through one shared input shape.
|
|
4
|
+
// This module omits absent fields and adds deterministic identifiers before any renderer or baseline sees the finding.
|
|
2
5
|
import { createHash } from "node:crypto";
|
|
3
6
|
import type { Confidence, Finding, Pillar, Severity } from "./types.ts";
|
|
4
7
|
|
|
5
|
-
//
|
|
6
|
-
//
|
|
8
|
+
// Describes the evidence one rule supplies before a complete user-facing finding is built.
|
|
9
|
+
//
|
|
10
|
+
// Optional locations and guidance stay absent when the rule cannot provide them.
|
|
11
|
+
// Stable contract: centralized identifiers make every report and baseline interpret the same occurrence consistently.
|
|
7
12
|
interface FindingInput {
|
|
8
13
|
ruleId: string;
|
|
9
14
|
message: string;
|
|
10
15
|
filePath: string;
|
|
11
16
|
line?: number;
|
|
12
17
|
endLine?: number;
|
|
18
|
+
// The optional one-based column separates same-line occurrences in reports without changing the baseline fingerprint (ADR-017).
|
|
19
|
+
column?: number;
|
|
13
20
|
severity: Severity;
|
|
14
21
|
pillar: Pillar;
|
|
15
22
|
confidence: Confidence;
|
|
@@ -18,38 +25,55 @@ interface FindingInput {
|
|
|
18
25
|
metadata?: Record<string, unknown>;
|
|
19
26
|
}
|
|
20
27
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
28
|
+
/**
|
|
29
|
+
* Builds a report finding with a stable baseline fingerprint and cross-edit identity, omitting absent optional fields.
|
|
30
|
+
*
|
|
31
|
+
* @param findingInput - Rule evidence supplying the rule id, message, file path, severity, pillar, confidence, and optional location or metadata.
|
|
32
|
+
* @returns The complete finding carrying deterministic `fingerprint` and `stableIdentity` hashes.
|
|
33
|
+
*/
|
|
34
|
+
function makeFinding(findingInput: FindingInput): Finding {
|
|
35
|
+
// Missing line or symbol values occupy stable empty slots so that the fields keep their positions in the fingerprint input.
|
|
25
36
|
const fingerprint = createHash("sha256")
|
|
26
|
-
.update([
|
|
37
|
+
.update([findingInput.ruleId, findingInput.filePath, findingInput.line ?? "", findingInput.symbol ?? ""].join("\0"))
|
|
27
38
|
.digest("hex")
|
|
28
39
|
.slice(0, 16);
|
|
40
|
+
// Omits missing or zero coordinates and empty optional text so consumers can treat them as unavailable. Missing metadata becomes an empty object.
|
|
29
41
|
return {
|
|
30
|
-
ruleId:
|
|
31
|
-
message:
|
|
32
|
-
filePath:
|
|
33
|
-
...(
|
|
34
|
-
...(
|
|
35
|
-
|
|
36
|
-
|
|
42
|
+
ruleId: findingInput.ruleId,
|
|
43
|
+
message: findingInput.message,
|
|
44
|
+
filePath: findingInput.filePath,
|
|
45
|
+
...(findingInput.line ? { line: findingInput.line } : {}),
|
|
46
|
+
...(findingInput.endLine ? { endLine: findingInput.endLine } : {}),
|
|
47
|
+
...(findingInput.column ? { column: findingInput.column } : {}),
|
|
48
|
+
severity: findingInput.severity,
|
|
49
|
+
pillar: findingInput.pillar,
|
|
37
50
|
secondaryPillars: [],
|
|
38
51
|
tier: "v0.1",
|
|
39
|
-
confidence:
|
|
40
|
-
...(
|
|
41
|
-
...(
|
|
42
|
-
metadata:
|
|
52
|
+
confidence: findingInput.confidence,
|
|
53
|
+
...(findingInput.symbol ? { symbol: findingInput.symbol } : {}),
|
|
54
|
+
...(findingInput.remediation ? { remediation: findingInput.remediation } : {}),
|
|
55
|
+
metadata: findingInput.metadata ?? {},
|
|
43
56
|
fingerprint,
|
|
44
|
-
stableIdentity: stableIdentityFor(
|
|
57
|
+
stableIdentity: stableIdentityFor(findingInput),
|
|
45
58
|
};
|
|
46
59
|
}
|
|
47
60
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
61
|
+
/**
|
|
62
|
+
* Builds the line-insensitive identity external diff tools use to track a finding across edits.
|
|
63
|
+
*
|
|
64
|
+
* @param findingInput - Rule evidence supplying the rule id, file path, symbol or message, and optional column to separate same-line occurrences.
|
|
65
|
+
* @returns A deterministic 16-character hex SHA-256 prefix that distinguishes same-line occurrences without storing secret-derived text.
|
|
66
|
+
*/
|
|
67
|
+
function stableIdentityFor(findingInput: FindingInput): string {
|
|
68
|
+
// Empty or missing symbols cannot identify the user's code, so those findings fall back to their user-facing message.
|
|
69
|
+
const hasNamedSymbol = typeof findingInput.symbol === "string" && findingInput.symbol.length > 0;
|
|
70
|
+
const symbolOrMessage = hasNamedSymbol ? findingInput.symbol : findingInput.message;
|
|
71
|
+
// A named symbol already identifies the user's code; otherwise a known column keeps same-line occurrences separate.
|
|
72
|
+
const occurrenceIdentity = hasNamedSymbol || findingInput.column === undefined
|
|
73
|
+
? symbolOrMessage
|
|
74
|
+
: `${symbolOrMessage}\0column:${findingInput.column}`;
|
|
51
75
|
return createHash("sha256")
|
|
52
|
-
.update([
|
|
76
|
+
.update([findingInput.ruleId, findingInput.filePath, occurrenceIdentity].join("\0"))
|
|
53
77
|
.digest("hex")
|
|
54
78
|
.slice(0, 16);
|
|
55
79
|
}
|