@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.
- package/CHANGELOG.md +82 -0
- package/CONTRIBUTING.md +32 -25
- package/README.md +49 -50
- package/SECURITY.md +18 -31
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -10
- package/docs/agent-hook.md +32 -35
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +160 -89
- 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 -172
- package/docs/rules.md +126 -98
- package/package.json +10 -8
- package/src/analyser.ts +817 -323
- 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 +62 -68
- package/src/blocks.ts +512 -336
- package/src/changed-regions.ts +380 -79
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +445 -436
- package/src/cli-program.ts +915 -172
- package/src/cli.ts +9 -3
- package/src/comment-rules.ts +236 -418
- package/src/comment-scanner.ts +339 -47
- package/src/complexity-metrics.ts +111 -35
- 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 +751 -223
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +182 -54
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +493 -140
- package/src/doc-rules.ts +602 -126
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +134 -109
- package/src/findings.ts +47 -27
- package/src/fixture-purpose-rules.ts +194 -50
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +328 -121
- package/src/hook-contract.ts +681 -255
- package/src/init-config.ts +163 -118
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -468
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +32 -127
- package/src/parsed-script.ts +868 -314
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +86 -74
- package/src/project-config-rules.ts +324 -140
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +102 -38
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +821 -203
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +249 -55
- package/src/security-flow-rules.ts +791 -115
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +460 -387
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +378 -104
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +343 -253
- package/src/text-scans.ts +62 -11
- package/src/types.ts +220 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -163
- package/src/test-fixtures.ts +0 -671
package/src/analyser.ts
CHANGED
|
@@ -1,37 +1,46 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// File overview: Builds the analysis report used by the CLI, dashboard, and coding-agent hook.
|
|
2
|
+
//
|
|
3
|
+
// A command such as `gruff-ts analyse src --diff staged` still reads project context before selecting findings from staged changes.
|
|
4
|
+
// This module also applies reviewed findings from a baseline and records history after a valid full scan.
|
|
4
5
|
import { Buffer, isUtf8 } from "node:buffer";
|
|
5
|
-
import { readFileSync } from "node:fs";
|
|
6
|
+
import { readFileSync, statSync } from "node:fs";
|
|
6
7
|
import { cwd } from "node:process";
|
|
7
|
-
import {
|
|
8
|
+
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
8
9
|
import { recordHistory, sortedUniqueFindings } from "./baseline.ts";
|
|
10
|
+
import { declarationPositionFromSpans, findingIdentities, type DeclarationSpan } from "./baseline-identity.ts";
|
|
9
11
|
import { applyBaselineOptions, type BaselineApplication } from "./baseline-options.ts";
|
|
10
|
-
import { changedRegionScope, filterChangedFindings, filterScopedDiagnostics } from "./changed-regions.ts";
|
|
11
|
-
import { loadConfig,
|
|
12
|
+
import { CHANGED_REGION_DIAGNOSTIC_TYPE, ChangedRegionError, changedRegionScope, filterChangedFindings, filterScopedDiagnostics, type ChangedRegionScope } from "./changed-regions.ts";
|
|
13
|
+
import { loadConfig, optionBoolean, ruleEnabled, ruleSeverity, threshold } from "./config.ts";
|
|
14
|
+
import { applyInlineSuppressions, isInlineSuppressionRelevantRule } from "./inline-suppressions.ts";
|
|
15
|
+
import { applyBuiltInTestPathSkip, partitionSensitiveExclusions } from "./sensitive-exclusions.ts";
|
|
12
16
|
import { VERSION } from "./constants.ts";
|
|
13
17
|
import { absolutize, discoverSources, displayPath, type SourceFile } from "./discovery.ts";
|
|
14
18
|
import { makeFinding } from "./findings.ts";
|
|
15
19
|
import { applyConfiguredSeverity, finding, parameterNames } from "./findings-helpers.ts";
|
|
16
20
|
import { commentRecords, type CommentRecord } from "./comment-scanner.ts";
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
21
|
+
import { catalogueConfidence } from "./rules.ts";
|
|
22
|
+
import { analyseArchitectureRules, analyseCircularImportRule, buildProjectIndex, CIRCULAR_IMPORT_RULE_ID, extractImportStatements, isProductionSourcePath, isTestPath, type ProjectSource } from "./project-rules.ts";
|
|
23
|
+
import { analyseBlockMeasures, analyseBlockRules, type BlockRuleContext, blockRuleContext, type FunctionBlock, functionBlocks, measuredOnlyFunctionBlocks } from "./blocks.ts";
|
|
24
|
+
import { bandedFields, LOWER_BAND_FILE, SPLIT_FILE } from "./limit-band.ts";
|
|
25
|
+
import { analyseClassRules } from "./class-rules.ts";
|
|
20
26
|
import { analyseDeadCode, analyseUnreachable, analyseUnusedImports } from "./dead-code-rules.ts";
|
|
21
27
|
import { analyseCommentQualityRules } from "./comment-rules.ts";
|
|
22
28
|
import { analyseDocRules, analyseFileOverviewDoc, analyseInterfaceDocs } from "./doc-rules.ts";
|
|
23
29
|
import { analyseLineRules } from "./line-rules.ts";
|
|
24
30
|
import { analyseSecurityFlow } from "./security-flow-rules.ts";
|
|
25
|
-
import {
|
|
31
|
+
import { pushIdentifierQualityAt, pushShortVariableAt } from "./naming-pushers.ts";
|
|
26
32
|
import { analyseTestBlock } from "./test-block-rules.ts";
|
|
33
|
+
import { analyseDuplicateTestGroups } from "./duplicate-test-group-rules.ts";
|
|
27
34
|
import { analyseGithubActionsRules } from "./github-actions-rules.ts";
|
|
28
35
|
import { analyseProjectConfigRules } from "./project-config-rules.ts";
|
|
36
|
+
import { BUILT_IN_PROFILES } from "./profiles.ts";
|
|
29
37
|
import { ruleDescriptors } from "./rules.ts";
|
|
30
38
|
import { scoreReport, summarize } from "./scoring.ts";
|
|
39
|
+
import { isExecutionRequested } from "./selectors.ts";
|
|
31
40
|
import { analyseSensitiveData } from "./sensitive-data-rules.ts";
|
|
32
|
-
import { parseScript, type ParsedScript } from "./parsed-script.ts";
|
|
41
|
+
import { codeLineFlags, maskDecorators, parseScript, type ParsedScript } from "./parsed-script.ts";
|
|
33
42
|
import { maskNonCode, maskTemplateLiteralBodies } from "./source-text.ts";
|
|
34
|
-
import type { AnalysisOptions, AnalysisReport, Config, Finding, Pillar, RunDiagnostic, ScanSurfaceNote, SkippedPath } from "./types.ts";
|
|
43
|
+
import type { AnalysisOptions, AnalysisReport, Config, Finding, OutputFormat, Pillar, RunDiagnostic, ScanSurfaceNote, SkippedPath, SuppressedFinding, SuppressionSummary } from "./types.ts";
|
|
35
44
|
|
|
36
45
|
/*
|
|
37
46
|
* Internal hook view contract: both reports come from one current-tree scan so full-file and
|
|
@@ -43,105 +52,380 @@ export interface HookAnalysisReports {
|
|
|
43
52
|
}
|
|
44
53
|
|
|
45
54
|
/**
|
|
46
|
-
*
|
|
55
|
+
* Build a report for an `analyse`, `summary`, or `report` request.
|
|
56
|
+
* Invariant: an invalid scan or any changed-region scan is excluded from the user's full-scan score history.
|
|
47
57
|
*
|
|
48
|
-
* @param
|
|
49
|
-
* @returns
|
|
58
|
+
* @param requestedOptions - paths, rules, and scan scope. An empty path list scans the launch directory. Omit history to skip writing it.
|
|
59
|
+
* @returns A report ready for the caller's formatter. An unreadable changed scope returns a diagnostic and an empty findings list.
|
|
60
|
+
* @throws ConfigLoadError for invalid configuration. Unexpected scope errors propagate to the caller.
|
|
50
61
|
*/
|
|
51
|
-
export function analyse(
|
|
62
|
+
export function analyse(requestedOptions: AnalysisOptions): AnalysisReport {
|
|
63
|
+
const options = targetsFromLaunchDirectory(requestedOptions);
|
|
52
64
|
const preparation = prepareAnalysis(options);
|
|
53
|
-
|
|
54
|
-
|
|
65
|
+
let changedScope: ChangedRegionScope | undefined;
|
|
66
|
+
try {
|
|
67
|
+
changedScope = changedRegionScope(options, preparation.projectRoot);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
// A typo in `--changed-ranges` or a missing Git ref can be reported as an invalid scan before writing a baseline.
|
|
70
|
+
if (!(error instanceof ChangedRegionError)) {
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
return failedRunReport(preparation.projectRoot, options.format, CHANGED_REGION_DIAGNOSTIC_TYPE, error.message);
|
|
74
|
+
}
|
|
75
|
+
const run = completeAnalysis(preparation, options, "diagnose", changedScope);
|
|
55
76
|
const changedResult = filterChangedFindings(run.baselineResult.findings, changedScope, run.scanned.sources);
|
|
56
77
|
|
|
57
|
-
|
|
58
|
-
|
|
78
|
+
// Generation uses the full scan, so errors anywhere in that scan must stay visible.
|
|
79
|
+
const diagnostics = options.generateBaseline ? run.diagnostics : filterScopedDiagnostics(run.diagnostics, changedScope);
|
|
80
|
+
const suppressedFindings = filterChangedSuppressedFindings(run.suppressedFindings, changedScope, run.scanned.sources);
|
|
81
|
+
const baseline = run.baselineResult.baseline;
|
|
82
|
+
// When a baseline was applied, `--fail-on-new` counts only unreviewed findings that remain in the requested scope.
|
|
83
|
+
const scopedBaseline = {
|
|
84
|
+
...run.baselineResult,
|
|
85
|
+
findings: changedResult.findings,
|
|
86
|
+
...(changedScope !== undefined && baseline && !baseline.generated
|
|
87
|
+
? { baseline: { ...baseline, newFindings: changedResult.findings.length } }
|
|
88
|
+
: {}),
|
|
89
|
+
};
|
|
90
|
+
const report = reportFromRun({ ...run, diagnostics, suppressedFindings }, options, scopedBaseline, changedResult.suppressedCount);
|
|
91
|
+
// An invalid baseline, a changed-region scan, or a partial-catalogue scan cannot add a point to the user's full-scan trend history.
|
|
92
|
+
if (
|
|
93
|
+
options.historyFile
|
|
94
|
+
&& changedScope === undefined
|
|
95
|
+
&& !(options.execution && isExecutionRequested(options.execution))
|
|
96
|
+
&& !diagnostics.some((diagnostic) => diagnostic.invalidatesRun !== false)
|
|
97
|
+
) {
|
|
98
|
+
recordHistory(run.projectRoot, options.historyFile, report.score, report.findings.length, diagnostics);
|
|
59
99
|
}
|
|
100
|
+
return report;
|
|
101
|
+
}
|
|
60
102
|
|
|
61
|
-
|
|
62
|
-
|
|
103
|
+
/**
|
|
104
|
+
* Filters inline-suppressed SARIF records to the active changed-region scope while keeping whole-scan suppression audit rows untouched.
|
|
105
|
+
* Invariant: preserves the input order and returns the original list unchanged when unscoped or empty.
|
|
106
|
+
*
|
|
107
|
+
* @param suppressedFindings - full-scan inline/duplicate suppressed findings retained for SARIF output
|
|
108
|
+
* @param scope - active changed-region scope, or undefined for a full scan
|
|
109
|
+
* @param sources - retained source/AST snapshots used to evaluate symbol-level changed-region membership
|
|
110
|
+
* @returns Suppressed findings inside `scope`, or the original list unchanged when unscoped or empty.
|
|
111
|
+
*/
|
|
112
|
+
function filterChangedSuppressedFindings(
|
|
113
|
+
suppressedFindings: SuppressedFinding[],
|
|
114
|
+
scope: ChangedRegionScope | undefined,
|
|
115
|
+
sources: Map<string, { file: SourceFile; source: string; parsed?: ParsedScript }>,
|
|
116
|
+
): SuppressedFinding[] {
|
|
117
|
+
if (scope === undefined || suppressedFindings.length === 0) {
|
|
118
|
+
return suppressedFindings;
|
|
119
|
+
}
|
|
120
|
+
const kept = new Set(filterChangedFindings(suppressedFindings.map((entry) => entry.finding), scope, sources).findings);
|
|
121
|
+
return suppressedFindings.filter((entry) => kept.has(entry.finding));
|
|
63
122
|
}
|
|
64
123
|
|
|
65
|
-
|
|
66
|
-
|
|
124
|
+
/**
|
|
125
|
+
* Build the full and changed-region views the hook needs to distinguish a new finding from one already covered by a baseline.
|
|
126
|
+
* Both views use one read of the user's files. With no change selector, both fields point to that full scan.
|
|
127
|
+
*
|
|
128
|
+
* @param currentOptions - full-scan options resolved from the launch directory
|
|
129
|
+
* @param scopedOptions - change-scoped options providing the diff or range selector and formatting choices
|
|
130
|
+
* @param hasChangedRegion - true when scopedOptions selects a changed region; false skips scope resolution
|
|
131
|
+
* @returns Both reports sharing one file scan; when hasChangedRegion is false, scopedReport aliases currentReport.
|
|
132
|
+
*/
|
|
67
133
|
export function analyseHookReports(currentOptions: AnalysisOptions, scopedOptions: AnalysisOptions, hasChangedRegion: boolean): HookAnalysisReports {
|
|
68
|
-
|
|
134
|
+
currentOptions = targetsFromLaunchDirectory(currentOptions);
|
|
135
|
+
scopedOptions = targetsFromLaunchDirectory(scopedOptions);
|
|
136
|
+
// A hook without `--diff`, `--since`, or `--changed-ranges` has no narrower view to resolve.
|
|
137
|
+
const scopedChangedScope = hasChangedRegion ? changedRegionScope(scopedOptions, projectRootFromTargets(scopedOptions.paths)) : undefined;
|
|
138
|
+
const run = completeAnalysis(prepareAnalysis(currentOptions), currentOptions, "throw", scopedChangedScope);
|
|
69
139
|
const currentReport = reportFromRun(run, currentOptions, run.baselineResult);
|
|
140
|
+
// An unscoped hook presents the same findings it uses for baseline comparison.
|
|
70
141
|
if (!hasChangedRegion) {
|
|
71
142
|
return { currentReport, scopedReport: currentReport };
|
|
72
143
|
}
|
|
73
|
-
const scopedChangedScope = changedRegionScope(scopedOptions);
|
|
74
144
|
const scopedChangedResult = filterChangedFindings(run.baselineResult.findings, scopedChangedScope, run.scanned.sources);
|
|
145
|
+
const scopedSuppressedFindings = filterChangedSuppressedFindings(run.suppressedFindings, scopedChangedScope, run.scanned.sources);
|
|
75
146
|
// Same file-scoped diagnostics policy as diff-scoped analyse, so both surfaces agree.
|
|
76
|
-
const scopedReport = reportFromRun(
|
|
147
|
+
const scopedReport = reportFromRun(
|
|
148
|
+
{ ...run, diagnostics: filterScopedDiagnostics(run.diagnostics, scopedChangedScope), suppressedFindings: scopedSuppressedFindings },
|
|
149
|
+
scopedOptions,
|
|
150
|
+
{ ...run.baselineResult, findings: scopedChangedResult.findings },
|
|
151
|
+
scopedChangedResult.suppressedCount,
|
|
152
|
+
);
|
|
77
153
|
return { currentReport, scopedReport };
|
|
78
154
|
}
|
|
79
155
|
|
|
80
|
-
|
|
156
|
+
/**
|
|
157
|
+
* Choose the directory that owns the user's scan configuration, Git diff, and report paths.
|
|
158
|
+
* Use the launch directory for local targets and the common parent for targets outside it.
|
|
159
|
+
*
|
|
160
|
+
* @param paths - Scan targets resolved from the launch directory; an empty list selects the launch directory.
|
|
161
|
+
* @returns The launch directory or a common ancestor. A lone missing external target uses its parent so JSON can name the missing file.
|
|
162
|
+
* @throws When targets cannot share a filesystem root.
|
|
163
|
+
*/
|
|
164
|
+
export function projectRootFromTargets(paths: string[]): string {
|
|
165
|
+
const launchDirectory = cwd();
|
|
166
|
+
|
|
167
|
+
// No target was named, so the directory the command ran from is the project.
|
|
168
|
+
if (paths.length === 0) {
|
|
169
|
+
return launchDirectory;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
let common: string | null = null;
|
|
173
|
+
// A later usable target can widen the common directory because the root must contain every usable target.
|
|
174
|
+
for (const path of paths) {
|
|
175
|
+
const absolute = resolve(launchDirectory, path);
|
|
176
|
+
let directory = absolute;
|
|
177
|
+
try {
|
|
178
|
+
// A file contributes its containing directory because reported paths need a directory anchor.
|
|
179
|
+
if (!statSync(absolute).isDirectory()) {
|
|
180
|
+
directory = dirname(absolute);
|
|
181
|
+
}
|
|
182
|
+
} catch {
|
|
183
|
+
// A typo such as `analyse ../app/mising.ts` keeps a project-relative diagnostic. A missing file in a list cannot move its root.
|
|
184
|
+
if (paths.length !== 1) {
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
directory = dirname(absolute);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// The first target sets the starting answer; later ones can only widen it.
|
|
191
|
+
if (common === null) {
|
|
192
|
+
common = directory;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
// Expand the root until all usable targets can share one project-relative report.
|
|
196
|
+
while (!isSameOrDescendant(directory, common)) {
|
|
197
|
+
const parent = dirname(common);
|
|
198
|
+
// Reaching a filesystem root without containing this target means no single root can anchor both paths.
|
|
199
|
+
if (parent === common) {
|
|
200
|
+
throw new Error("scan targets do not share a filesystem root");
|
|
201
|
+
}
|
|
202
|
+
common = parent;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Keep the launch directory when no target was usable or their shared root is inside it, preserving config and baseline anchoring.
|
|
207
|
+
if (common === null || isSameOrDescendant(common, launchDirectory)) {
|
|
208
|
+
return launchDirectory;
|
|
209
|
+
}
|
|
210
|
+
return common;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Invariant: explicit paths keep their launch-directory meaning when a target selects a different project root.
|
|
215
|
+
* For example, `analyse ../app --baseline reviewed.json` still reads `reviewed.json` from the launch directory.
|
|
216
|
+
*
|
|
217
|
+
* @param options - Scan options with paths from the command line. Omitted baseline and history options stay omitted.
|
|
218
|
+
* @returns The original options for a local scan, or a copy with absolute targets and baseline and history paths pointing to the same files.
|
|
219
|
+
*/
|
|
220
|
+
function targetsFromLaunchDirectory(options: AnalysisOptions): AnalysisOptions {
|
|
221
|
+
const launchDirectory = cwd();
|
|
222
|
+
const projectRoot = projectRootFromTargets(options.paths);
|
|
223
|
+
// Inside the launch directory the root and the operands already agree, so they are passed on exactly as typed.
|
|
224
|
+
if (projectRoot === launchDirectory) {
|
|
225
|
+
return options;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Re-anchor a launch-directory path option against projectRoot while keeping absolute paths untouched.
|
|
229
|
+
*
|
|
230
|
+
* @param path - file path supplied relative to launchDirectory or as an absolute path
|
|
231
|
+
* @returns Path unchanged when absolute, or relative to projectRoot when resolved from launchDirectory.
|
|
232
|
+
*/
|
|
233
|
+
const fromRoot = (path: string): string => (isAbsolute(path) ? path : relative(projectRoot, resolve(launchDirectory, path)));
|
|
234
|
+
// Keep a relative CLI `--profile` file path anchored to the launch directory, while leaving built-in profile names untouched.
|
|
235
|
+
const anchoredProfile = options.profile !== undefined && !BUILT_IN_PROFILES.has(options.profile) && !BUILT_IN_PROFILES.has(`gruff.${options.profile}`)
|
|
236
|
+
? fromRoot(options.profile)
|
|
237
|
+
: options.profile;
|
|
238
|
+
return {
|
|
239
|
+
...options,
|
|
240
|
+
paths: options.paths.map((path) => resolve(launchDirectory, path)),
|
|
241
|
+
...(anchoredProfile !== undefined ? { profile: anchoredProfile } : {}),
|
|
242
|
+
...(options.baseline ? { baseline: fromRoot(options.baseline) } : {}),
|
|
243
|
+
...(options.generateBaseline ? { generateBaseline: fromRoot(options.generateBaseline) } : {}),
|
|
244
|
+
...(options.migrateBaseline ? { migrateBaseline: fromRoot(options.migrateBaseline) } : {}),
|
|
245
|
+
...(options.historyFile ? { historyFile: fromRoot(options.historyFile) } : {}),
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Check whether a target is inside a launch or scan directory using native path separators.
|
|
251
|
+
* Use this before accepting multiple targets so `/work/apidocs` is treated as a sibling of `/work/api`.
|
|
252
|
+
*
|
|
253
|
+
* @param candidate - Directory being tested.
|
|
254
|
+
* @param ancestor - Directory that may contain it.
|
|
255
|
+
* @returns True when candidate is the ancestor or sits inside it.
|
|
256
|
+
*/
|
|
257
|
+
function isSameOrDescendant(candidate: string, ancestor: string): boolean {
|
|
258
|
+
const fromAncestor = relative(ancestor, candidate);
|
|
259
|
+
return !isAbsolute(fromAncestor) && fromAncestor !== ".." && !fromAncestor.startsWith(`..${sep}`);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Resolve project inputs and configuration needed before scanning files.
|
|
264
|
+
*
|
|
265
|
+
* @param options - scan options specifying target paths, config overrides, and discovery settings
|
|
266
|
+
* @returns The project root, loaded config, discovered inputs, and an empty diagnostic array selected by options for a scan.
|
|
267
|
+
*/
|
|
81
268
|
function prepareAnalysis(options: AnalysisOptions): AnalysisPreparation {
|
|
82
|
-
const projectRoot =
|
|
269
|
+
const projectRoot = projectRootFromTargets(options.paths);
|
|
83
270
|
const config = loadConfig(projectRoot, options);
|
|
84
271
|
const diagnostics: RunDiagnostic[] = [];
|
|
85
272
|
const discovery = discoverSources(projectRoot, options, config);
|
|
86
273
|
return { projectRoot, config, diagnostics, discovery };
|
|
87
274
|
}
|
|
88
275
|
|
|
89
|
-
|
|
90
|
-
|
|
276
|
+
/**
|
|
277
|
+
* Give a finding its rule's catalogue confidence, so list-rules, the hook gate and the score read one value. A rule helper's
|
|
278
|
+
* default must not override the catalogue. The fingerprint and stable identity do not include confidence, so both stay unchanged.
|
|
279
|
+
*
|
|
280
|
+
* @param finding - scanner result for a rule the catalogue normally lists
|
|
281
|
+
* @returns the same finding when its confidence already matches, a copy carrying the catalogue confidence otherwise, or the
|
|
282
|
+
* finding unchanged for a rule id the catalogue does not list
|
|
283
|
+
*/
|
|
284
|
+
function withCatalogueConfidence(finding: Finding): Finding {
|
|
285
|
+
const confidence = catalogueConfidence(finding.ruleId);
|
|
286
|
+
return confidence === undefined || confidence === finding.confidence ? finding : { ...finding, confidence };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Run the checks for the user's resolved project and apply its exclusions and baseline.
|
|
291
|
+
* Invariant: assign baseline identities before filtering so the hook and SARIF can refer to the same finding.
|
|
292
|
+
*
|
|
293
|
+
* @param preparation - project scope, discovery and config, with the caller's diagnostic array to append to
|
|
294
|
+
* @param options - scope and baseline choices. An unset baseline path lets the scan use the project's default when enabled.
|
|
295
|
+
* @param unusableBaseline - `throw` lets the hook report a refusal. `diagnose` keeps findings and adds a fatal baseline diagnostic.
|
|
296
|
+
* @param changedScope - optional changed-region scope indicating which files need retained source and AST snapshots for symbol expansion
|
|
297
|
+
* @returns Findings, diagnostics, and suppression counts for rendering. An empty findings list can still have diagnostics.
|
|
298
|
+
* @throws {BaselineFileError} - a baseline file failure in throw mode.
|
|
299
|
+
*/
|
|
300
|
+
function completeAnalysis(
|
|
301
|
+
preparation: AnalysisPreparation,
|
|
302
|
+
options: AnalysisOptions,
|
|
303
|
+
unusableBaseline: "throw" | "diagnose" = "throw",
|
|
304
|
+
changedScope?: ChangedRegionScope,
|
|
305
|
+
): AnalysisRun {
|
|
91
306
|
const { projectRoot, config, diagnostics, discovery } = preparation;
|
|
92
307
|
pushMissingPathDiagnostics(discovery.missingPaths, diagnostics);
|
|
93
308
|
|
|
94
|
-
const scanned = scanDiscoveredSources(discovery.files, config, diagnostics);
|
|
309
|
+
const scanned = scanDiscoveredSources(discovery.files, config, diagnostics, changedScope);
|
|
95
310
|
const allFindings = sortedUniqueFindings([
|
|
96
311
|
...scanned.findings,
|
|
97
312
|
...analyseProjectIndex(projectRoot, options, discovery.files, scanned.projectSources, config).filter((finding) => ruleEnabled(config, finding.ruleId)),
|
|
98
|
-
].map((finding) => applyConfiguredSeverity(config, finding)));
|
|
99
|
-
|
|
313
|
+
].map((finding) => applyConfiguredSeverity(config, withCatalogueConfidence(finding))));
|
|
314
|
+
// An approved sensitive exclusion removes the finding from the report and gate, but its audit count still covers the full scan.
|
|
315
|
+
const excluded = partitionSensitiveExclusions(allFindings, config.sensitiveExclusions);
|
|
316
|
+
// A configured entry claims its findings first, so its count stays what the user wrote it for.
|
|
317
|
+
const testPathSkipped = applyBuiltInTestPathSkip(excluded.findings, excluded.suppressions);
|
|
318
|
+
// Assign baseline identities before filtering so hiding one declaration cannot renumber another in SARIF or the hook.
|
|
319
|
+
const spans = scanned.declarationSpans;
|
|
320
|
+
const namedFindings = withBaselineIdentities(testPathSkipped.findings, spans);
|
|
321
|
+
// Apply inline suppressions to findings with identities so SARIF can still identify a suppressed result.
|
|
322
|
+
const inline = applyInlineSuppressions(namedFindings, testPathSkipped.suppressions, scanned.sources);
|
|
323
|
+
// A missing file or parse error makes `--generate-baseline` unsafe because it would save a partial review.
|
|
324
|
+
const baselineResult = options.generateBaseline && diagnostics.some((diagnostic) => diagnostic.invalidatesRun !== false)
|
|
325
|
+
? { findings: inline.findings, diagnostics: [] }
|
|
326
|
+
: applyBaselineOptions(projectRoot, options, inline.findings, spans, unusableBaseline);
|
|
327
|
+
// A baseline collision records a non-fatal diagnostic and leaves every finding with that identity visible.
|
|
328
|
+
diagnostics.push(...baselineResult.diagnostics);
|
|
100
329
|
const notes = [...discovery.notes, ...scanned.notes];
|
|
101
|
-
|
|
330
|
+
// A selective scan scores only pillars backed by enabled rules. Omitting selectors keeps the normal score denominator.
|
|
331
|
+
const evaluatedPillars = options.execution && isExecutionRequested(options.execution)
|
|
332
|
+
? ruleDescriptors().filter((rule) => ruleEnabled(config, rule.ruleId)).map((rule) => rule.pillar)
|
|
333
|
+
: undefined;
|
|
334
|
+
return { projectRoot, discovery, diagnostics, scanned, baselineResult, notes, evaluatedPillars, suppressions: inline.suppressions, suppressedFindings: inline.suppressed };
|
|
102
335
|
}
|
|
103
336
|
|
|
104
|
-
|
|
337
|
+
/**
|
|
338
|
+
* Builds the analysis report from the findings selected for this command.
|
|
339
|
+
* Invariant: suppression audit counts cover the full scan, even when the report shows only the requested changes.
|
|
340
|
+
*
|
|
341
|
+
* @param run - completed scan supplying discovery totals, diagnostics, notes and suppression records
|
|
342
|
+
* @param options - request inputs and threshold. No explicit inputs are shown as "." for a project scan.
|
|
343
|
+
* @param baselineResult - the selected findings and any baseline details. No baseline leaves out the review section.
|
|
344
|
+
* @param suppressedCount - number of findings omitted by changed-region filtering. Omit it to leave the field out of the report.
|
|
345
|
+
* @returns Native report state with the supplied findings, scan totals, and any baseline or changed-region count supplied.
|
|
346
|
+
*/
|
|
105
347
|
function reportFromRun(run: AnalysisRun, options: AnalysisOptions, baselineResult: BaselineApplication, suppressedCount?: number): AnalysisReport {
|
|
106
|
-
return buildAnalysisReport(run.projectRoot, options, run.discovery, run.diagnostics, baselineResult, run.notes, suppressedCount);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// Assembles the run's payload; the field shape is the stable gruff.analysis.v2 schema contract.
|
|
110
|
-
function buildAnalysisReport(
|
|
111
|
-
projectRoot: string,
|
|
112
|
-
options: AnalysisOptions,
|
|
113
|
-
discovery: DiscoverySummary,
|
|
114
|
-
diagnostics: RunDiagnostic[],
|
|
115
|
-
baselineResult: BaselineApplication,
|
|
116
|
-
notes: ScanSurfaceNote[],
|
|
117
|
-
suppressedCount?: number,
|
|
118
|
-
): AnalysisReport {
|
|
119
348
|
const findings = baselineResult.findings;
|
|
120
349
|
return {
|
|
121
|
-
schemaVersion: "gruff.analysis.
|
|
350
|
+
schemaVersion: "gruff.analysis.v3",
|
|
122
351
|
tool: { name: "gruff-ts", version: VERSION },
|
|
123
352
|
run: {
|
|
124
|
-
projectRoot,
|
|
353
|
+
projectRoot: run.projectRoot,
|
|
125
354
|
format: options.format,
|
|
126
355
|
failOn: options.failOn,
|
|
127
356
|
generatedAt: new Date().toISOString(),
|
|
357
|
+
// Record explicit inputs as absolute paths so they keep their launch-directory meaning if the project root differs.
|
|
358
|
+
// With no explicit input, a single dot denotes the default project scan.
|
|
359
|
+
inputs: options.paths.length === 0 ? ["."] : options.paths.map((path) => resolve(cwd(), path)),
|
|
360
|
+
...(options.config === undefined ? {} : { config: resolve(cwd(), options.config) }),
|
|
361
|
+
...(options.shouldIncludeIgnored ? { includeIgnored: true as const } : {}),
|
|
128
362
|
},
|
|
129
363
|
summary: summarize(findings),
|
|
130
364
|
paths: {
|
|
131
|
-
analysedFiles: discovery.files.length,
|
|
132
|
-
ignoredPaths: discovery.ignoredPaths,
|
|
133
|
-
skipped: discovery.skipped,
|
|
134
|
-
missingPaths: discovery.missingPaths,
|
|
365
|
+
analysedFiles: run.discovery.files.length,
|
|
366
|
+
ignoredPaths: run.discovery.ignoredPaths,
|
|
367
|
+
skipped: run.discovery.skipped,
|
|
368
|
+
missingPaths: run.discovery.missingPaths,
|
|
135
369
|
},
|
|
136
|
-
diagnostics,
|
|
137
|
-
...(notes.length === 0 ? {} : { notes }),
|
|
370
|
+
diagnostics: run.diagnostics,
|
|
371
|
+
...(run.notes.length === 0 ? {} : { notes: run.notes }),
|
|
372
|
+
suppressions: run.suppressions,
|
|
373
|
+
suppressedFindings: run.suppressedFindings,
|
|
138
374
|
findings,
|
|
139
375
|
...(suppressedCount === undefined ? {} : { suppressedCount }),
|
|
140
|
-
|
|
376
|
+
// Score uses evaluated script files. The analysed file count also includes text assets that received raw-text checks.
|
|
377
|
+
score: scoreReport(findings, run.scanned.evaluatedFiles, run.evaluatedPillars),
|
|
141
378
|
...(baselineResult.baseline ? { baseline: baselineResult.baseline } : {}),
|
|
142
379
|
};
|
|
143
380
|
}
|
|
144
381
|
|
|
382
|
+
// The type every port publishes when it cannot load the configuration it was given.
|
|
383
|
+
export const CONFIG_ERROR_DIAGNOSTIC_TYPE = "config-error";
|
|
384
|
+
|
|
385
|
+
// The type every port publishes when it refuses the targets it was given, such as several outside the launch directory.
|
|
386
|
+
export const TARGET_ERROR_DIAGNOSTIC_TYPE = "target-error";
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Identify a multi-target request that violates the launch-directory boundary so the caller can refuse it before reporting.
|
|
390
|
+
* A single external target is allowed; every target in a multi-target request must stay inside the launch directory.
|
|
391
|
+
*
|
|
392
|
+
* @param paths - Scan targets resolved from the launch directory for this boundary check.
|
|
393
|
+
* @returns The first outside target in a multi-target request, or null when no request boundary is violated.
|
|
394
|
+
*/
|
|
395
|
+
export function targetOutsideLaunchDirectory(paths: string[]): string | null {
|
|
396
|
+
// A single target, or none, always has a root the run can report against.
|
|
397
|
+
if (paths.length < 2) {
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
400
|
+
const launchDirectory = cwd();
|
|
401
|
+
// Multi-target requests are refused as soon as any operand lies outside the launch directory.
|
|
402
|
+
return paths.find((path) => !isSameOrDescendant(resolve(launchDirectory, path), launchDirectory)) ?? null;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Build a stable gruff.analysis.v3 report for a run refused before discovery so machine consumers can read the failure.
|
|
407
|
+
*
|
|
408
|
+
* @param projectRoot - project path to record for the refused run
|
|
409
|
+
* @param format - requested output format to record in run metadata
|
|
410
|
+
* @param diagnosticType - category that identifies why the run was refused
|
|
411
|
+
* @param message - explanation to include in the diagnostic
|
|
412
|
+
* @returns A report with one run diagnostic, zero analysed files and no findings.
|
|
413
|
+
*/
|
|
414
|
+
export function failedRunReport(projectRoot: string, format: OutputFormat, diagnosticType: string, message: string): AnalysisReport {
|
|
415
|
+
return {
|
|
416
|
+
schemaVersion: "gruff.analysis.v3",
|
|
417
|
+
tool: { name: "gruff-ts", version: VERSION },
|
|
418
|
+
// Use the analyse default threshold because the caller handles the refusal status separately.
|
|
419
|
+
run: { projectRoot, format, failOn: "advisory", generatedAt: new Date().toISOString() },
|
|
420
|
+
summary: summarize([]),
|
|
421
|
+
paths: { analysedFiles: 0, ignoredPaths: [], skipped: [], missingPaths: [] },
|
|
422
|
+
diagnostics: [{ diagnosticType, message }],
|
|
423
|
+
suppressions: [],
|
|
424
|
+
findings: [],
|
|
425
|
+
score: scoreReport([], 0),
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
|
|
145
429
|
// Subset of discovery output that survives diff filtering. Held as its own type so the diff
|
|
146
430
|
// filter can mutate `files` in place without exposing the whole `SourceDiscoveryResult` shape.
|
|
147
431
|
interface DiscoverySummary {
|
|
@@ -154,11 +438,13 @@ interface DiscoverySummary {
|
|
|
154
438
|
|
|
155
439
|
// Output of the per-file scan pass - both the findings produced and the cached source bodies that
|
|
156
440
|
// later project-level rules need to operate against the deterministic stable shape used by baselines.
|
|
157
|
-
// Contract invariant: `notes` records
|
|
441
|
+
// Contract invariant: `notes` records non-text scan-surface changes without changing finding order.
|
|
158
442
|
interface SourceScanResult {
|
|
159
443
|
findings: Finding[];
|
|
444
|
+
evaluatedFiles: number;
|
|
160
445
|
projectSources: ProjectSource[];
|
|
161
446
|
sources: Map<string, { file: SourceFile; source: string; parsed?: ParsedScript }>;
|
|
447
|
+
declarationSpans: Map<string, DeclarationSpan[]>;
|
|
162
448
|
notes: ScanSurfaceNote[];
|
|
163
449
|
}
|
|
164
450
|
|
|
@@ -171,19 +457,31 @@ interface AnalysisPreparation {
|
|
|
171
457
|
discovery: DiscoverySummary;
|
|
172
458
|
}
|
|
173
459
|
|
|
174
|
-
// Completed scan state before final report rendering.
|
|
175
|
-
// changed-region filtering can project findings without losing baseline
|
|
460
|
+
// Completed scan state before final report rendering. Stable contract: the baseline result is
|
|
461
|
+
// carried separately so changed-region filtering can project findings without losing baseline
|
|
462
|
+
// metadata, and the suppression rows stay whole-scan counts rather than a projection of them.
|
|
176
463
|
interface AnalysisRun {
|
|
177
464
|
projectRoot: string;
|
|
178
465
|
discovery: DiscoverySummary;
|
|
179
466
|
diagnostics: RunDiagnostic[];
|
|
180
467
|
scanned: SourceScanResult;
|
|
468
|
+
evaluatedPillars: Pillar[] | undefined;
|
|
181
469
|
baselineResult: BaselineApplication;
|
|
182
470
|
notes: ScanSurfaceNote[];
|
|
471
|
+
// Configured sensitive-exclusion rows, then built-in test-path and section 13c rows, counted over the full scan
|
|
472
|
+
// so a changed-region projection cannot understate what a suppression actually hid.
|
|
473
|
+
suppressions: SuppressionSummary[];
|
|
474
|
+
// Findings section 13c removed, kept so SARIF can show each as suppressed.
|
|
475
|
+
suppressedFindings: SuppressedFinding[];
|
|
183
476
|
}
|
|
184
477
|
|
|
185
|
-
|
|
186
|
-
|
|
478
|
+
/**
|
|
479
|
+
* Record a run-invalidating diagnostic for every unresolved target path so callers report missing inputs.
|
|
480
|
+
*
|
|
481
|
+
* @param missingPaths - requested target paths that discovery could not resolve
|
|
482
|
+
* @param diagnostics - caller's diagnostic array mutated by appending one missing-path entry per item
|
|
483
|
+
* @returns Nothing. Appends one diagnostic per missing path to diagnostics, forcing exit 2; an empty list adds nothing.
|
|
484
|
+
*/
|
|
187
485
|
function pushMissingPathDiagnostics(missingPaths: string[], diagnostics: RunDiagnostic[]): void {
|
|
188
486
|
for (const missingPath of missingPaths) {
|
|
189
487
|
diagnostics.push({
|
|
@@ -194,16 +492,30 @@ function pushMissingPathDiagnostics(missingPaths: string[], diagnostics: RunDiag
|
|
|
194
492
|
}
|
|
195
493
|
}
|
|
196
494
|
|
|
197
|
-
|
|
198
|
-
*
|
|
199
|
-
*
|
|
200
|
-
*
|
|
495
|
+
/**
|
|
496
|
+
* Read and scan inputs in stable discovery order so that project-index snapshots keep their graph anchors.
|
|
497
|
+
* Record failures caught during a file's read or scan as read-error diagnostics so the remaining files can still be checked.
|
|
498
|
+
* Computes declaration spans per file so parsed syntax trees can be garbage-collected immediately on large repositories.
|
|
499
|
+
*
|
|
500
|
+
* @param files - discovered inputs in a stable order. An empty list leaves the scan with no files to score.
|
|
501
|
+
* @param config - scan budget, rule settings and project-source selection settings
|
|
502
|
+
* @param diagnostics - caller's array for budget, parser and caught file-scan diagnostics
|
|
503
|
+
* @param changedScope - optional changed-region scope naming files that must retain source and parsed ASTs after per-file analysis
|
|
504
|
+
* @returns Findings, retained project snapshots, minimal retained sources, per-file declaration spans, and notes for skipped non-text inputs.
|
|
201
505
|
*/
|
|
202
|
-
function scanDiscoveredSources(
|
|
506
|
+
function scanDiscoveredSources(
|
|
507
|
+
files: SourceFile[],
|
|
508
|
+
config: Config,
|
|
509
|
+
diagnostics: RunDiagnostic[],
|
|
510
|
+
changedScope?: ChangedRegionScope,
|
|
511
|
+
): SourceScanResult {
|
|
203
512
|
const findings: Finding[] = [];
|
|
513
|
+
let evaluatedFiles = 0;
|
|
204
514
|
const projectSources: ProjectSource[] = [];
|
|
205
515
|
const sources = new Map<string, { file: SourceFile; source: string; parsed?: ParsedScript }>();
|
|
516
|
+
const spansByFile = new Map<string, DeclarationSpan[]>();
|
|
206
517
|
const notes: ScanSurfaceNote[] = [];
|
|
518
|
+
// Check each supported input so one unreadable file can be diagnosed without discarding the other files' findings.
|
|
207
519
|
for (const file of files) {
|
|
208
520
|
try {
|
|
209
521
|
const fileBytes = readFileSync(file.absolutePath);
|
|
@@ -217,20 +529,36 @@ function scanDiscoveredSources(files: SourceFile[], config: Config, diagnostics:
|
|
|
217
529
|
continue;
|
|
218
530
|
}
|
|
219
531
|
const source = fileBytes.toString("utf8");
|
|
220
|
-
const
|
|
221
|
-
//
|
|
222
|
-
const parsed =
|
|
223
|
-
|
|
224
|
-
if (
|
|
225
|
-
|
|
532
|
+
const budgetDiagnostic = deepScanBudgetDiagnostic(file, source, config);
|
|
533
|
+
// Over-budget scripts skip parsing and project snapshots but still get enabled text checks. Other scripts share one parse.
|
|
534
|
+
const parsed = budgetDiagnostic ? undefined : parseScript(file, source);
|
|
535
|
+
// The user can still see text findings from a script that exceeds the deep-scan budget.
|
|
536
|
+
if (budgetDiagnostic) {
|
|
537
|
+
diagnostics.push(budgetDiagnostic);
|
|
226
538
|
} else {
|
|
539
|
+
// Retain files that can contribute to cross-file findings such as import cycles.
|
|
227
540
|
if (shouldRetainProjectSource(file, source)) {
|
|
228
|
-
projectSources.push(projectSource(file, source));
|
|
541
|
+
projectSources.push(projectSource(file, source, parsed));
|
|
542
|
+
}
|
|
543
|
+
if (parsed) {
|
|
544
|
+
spansByFile.set(file.displayPath, fileDeclarationSpans(source, parsed));
|
|
229
545
|
}
|
|
230
546
|
diagnostics.push(...(parsed?.diagnostics ?? []));
|
|
231
547
|
}
|
|
232
|
-
|
|
548
|
+
const fileFindings = analyseSource(file, source, config, budgetDiagnostic === undefined, parsed);
|
|
549
|
+
findings.push(...fileFindings);
|
|
550
|
+
// Retain full AST snapshots only for files needed by changed-region symbol expansion, and raw text only when inline suppression applies.
|
|
551
|
+
if (shouldRetainParsedForChangedScope(file.displayPath, changedScope)) {
|
|
552
|
+
sources.set(file.displayPath, { file, source, ...(parsed ? { parsed } : {}) });
|
|
553
|
+
} else if (fileFindings.some((entry) => isInlineSuppressionRelevantRule(entry.ruleId))) {
|
|
554
|
+
sources.set(file.displayPath, { file, source });
|
|
555
|
+
}
|
|
556
|
+
// Text assets can produce findings, but only evaluated scripts contribute to the file count used for scoring.
|
|
557
|
+
if (file.isScript) {
|
|
558
|
+
evaluatedFiles += 1;
|
|
559
|
+
}
|
|
233
560
|
} catch (error) {
|
|
561
|
+
// A file deleted during the scan produces a diagnostic. Findings from other files remain available.
|
|
234
562
|
diagnostics.push({
|
|
235
563
|
diagnosticType: "read-error",
|
|
236
564
|
message: `Unable to read file: ${String(error)}`,
|
|
@@ -239,63 +567,203 @@ function scanDiscoveredSources(files: SourceFile[], config: Config, diagnostics:
|
|
|
239
567
|
});
|
|
240
568
|
}
|
|
241
569
|
}
|
|
242
|
-
return { findings, projectSources, sources, notes };
|
|
570
|
+
return { findings, evaluatedFiles, projectSources, sources, declarationSpans: spansByFile, notes };
|
|
243
571
|
}
|
|
244
572
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
573
|
+
/**
|
|
574
|
+
* Reports whether a file's source and parsed syntax tree must stay cached after per-file analysis for changed-region symbol expansion.
|
|
575
|
+
*
|
|
576
|
+
* @param filePath - project-relative display path of the scanned file
|
|
577
|
+
* @param changedScope - optional changed-region scope active for this run
|
|
578
|
+
* @returns True when `changedScope` uses explicit ranges or lists `filePath` as a changed file; false for full scans and untouched files.
|
|
579
|
+
*/
|
|
580
|
+
function shouldRetainParsedForChangedScope(filePath: string, changedScope: ChangedRegionScope | undefined): boolean {
|
|
581
|
+
if (changedScope === undefined) {
|
|
582
|
+
return false;
|
|
583
|
+
}
|
|
584
|
+
return changedScope.explicitRanges !== undefined || changedScope.changedFiles.has(filePath);
|
|
585
|
+
}
|
|
249
586
|
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
587
|
+
/**
|
|
588
|
+
* Attach baseline identities and subjects before filtering so that SARIF and baseline matching share the same stable fingerprint identity.
|
|
589
|
+
*
|
|
590
|
+
* @param findings - findings to name together before any reporting view narrows the list
|
|
591
|
+
* @param spansByFile - parsed declaration spans used to assign positions and ordinals
|
|
592
|
+
* @returns A new array in input order. Findings with identities gain native identity and subject fields, and unnamed findings stay unchanged.
|
|
593
|
+
*/
|
|
594
|
+
function withBaselineIdentities(findings: Finding[], spansByFile: Map<string, DeclarationSpan[]>): Finding[] {
|
|
595
|
+
const identities = findingIdentities(findings, declarationPositionFromSpans(spansByFile));
|
|
596
|
+
return findings.map((finding, index) => {
|
|
597
|
+
const named = identities[index];
|
|
598
|
+
// Publishing the subject beside the identity is what lets the hook state the ordinal instead of re-deriving it.
|
|
599
|
+
return named === undefined ? finding : { ...finding, baselineIdentity: named.identity, baselineSubject: named.subject };
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* Collects declaration spans for one parsed script so a baseline can distinguish same-named functions in one file
|
|
605
|
+
* without keeping the full TypeScript AST alive across the entire repository scan.
|
|
606
|
+
*
|
|
607
|
+
* @param source - raw UTF-8 source text of the script
|
|
608
|
+
* @param parsed - shared parsed syntax tree for the script
|
|
609
|
+
* @returns Declaration spans covering named functions, methods, callable bindings, and measured-only inline callables.
|
|
610
|
+
*/
|
|
611
|
+
function fileDeclarationSpans(source: string, parsed: ParsedScript): DeclarationSpan[] {
|
|
612
|
+
const blocks = functionBlocks(source, source, parsed);
|
|
613
|
+
// Keep positions for measured inline functions too, so two functions named `<iife>` can have separate baseline entries.
|
|
614
|
+
const measuredOnly = measuredOnlyFunctionBlocks(source, maskNonCode(source), parsed);
|
|
615
|
+
return keepColumnsOnSharedLines([...blocks, ...measuredOnly].map((block) => blockDeclarationSpan(block, parsed)));
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* Drops column bounds from every span that shares no line with a same-named span, so ordinary declarations keep line-only baseline positions.
|
|
620
|
+
* Only two functions with one name on one line, such as `[{ run: () => 1 }, { run: () => 2 }]`, need columns to keep separate entries.
|
|
621
|
+
*
|
|
622
|
+
* @param spans - every declaration span found in one file, possibly carrying start and end columns
|
|
623
|
+
* @returns The same spans in order; columns survive only where a same-named span starts or ends on a shared line
|
|
624
|
+
*/
|
|
625
|
+
function keepColumnsOnSharedLines(spans: DeclarationSpan[]): DeclarationSpan[] {
|
|
626
|
+
const spansByName = new Map<string, DeclarationSpan[]>();
|
|
627
|
+
for (const span of spans) {
|
|
628
|
+
spansByName.set(span.name, [...(spansByName.get(span.name) ?? []), span]);
|
|
629
|
+
}
|
|
630
|
+
return spans.map((span) => {
|
|
631
|
+
const spanLines = [span.startLine, span.endLine];
|
|
632
|
+
const sharesLine = (spansByName.get(span.name) ?? []).some((other) => other !== span
|
|
633
|
+
&& (spanLines.includes(other.startLine) || spanLines.includes(other.endLine)));
|
|
634
|
+
// Two same-named declarations sharing a line keep their columns so each gets its own baseline entry.
|
|
635
|
+
if (sharesLine) {
|
|
636
|
+
return span;
|
|
637
|
+
}
|
|
638
|
+
// A declaration alone on its lines is told apart by line alone, so dropping columns keeps existing baseline entries stable.
|
|
639
|
+
const { startColumn: _startColumn, endColumn: _endColumn, ...lineOnly } = span;
|
|
640
|
+
return lineOnly;
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* Builds the baseline span for one function, adding 1-based start and end columns when the syntax tree has them.
|
|
646
|
+
* Columns keep two same-named functions on one line apart, so each keeps its own baseline entry.
|
|
647
|
+
*
|
|
648
|
+
* @param block - discovered function or callable block; when `callableNode` is absent, only line bounds are returned
|
|
649
|
+
* @param parsed - shared parsed syntax tree owning the block's AST offsets
|
|
650
|
+
* @returns Declaration span with line bounds, plus 1-based start/end columns when `callableNode` is present.
|
|
651
|
+
*/
|
|
652
|
+
function blockDeclarationSpan(block: FunctionBlock, parsed: ParsedScript): DeclarationSpan {
|
|
653
|
+
const endLine = block.startLine + block.lineCount - 1;
|
|
654
|
+
const span: DeclarationSpan = { name: block.name, startLine: block.startLine, endLine };
|
|
655
|
+
// A block found without a syntax node keeps line-only bounds, so its baseline entry is ranked by line alone.
|
|
656
|
+
if (block.callableNode === undefined) {
|
|
657
|
+
return span;
|
|
658
|
+
}
|
|
659
|
+
const anchorNode = declarationAnchorNode(block.callableNode);
|
|
660
|
+
const startPos = parsed.sourceFile.getLineAndCharacterOfPosition(anchorNode.getStart(parsed.sourceFile));
|
|
661
|
+
const endPos = parsed.sourceFile.getLineAndCharacterOfPosition(block.callableNode.getEnd());
|
|
662
|
+
// Preserve column precision when the declaration starts on the span's own opening line; leading JSDoc/decorators begin at column 1.
|
|
663
|
+
span.startColumn = startPos.line + 1 === block.startLine ? startPos.character + 1 : 1;
|
|
664
|
+
// Record the end column only when the syntax node ends on the block's last line, so a mismatch never narrows the span.
|
|
665
|
+
if (endPos.line + 1 === endLine) {
|
|
666
|
+
// The syntax node's end is just past its last character, so that offset is already the last character's 1-based column.
|
|
667
|
+
span.endColumn = endPos.character;
|
|
668
|
+
}
|
|
669
|
+
return span;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* Widens an arrow or function expression to the variable or property it is assigned to.
|
|
674
|
+
* Findings reported on that name then still fall inside the function's span.
|
|
675
|
+
*
|
|
676
|
+
* @param callableNode - parsed AST node for the callable body
|
|
677
|
+
* @returns The owning variable/property declaration node when it directly wraps `callableNode`, otherwise `callableNode`.
|
|
678
|
+
*/
|
|
679
|
+
function declarationAnchorNode(callableNode: import("typescript").Node): import("typescript").Node {
|
|
680
|
+
const parent = callableNode.parent;
|
|
681
|
+
// A function assigned to a variable or property starts at its name, which is where findings about it are reported.
|
|
682
|
+
if (parent !== undefined && "initializer" in parent && parent.initializer === callableNode) {
|
|
683
|
+
return parent;
|
|
684
|
+
}
|
|
685
|
+
return callableNode;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/**
|
|
689
|
+
* Check whether a script exceeds the configured line or byte limits for deep syntax analysis.
|
|
690
|
+
*
|
|
691
|
+
* @param file - candidate input whose script classification and display path guide budget enforcement
|
|
692
|
+
* @param source - UTF-8 source text measured for line count and byte length
|
|
693
|
+
* @param config - scan configuration supplying deepScanBudget thresholds and enabled state
|
|
694
|
+
* @returns A non-fatal diagnostic requesting skipped deep checks, or undefined for non-scripts,
|
|
695
|
+
* a disabled budget, or sources within both limits.
|
|
696
|
+
*/
|
|
697
|
+
function deepScanBudgetDiagnostic(file: SourceFile, source: string, config: Config): RunDiagnostic | undefined {
|
|
698
|
+
const budget = config.deepScanBudget;
|
|
699
|
+
if (!file.isScript || !budget.enabled) {
|
|
254
700
|
return undefined;
|
|
255
701
|
}
|
|
256
702
|
const lines = lineCount(source);
|
|
257
703
|
const bytes = Buffer.byteLength(source, "utf8");
|
|
258
|
-
if (lines <=
|
|
704
|
+
if (lines <= budget.maxLines && bytes <= budget.maxBytes) {
|
|
259
705
|
return undefined;
|
|
260
706
|
}
|
|
261
707
|
return {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
708
|
+
diagnosticType: "bounded-deep-scan",
|
|
709
|
+
filePath: file.displayPath,
|
|
710
|
+
line: 1,
|
|
711
|
+
invalidatesRun: false,
|
|
712
|
+
message: `path=${file.displayPath}; lines=${lines}; bytes=${bytes}; maxLines=${budget.maxLines}; maxBytes=${budget.maxBytes}; override=${budget.override}. Text-level rules (size, sensitive-data, config) still ran; masking, block parsing, AST walking, and other deep script analysis were skipped.`,
|
|
265
713
|
};
|
|
266
714
|
}
|
|
267
715
|
|
|
268
|
-
|
|
269
|
-
|
|
716
|
+
/**
|
|
717
|
+
* Decide whether a scanned file belongs in the project index for exported-surface, test-coverage, and graph rules.
|
|
718
|
+
*
|
|
719
|
+
* @param file - discovered file providing script classification and display path
|
|
720
|
+
* @param source - file text inspected for potential import or export syntax candidates
|
|
721
|
+
* @returns True for script files that are production code, tests, or import/export candidates; false for non-scripts or unrelated scripts.
|
|
722
|
+
*/
|
|
270
723
|
function shouldRetainProjectSource(file: SourceFile, source: string): boolean {
|
|
271
724
|
return file.isScript && (isProductionSourcePath(file.displayPath) || isTestPath(file.displayPath) || hasImportSyntaxCandidate(source));
|
|
272
725
|
}
|
|
273
726
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
727
|
+
/**
|
|
728
|
+
* Build compact project-index data for a retained script, pre-extracting import statements from template-masked lines
|
|
729
|
+
* so template fixture text cannot become graph edges and large scans do not retain full file line arrays.
|
|
730
|
+
*
|
|
731
|
+
* @param file - retained source file metadata
|
|
732
|
+
* @param source - raw UTF-8 source text scanned for import statements and code lines
|
|
733
|
+
* @param parsed - optional script parse used to exclude decorator text from the code-line count; without it, decorator-only lines count
|
|
734
|
+
* @returns Compact ProjectSource carrying pre-extracted import statements and substantive code-line count.
|
|
735
|
+
*/
|
|
736
|
+
function projectSource(file: SourceFile, source: string, parsed?: ParsedScript): ProjectSource {
|
|
737
|
+
const statements = hasImportSyntaxCandidate(source) ? extractImportStatements(maskTemplateLiteralBodies(source).split(/\r?\n/)) : [];
|
|
738
|
+
return { file, importStatements: statements, codeLineCount: codeLineFlags(source, parsed).filter(Boolean).length };
|
|
280
739
|
}
|
|
281
740
|
|
|
282
|
-
|
|
283
|
-
|
|
741
|
+
/**
|
|
742
|
+
* Cheap prefilter for files that might contain real import/export edges or fixture strings that mention them.
|
|
743
|
+
* False positives are acceptable; false negatives would drop graph edges.
|
|
744
|
+
*
|
|
745
|
+
* @param source - raw source text checked for import or from substrings
|
|
746
|
+
* @returns True when source contains `import` or `from`; false otherwise.
|
|
747
|
+
*/
|
|
284
748
|
function hasImportSyntaxCandidate(source: string): boolean {
|
|
285
749
|
return source.includes("import") || source.includes("from");
|
|
286
750
|
}
|
|
287
751
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
752
|
+
/**
|
|
753
|
+
* Run the text pass first and preserve stable rule order. Generated sources skip documentation and naming findings to avoid noise.
|
|
754
|
+
*
|
|
755
|
+
* @param file - input path and script classification used by the rule passes
|
|
756
|
+
* @param source - original file text to check and inspect for generated markers
|
|
757
|
+
* @param config - selects rules and supplies their settings
|
|
758
|
+
* @param isWithinDeepScanBudget - allows deeper rules for scripts small enough to scan
|
|
759
|
+
* @param parsed - shared script parse when available for syntax-backed checks
|
|
760
|
+
* @returns Enabled findings in emission order. Generated input retains eligible safety findings under the same filtering contract.
|
|
761
|
+
*/
|
|
294
762
|
function analyseSource(file: SourceFile, source: string, config: Config, isWithinDeepScanBudget: boolean, parsed?: ParsedScript): Finding[] {
|
|
295
763
|
const findings: Finding[] = [];
|
|
296
764
|
// Size and documentation rules share one comment scan so code-only line counts do not add a second pass.
|
|
297
|
-
const comments = (ruleEnabled(config, "size.file-length")
|
|
298
|
-
analyseTextRules(file, source, comments, config, findings);
|
|
765
|
+
const comments = file.isScript && (ruleEnabled(config, "size.file-length") || isAnyRuleEnabled(config, COMMENT_QUALITY_RULE_IDS)) ? commentRecords(source) : [];
|
|
766
|
+
analyseTextRules(file, source, comments, config, findings, parsed);
|
|
299
767
|
if (file.isScript && isWithinDeepScanBudget) {
|
|
300
768
|
analyseTypeScriptRules(file, source, comments, config, findings, parsed);
|
|
301
769
|
}
|
|
@@ -308,18 +776,28 @@ function analyseSource(file: SourceFile, source: string, config: Config, isWithi
|
|
|
308
776
|
// test-quality...) still applies - a generated file can leak a real credential.
|
|
309
777
|
const GENERATED_SKIPPED_PILLARS = new Set<Pillar>(["documentation", "naming"]);
|
|
310
778
|
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
779
|
+
/**
|
|
780
|
+
* Marker-based generated or copied classification over the file's opening lines. Deliberately requires an
|
|
781
|
+
* explicit marker rather than path hints so a `fixtures/` path alone must never change rule behaviour,
|
|
782
|
+
* and `classifyIgnore` in discovery.ts stays the only directory-level exclusion surface.
|
|
783
|
+
*
|
|
784
|
+
* @param source - file text whose first 10 lines are tested for generated or copied markers
|
|
785
|
+
* @returns True when any opening line matches a generated or copied header marker; false otherwise.
|
|
786
|
+
*/
|
|
314
787
|
function isGeneratedSource(source: string): boolean {
|
|
315
788
|
return source.split(/\r?\n/, 10).some((line) => /AUTO-?GENERATED|@generated\b|GENERATED FILE|Code generated|Generated by|DO NOT EDIT|Copied from/i.test(line));
|
|
316
789
|
}
|
|
317
790
|
|
|
318
|
-
|
|
319
|
-
*
|
|
320
|
-
*
|
|
321
|
-
*
|
|
322
|
-
*
|
|
791
|
+
/**
|
|
792
|
+
* Run cross-file checks after per-file analysis. Root graph context keeps cycles through requested files visible while preserving report scope.
|
|
793
|
+
* Unreadable files encountered while gathering root graph context are skipped so a scoped scan can continue.
|
|
794
|
+
*
|
|
795
|
+
* @param projectRoot - root for deciding and discovering circular-import context
|
|
796
|
+
* @param options - requested scope and discovery settings for root context
|
|
797
|
+
* @param scopedFiles - discovered files whose paths define which root cycles to keep
|
|
798
|
+
* @param projectSources - scanned source snapshots for the scoped project index
|
|
799
|
+
* @param config - enables cross-file rules and supplies their settings
|
|
800
|
+
* @returns Cross-file findings under the scoped reporting contract, or an empty list if no pass runs or produces a finding.
|
|
323
801
|
*/
|
|
324
802
|
function analyseProjectIndex(projectRoot: string, options: AnalysisOptions, scopedFiles: SourceFile[], projectSources: ProjectSource[], config: Config): Finding[] {
|
|
325
803
|
const shouldUseRootCircularContext = ruleEnabled(config, CIRCULAR_IMPORT_RULE_ID) && shouldBuildRootCircularContext(projectRoot, options, scopedFiles);
|
|
@@ -339,16 +817,21 @@ function analyseProjectIndex(projectRoot: string, options: AnalysisOptions, scop
|
|
|
339
817
|
}
|
|
340
818
|
|
|
341
819
|
const PROJECT_INDEX_RULE_IDS = [
|
|
342
|
-
"design.deep-relative-import",
|
|
343
820
|
CIRCULAR_IMPORT_RULE_ID,
|
|
344
821
|
"design.large-module-concentration",
|
|
345
822
|
] as const;
|
|
346
823
|
const SCOPED_PROJECT_INDEX_RULE_IDS = [
|
|
347
|
-
"design.deep-relative-import",
|
|
348
824
|
"design.large-module-concentration",
|
|
349
825
|
] as const;
|
|
350
826
|
|
|
351
|
-
|
|
827
|
+
/**
|
|
828
|
+
* Determine whether a scoped scan needs extra graph context rooted at projectRoot to find cycles through scopedFiles.
|
|
829
|
+
*
|
|
830
|
+
* @param projectRoot - project root directory used to resolve requested target paths
|
|
831
|
+
* @param options - scan options whose explicit path operands determine if the scan is already root-wide
|
|
832
|
+
* @param scopedFiles - files discovered for the requested targets
|
|
833
|
+
* @returns True when scopedFiles and explicit paths are non-empty and none resolve to projectRoot; false otherwise.
|
|
834
|
+
*/
|
|
352
835
|
function shouldBuildRootCircularContext(projectRoot: string, options: AnalysisOptions, scopedFiles: SourceFile[]): boolean {
|
|
353
836
|
if (scopedFiles.length === 0 || options.paths.length === 0) {
|
|
354
837
|
return false;
|
|
@@ -356,33 +839,55 @@ function shouldBuildRootCircularContext(projectRoot: string, options: AnalysisOp
|
|
|
356
839
|
return options.paths.every((input) => displayPath(projectRoot, absolutize(projectRoot, input)) !== ".");
|
|
357
840
|
}
|
|
358
841
|
|
|
359
|
-
|
|
842
|
+
/**
|
|
843
|
+
* Read root graph context so that a scoped scan can detect a cycle passing through files outside the request.
|
|
844
|
+
*
|
|
845
|
+
* @param projectRoot - root directory for graph discovery
|
|
846
|
+
* @param options - discovery settings to keep while clearing the requested path operands
|
|
847
|
+
* @param scopedFiles - requested files whose display paths qualify a cycle for the report
|
|
848
|
+
* @param config - discovery and project-source settings for the root scan
|
|
849
|
+
* @returns Stable circular-import findings touching a requested file, or an empty list if no cycle qualifies.
|
|
850
|
+
*/
|
|
360
851
|
function rootCircularImportFindings(projectRoot: string, options: AnalysisOptions, scopedFiles: SourceFile[], config: Config): Finding[] {
|
|
361
852
|
const requestedFiles = new Set(scopedFiles.map((file) => file.displayPath));
|
|
362
853
|
const rootDiscovery = discoverSources(projectRoot, { ...options, paths: [] }, config);
|
|
363
|
-
const rootProjectSources = graphProjectSources(rootDiscovery.files);
|
|
854
|
+
const rootProjectSources = graphProjectSources(rootDiscovery.files, config);
|
|
364
855
|
const findings: Finding[] = [];
|
|
365
856
|
analyseCircularImportRule(buildProjectIndex(rootProjectSources), findings);
|
|
366
857
|
return findings.filter((finding) => circularImportFindingTouchesRequestedFile(finding, requestedFiles));
|
|
367
858
|
}
|
|
368
859
|
|
|
369
|
-
|
|
370
|
-
|
|
860
|
+
/**
|
|
861
|
+
* Read root-context candidates from files and collect retained script snapshots that satisfy the deep-scan budget.
|
|
862
|
+
* Unreadable or unprocessable candidates are skipped; the primary scoped scan owns requested-file diagnostics.
|
|
863
|
+
*
|
|
864
|
+
* @param files - discovered root-level source candidates to read from disk
|
|
865
|
+
* @param config - scan configuration supplying deep-scan budget limits
|
|
866
|
+
* @returns Retained project-index snapshots for readable, within-budget scripts.
|
|
867
|
+
*/
|
|
868
|
+
function graphProjectSources(files: SourceFile[], config: Config): ProjectSource[] {
|
|
371
869
|
const projectSources: ProjectSource[] = [];
|
|
372
870
|
for (const file of files) {
|
|
373
871
|
try {
|
|
374
872
|
const source = readFileSync(file.absolutePath, "utf8");
|
|
375
|
-
if (!
|
|
873
|
+
if (!deepScanBudgetDiagnostic(file, source, config) && shouldRetainProjectSource(file, source)) {
|
|
376
874
|
projectSources.push(projectSource(file, source));
|
|
377
875
|
}
|
|
378
876
|
} catch {
|
|
379
|
-
//
|
|
877
|
+
// Root context is supplemental; the primary scan reports requested-file failures, so this pass adds no duplicate diagnostic.
|
|
380
878
|
}
|
|
381
879
|
}
|
|
382
880
|
return projectSources;
|
|
383
881
|
}
|
|
384
882
|
|
|
385
|
-
|
|
883
|
+
/**
|
|
884
|
+
* Check whether a circular-import finding lists a requested display path among its cycle members.
|
|
885
|
+
* The scope contract falls back to the finding's path for a missing or non-array list; empty arrays and non-string members never match.
|
|
886
|
+
*
|
|
887
|
+
* @param finding - circular-import finding whose `metadata.files` or `filePath` is inspected
|
|
888
|
+
* @param requestedFiles - set of display paths belonging to the scoped request
|
|
889
|
+
* @returns True when at least one cycle member path is in requestedFiles; false otherwise.
|
|
890
|
+
*/
|
|
386
891
|
function circularImportFindingTouchesRequestedFile(finding: Finding, requestedFiles: Set<string>): boolean {
|
|
387
892
|
const files = Array.isArray(finding.metadata.files) ? finding.metadata.files : [finding.filePath];
|
|
388
893
|
return files.some((file) => typeof file === "string" && requestedFiles.has(file));
|
|
@@ -400,19 +905,7 @@ const SENSITIVE_DATA_RULE_IDS = ruleIdsForPillar("sensitive-data");
|
|
|
400
905
|
const SIZE_RULE_IDS = ruleIdsForPillar("size");
|
|
401
906
|
const TEST_QUALITY_RULE_IDS = ruleIdsForPillar("test-quality");
|
|
402
907
|
|
|
403
|
-
/*
|
|
404
|
-
* Sensitive-data rules that infer a secret from shape rather than value, so generated
|
|
405
|
-
* dependency metadata defeats them: every integrity digest looks high-entropy, and a package
|
|
406
|
-
* named `gtoken` turns `gtoken: 8.0.0(supports-color@11.0.0)` into a credential assignment.
|
|
407
|
-
* Suppressed for lockfiles only. Every value-shaped detector still runs there.
|
|
408
|
-
*/
|
|
409
|
-
const LOCKFILE_SUPPRESSED_SENSITIVE_RULE_IDS = new Set([
|
|
410
|
-
"sensitive-data.high-entropy-string",
|
|
411
|
-
"sensitive-data.hardcoded-env-value",
|
|
412
|
-
]);
|
|
413
|
-
|
|
414
908
|
const GITHUB_ACTIONS_RULE_IDS = [
|
|
415
|
-
"security.github-actions-broad-permissions",
|
|
416
909
|
"security.github-actions-pull-request-target",
|
|
417
910
|
"security.github-actions-remote-shell",
|
|
418
911
|
"security.github-actions-secrets-in-pr",
|
|
@@ -421,32 +914,28 @@ const GITHUB_ACTIONS_RULE_IDS = [
|
|
|
421
914
|
|
|
422
915
|
const PROJECT_CONFIG_RULE_IDS = [
|
|
423
916
|
"security.remote-install-script",
|
|
424
|
-
"security.risky-lifecycle-script",
|
|
425
917
|
"security.url-dependency",
|
|
426
918
|
"waste.broad-runtime-version",
|
|
427
919
|
"design.package-bin-missing",
|
|
428
920
|
"design.package-bin-not-executable",
|
|
429
921
|
] as const;
|
|
430
922
|
|
|
431
|
-
|
|
923
|
+
// The size and complexity block rules, the only rules that also run on the measure-only callable forms.
|
|
924
|
+
const BLOCK_MEASURE_RULE_IDS = [
|
|
432
925
|
"size.function-length",
|
|
433
926
|
"size.parameter-count",
|
|
434
927
|
"complexity.cyclomatic",
|
|
435
|
-
|
|
436
|
-
|
|
928
|
+
] as const;
|
|
929
|
+
|
|
930
|
+
const BLOCK_RULE_IDS = [
|
|
931
|
+
...BLOCK_MEASURE_RULE_IDS,
|
|
437
932
|
"docs.missing-exported-function-doc",
|
|
438
933
|
"docs.missing-internal-function-doc",
|
|
439
|
-
"waste.empty-function",
|
|
440
|
-
"waste.unused-parameter",
|
|
441
|
-
"waste.redundant-variable",
|
|
442
934
|
"waste.useless-return",
|
|
443
935
|
] as const;
|
|
444
936
|
|
|
445
937
|
const PARAMETER_NAMING_RULE_IDS = [
|
|
446
|
-
"naming.boolean-prefix",
|
|
447
|
-
"naming.generic-parameter",
|
|
448
938
|
"naming.identifier-quality",
|
|
449
|
-
"naming.negative-boolean",
|
|
450
939
|
"naming.short-variable",
|
|
451
940
|
] as const;
|
|
452
941
|
|
|
@@ -454,41 +943,26 @@ const DOCBLOCK_RULE_IDS = [
|
|
|
454
943
|
"docs.missing-param-tag",
|
|
455
944
|
"docs.missing-return-tag",
|
|
456
945
|
"docs.stale-param-tag",
|
|
457
|
-
"docs.useless-docblock",
|
|
458
|
-
] as const;
|
|
459
|
-
|
|
460
|
-
const INTERFACE_FIELD_RULE_IDS = [
|
|
461
|
-
"naming.boolean-prefix",
|
|
462
|
-
"naming.negative-boolean",
|
|
463
946
|
] as const;
|
|
464
947
|
|
|
465
948
|
// Every rule id `analyseCommentQualityRules` can emit - including `docs.fixture-purpose-missing`
|
|
466
949
|
// via `pushFixturePurposeFindings` - so the group gate never silences an enabled rule.
|
|
467
950
|
const COMMENT_QUALITY_RULE_IDS = [
|
|
468
951
|
"docs.fixture-purpose-missing",
|
|
469
|
-
"docs.magic-threshold-without-rationale",
|
|
470
952
|
"docs.missing-error-behavior-doc",
|
|
471
953
|
"docs.missing-invariant-doc",
|
|
472
954
|
"docs.missing-side-effect-doc",
|
|
473
955
|
"docs.missing-why-for-complex-code",
|
|
474
|
-
"docs.stale-comment",
|
|
475
956
|
"docs.suppression-without-rationale",
|
|
476
957
|
"docs.todo-without-tracking",
|
|
477
|
-
"docs.useless-docblock",
|
|
478
958
|
] as const;
|
|
479
959
|
|
|
480
960
|
const CLASS_RULE_IDS = [
|
|
481
961
|
"docs.missing-public-doc",
|
|
482
962
|
"naming.class-file-mismatch",
|
|
483
|
-
"modernisation.public-property",
|
|
484
963
|
"modernisation.readonly-property-candidate",
|
|
485
964
|
] as const;
|
|
486
965
|
|
|
487
|
-
const IDENTIFIER_INVENTORY_RULE_IDS = [
|
|
488
|
-
"naming.acronym-case",
|
|
489
|
-
"naming.inconsistent-casing",
|
|
490
|
-
] as const;
|
|
491
|
-
|
|
492
966
|
const SECURITY_FLOW_RULE_IDS = [
|
|
493
967
|
"security.dynamic-regexp",
|
|
494
968
|
"security.open-redirect-candidate",
|
|
@@ -510,7 +984,6 @@ const BLOCK_DEPENDENT_RULE_IDS = [
|
|
|
510
984
|
...PARAMETER_NAMING_RULE_IDS,
|
|
511
985
|
...TEST_QUALITY_RULE_IDS,
|
|
512
986
|
...COMMENT_QUALITY_RULE_IDS,
|
|
513
|
-
...IDENTIFIER_INVENTORY_RULE_IDS,
|
|
514
987
|
];
|
|
515
988
|
|
|
516
989
|
const TYPESCRIPT_RULE_IDS = [
|
|
@@ -525,7 +998,11 @@ const TYPESCRIPT_RULE_IDS = [
|
|
|
525
998
|
...TEST_QUALITY_RULE_IDS,
|
|
526
999
|
];
|
|
527
1000
|
|
|
528
|
-
|
|
1001
|
+
/**
|
|
1002
|
+
* Group rule ids from the public catalogue once so broad pass gates stay aligned with profiles.
|
|
1003
|
+
*
|
|
1004
|
+
* @returns Read-only map from each pillar to its catalogue rule ids.
|
|
1005
|
+
*/
|
|
529
1006
|
function ruleIdsByPillar(): ReadonlyMap<Pillar, readonly string[]> {
|
|
530
1007
|
const byPillar = new Map<Pillar, string[]>();
|
|
531
1008
|
for (const descriptor of ruleDescriptors()) {
|
|
@@ -536,55 +1013,64 @@ function ruleIdsByPillar(): ReadonlyMap<Pillar, readonly string[]> {
|
|
|
536
1013
|
return byPillar;
|
|
537
1014
|
}
|
|
538
1015
|
|
|
539
|
-
|
|
1016
|
+
/**
|
|
1017
|
+
* Look up a precomputed pillar group from the catalogue index; missing groups are empty so callers stay branch-free.
|
|
1018
|
+
*
|
|
1019
|
+
* @param pillar - quality pillar whose registered rule ids are requested
|
|
1020
|
+
* @returns Array of rule ids for pillar, or an empty array when the pillar has none.
|
|
1021
|
+
*/
|
|
540
1022
|
function ruleIdsForPillar(pillar: Pillar): readonly string[] {
|
|
541
1023
|
return RULE_IDS_BY_PILLAR.get(pillar) ?? [];
|
|
542
1024
|
}
|
|
543
1025
|
|
|
544
|
-
|
|
1026
|
+
/**
|
|
1027
|
+
* Check whether at least one rule in a group is active under the resolved configuration.
|
|
1028
|
+
*
|
|
1029
|
+
* @param config - scan configuration including profile defaults and explicit rule overrides
|
|
1030
|
+
* @param ruleIds - candidate rule identifiers to test
|
|
1031
|
+
* @returns True when any id in ruleIds is enabled by config; false when none are enabled or ruleIds is empty.
|
|
1032
|
+
*/
|
|
545
1033
|
function isAnyRuleEnabled(config: Config, ruleIds: readonly string[]): boolean {
|
|
546
1034
|
return ruleIds.some((ruleId) => ruleEnabled(config, ruleId));
|
|
547
1035
|
}
|
|
548
1036
|
|
|
549
|
-
|
|
550
|
-
*
|
|
551
|
-
*
|
|
552
|
-
*
|
|
1037
|
+
/**
|
|
1038
|
+
* Check source text before deeper script passes so that text inputs are covered too. Keep the rule order stable for tied findings.
|
|
1039
|
+
*
|
|
1040
|
+
* @param file - input path for findings and script classification for the size check
|
|
1041
|
+
* @param source - raw text to measure or check for sensitive data, workflow and configuration issues
|
|
1042
|
+
* @param comments - comment records used to count substantive script lines
|
|
1043
|
+
* @param config - enables checks and supplies the size threshold and severity
|
|
1044
|
+
* @param findings - caller's array to append results to
|
|
1045
|
+
* @param parsed - shared script parse used to exclude decorator text. Without it, decorator-only lines count.
|
|
1046
|
+
* @returns Nothing. Appends size findings when enabled and text findings from each group with at least one enabled rule.
|
|
553
1047
|
*/
|
|
554
|
-
function analyseTextRules(file: SourceFile, source: string, comments: CommentRecord[], config: Config, findings: Finding[]): void {
|
|
555
|
-
|
|
556
|
-
|
|
1048
|
+
function analyseTextRules(file: SourceFile, source: string, comments: CommentRecord[], config: Config, findings: Finding[], parsed?: ParsedScript): void {
|
|
1049
|
+
// The file-length threshold applies to scripts because it measures code size. Other inputs still receive enabled text checks.
|
|
1050
|
+
// The size bands follow FAMILY-CONTRACT.md section 12 under Size and complexity findings in two bands.
|
|
1051
|
+
if (file.isScript && ruleEnabled(config, "size.file-length")) {
|
|
1052
|
+
const lines = substantiveLineCount(source, comments, parsed);
|
|
557
1053
|
const fileLengthThreshold = threshold(config, "size.file-length", 1000);
|
|
558
1054
|
if (lines > fileLengthThreshold) {
|
|
1055
|
+
const band = bandedFields(lines, fileLengthThreshold, ruleSeverity(config, "size.file-length", "error"), LOWER_BAND_FILE, SPLIT_FILE);
|
|
559
1056
|
findings.push(
|
|
560
1057
|
makeFinding({
|
|
561
1058
|
ruleId: "size.file-length",
|
|
562
1059
|
message: `File has ${lines} substantive lines, above the threshold of ${fileLengthThreshold}.`,
|
|
563
1060
|
filePath: file.displayPath,
|
|
564
1061
|
line: 1,
|
|
565
|
-
severity:
|
|
1062
|
+
severity: band.severity,
|
|
566
1063
|
pillar: "size",
|
|
567
1064
|
confidence: "high",
|
|
568
|
-
remediation:
|
|
569
|
-
metadata: { lines, threshold: fileLengthThreshold },
|
|
1065
|
+
remediation: band.remediation,
|
|
1066
|
+
metadata: { lines, threshold: fileLengthThreshold, limitBand: band.limitBand },
|
|
570
1067
|
}),
|
|
571
1068
|
);
|
|
572
1069
|
}
|
|
573
1070
|
}
|
|
574
1071
|
|
|
575
1072
|
if (isAnyRuleEnabled(config, SENSITIVE_DATA_RULE_IDS)) {
|
|
576
|
-
|
|
577
|
-
analyseSensitiveData(file, source, config, sensitiveFindings);
|
|
578
|
-
// Generated dependency metadata defeats the two shape-based detectors: integrity digests
|
|
579
|
-
// look high-entropy, and a package whose name contains `token`/`key`/`secret` makes its
|
|
580
|
-
// version spec look like a credential assignment. The value-shaped detectors still run,
|
|
581
|
-
// because a credential in a `resolved` URL is the real leak vector for this file family.
|
|
582
|
-
const isLockfile = isGeneratedLockfile(file.displayPath);
|
|
583
|
-
for (const sensitiveFinding of sensitiveFindings) {
|
|
584
|
-
if (!isLockfile || !LOCKFILE_SUPPRESSED_SENSITIVE_RULE_IDS.has(sensitiveFinding.ruleId)) {
|
|
585
|
-
findings.push(sensitiveFinding);
|
|
586
|
-
}
|
|
587
|
-
}
|
|
1073
|
+
analyseSensitiveData(file, source, findings);
|
|
588
1074
|
}
|
|
589
1075
|
if (isAnyRuleEnabled(config, GITHUB_ACTIONS_RULE_IDS)) {
|
|
590
1076
|
analyseGithubActionsRules(file, source, findings);
|
|
@@ -594,25 +1080,33 @@ function analyseTextRules(file: SourceFile, source: string, comments: CommentRec
|
|
|
594
1080
|
}
|
|
595
1081
|
}
|
|
596
1082
|
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
1083
|
+
/**
|
|
1084
|
+
* Count nonblank lines after masking recorded comments and, when available, decorators, while skipping `#!` lines.
|
|
1085
|
+
* String text otherwise counts.
|
|
1086
|
+
*
|
|
1087
|
+
* @param source - raw script text to measure
|
|
1088
|
+
* @param comments - recorded comment spans replaced with spaces before counting
|
|
1089
|
+
* @param parsed - optional script parse enabling decorator masking; without it, decorator-only lines count
|
|
1090
|
+
* @returns Count of substantive lines, or 0 for empty source.
|
|
1091
|
+
*/
|
|
1092
|
+
function substantiveLineCount(source: string, comments: CommentRecord[], parsed?: ParsedScript): number {
|
|
1093
|
+
const withoutComments = maskRecordedComments(source, comments);
|
|
1094
|
+
// Mask only the decorator spans so code sharing a line with a decorator still counts.
|
|
1095
|
+
// See FAMILY-CONTRACT.md section 12 under Code lines in every line count.
|
|
1096
|
+
const withoutDecorators = parsed ? maskDecorators(withoutComments, parsed) : withoutComments;
|
|
1097
|
+
return withoutDecorators
|
|
603
1098
|
.split(/\r?\n/)
|
|
604
|
-
.filter((line) => isSubstantiveLine(
|
|
1099
|
+
.filter((line) => isSubstantiveLine(line))
|
|
605
1100
|
.length;
|
|
606
1101
|
}
|
|
607
1102
|
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
// Replaces comment text with spaces while retaining newlines and UTF-16 offsets from CommentRecord.
|
|
1103
|
+
/**
|
|
1104
|
+
* Replace comment text with spaces while retaining newlines and UTF-16 offsets from CommentRecord.
|
|
1105
|
+
*
|
|
1106
|
+
* @param source - original script text
|
|
1107
|
+
* @param comments - ordered comment spans whose non-newline characters are masked
|
|
1108
|
+
* @returns Source text with recorded comments blanked out and line structure preserved.
|
|
1109
|
+
*/
|
|
616
1110
|
function maskRecordedComments(source: string, comments: CommentRecord[]): string {
|
|
617
1111
|
let cursor = 0;
|
|
618
1112
|
let masked = "";
|
|
@@ -625,29 +1119,24 @@ function maskRecordedComments(source: string, comments: CommentRecord[]): string
|
|
|
625
1119
|
return masked + source.slice(cursor);
|
|
626
1120
|
}
|
|
627
1121
|
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
function isSubstantiveLine(
|
|
1122
|
+
/**
|
|
1123
|
+
* Test whether a line contributes to substantive code length.
|
|
1124
|
+
* A blank line and a `#!` interpreter line are free; a TypeScript private field such as `#count = 0;` still counts.
|
|
1125
|
+
*
|
|
1126
|
+
* @param line - single comment-masked and decorator-masked source line
|
|
1127
|
+
* @returns True when the trimmed line is non-empty and does not start with `#!`; false otherwise.
|
|
1128
|
+
*/
|
|
1129
|
+
function isSubstantiveLine(line: string): boolean {
|
|
636
1130
|
const trimmed = line.trim();
|
|
637
|
-
|
|
638
|
-
return false;
|
|
639
|
-
}
|
|
640
|
-
const name = basename(file.displayPath).toLowerCase();
|
|
641
|
-
const extension = extname(name);
|
|
642
|
-
const usesHashComments = [".yaml", ".yml", ".toml"].includes(extension) || name === ".npmrc" || name.startsWith(".env");
|
|
643
|
-
if ((usesHashComments || (file.isScript && trimmed.startsWith("#!"))) && trimmed.startsWith("#")) {
|
|
644
|
-
return false;
|
|
645
|
-
}
|
|
646
|
-
const usesSemicolonComments = extension === ".ini" || name === ".npmrc";
|
|
647
|
-
return !(usesSemicolonComments && trimmed.startsWith(";"));
|
|
1131
|
+
return trimmed !== "" && !trimmed.startsWith("#!");
|
|
648
1132
|
}
|
|
649
1133
|
|
|
650
|
-
|
|
1134
|
+
/**
|
|
1135
|
+
* Count logical lines in source without allocating a split array.
|
|
1136
|
+
*
|
|
1137
|
+
* @param source - text whose newline characters are counted
|
|
1138
|
+
* @returns Logical line count, where empty source is 1 and each trailing newline adds 1.
|
|
1139
|
+
*/
|
|
651
1140
|
function lineCount(source: string): number {
|
|
652
1141
|
let count = 1;
|
|
653
1142
|
for (let index = 0; index < source.length; index += 1) {
|
|
@@ -658,17 +1147,16 @@ function lineCount(source: string): number {
|
|
|
658
1147
|
return count;
|
|
659
1148
|
}
|
|
660
1149
|
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
*
|
|
671
|
-
* then walks every rule pack in a stable, deterministic order so reports and baselines remain reproducible.
|
|
1150
|
+
/**
|
|
1151
|
+
* Run enabled script checks in a stable order so that reports remain reproducible. Skip passes that require a parse when it is unavailable.
|
|
1152
|
+
*
|
|
1153
|
+
* @param file - script being checked and the path used in its findings
|
|
1154
|
+
* @param source - original script text used by lexical and text checks
|
|
1155
|
+
* @param comments - comment locations and text available to comment quality checks
|
|
1156
|
+
* @param config - selects rule passes and their settings
|
|
1157
|
+
* @param findings - caller's array to append script findings to
|
|
1158
|
+
* @param parsed - shared script parse when available for syntax-backed checks
|
|
1159
|
+
* @returns Nothing. Appends findings from enabled passes to the caller's array.
|
|
672
1160
|
*/
|
|
673
1161
|
function analyseTypeScriptRules(file: SourceFile, source: string, comments: CommentRecord[], config: Config, findings: Finding[], parsed?: ParsedScript): void {
|
|
674
1162
|
if (!isAnyRuleEnabled(config, TYPESCRIPT_RULE_IDS)) {
|
|
@@ -678,51 +1166,77 @@ function analyseTypeScriptRules(file: SourceFile, source: string, comments: Comm
|
|
|
678
1166
|
const blocks = isAnyRuleEnabled(config, BLOCK_DEPENDENT_RULE_IDS) ? functionBlocks(source, codeSource, parsed) : [];
|
|
679
1167
|
runRulePass(config, "docs.missing-file-overview", () => analyseFileOverviewDoc(file, source, findings));
|
|
680
1168
|
analyseBlocks(file, source, codeSource, blocks, config, findings);
|
|
681
|
-
runRulePass(config, "
|
|
682
|
-
|
|
1169
|
+
runRulePass(config, "test-quality.duplicate-test-body", () => {
|
|
1170
|
+
if (parsed) {
|
|
1171
|
+
analyseDuplicateTestGroups(file, parsed, findings);
|
|
1172
|
+
}
|
|
1173
|
+
});
|
|
1174
|
+
// Callables only the size and complexity rules measure; the documentation and naming rules never see them.
|
|
1175
|
+
runRuleGroupPass(config, BLOCK_MEASURE_RULE_IDS, () => {
|
|
1176
|
+
if (parsed) {
|
|
1177
|
+
for (const block of measuredOnlyFunctionBlocks(source, codeSource, parsed)) {
|
|
1178
|
+
analyseBlockMeasures(blockRuleContext(file, block, config, findings));
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
});
|
|
1182
|
+
runRulePass(config, "waste.unused-import", () => analyseUnusedImports(file, codeSource, source, findings, parsed));
|
|
1183
|
+
runRuleGroupPass(config, LINE_RULE_IDS, () => analyseLineRules(file, source, codeSource, config, findings, parsed));
|
|
683
1184
|
runRuleGroupPass(config, SECURITY_FLOW_RULE_IDS, () => analyseSecurityFlow(file, source, findings, parsed?.sourceFile));
|
|
684
1185
|
runRulePass(config, "waste.unreachable-code", () => analyseUnreachable(file, codeSource, findings));
|
|
685
|
-
//
|
|
686
|
-
// like the other syntax-backed passes instead of falling back to a lossy regex walk.
|
|
1186
|
+
// Without a parse, skip docblock checks because they need reliable callable signatures.
|
|
687
1187
|
runRuleGroupPass(config, DOCBLOCK_RULE_IDS, () => {
|
|
688
1188
|
if (parsed) {
|
|
689
|
-
analyseDocRules(file, findings, parsed
|
|
1189
|
+
analyseDocRules(file, findings, parsed, {
|
|
1190
|
+
isParamTagEveryCallable: optionBoolean(config, "docs.missing-param-tag", "everyCallable", true),
|
|
1191
|
+
isReturnTagEveryCallable: optionBoolean(config, "docs.missing-return-tag", "everyCallable", true),
|
|
1192
|
+
});
|
|
690
1193
|
}
|
|
691
1194
|
});
|
|
692
1195
|
runRulePass(config, "docs.missing-interface-doc", () => analyseInterfaceDocs(file, source, codeSource, findings));
|
|
693
|
-
runRuleGroupPass(config, INTERFACE_FIELD_RULE_IDS, () => analyseInterfaceFields(file, source, codeSource, config, findings));
|
|
694
1196
|
runRuleGroupPass(config, COMMENT_QUALITY_RULE_IDS, () => analyseCommentQualityRules({ file, source, codeSource, blocks, comments, config, findings }));
|
|
695
1197
|
runRuleGroupPass(config, CLASS_RULE_IDS, () => analyseClassRules(file, source, codeSource, config, findings, parsed));
|
|
696
1198
|
runRulePass(config, "dead-code.unused-private-method", () => analyseDeadCode(file, codeSource, findings));
|
|
697
|
-
runRuleGroupPass(config, IDENTIFIER_INVENTORY_RULE_IDS, () => {
|
|
698
|
-
// A normal deep script scan always supplies the shared parse; a missing result must not reparse.
|
|
699
|
-
if (!parsed) {
|
|
700
|
-
return;
|
|
701
|
-
}
|
|
702
|
-
const inventory = collectDeclaredIdentifiers(source, codeSource, parsed);
|
|
703
|
-
runRulePass(config, "naming.inconsistent-casing", () => analyseInconsistentCasing(file, inventory, config, findings));
|
|
704
|
-
runRulePass(config, "naming.acronym-case", () => analyseAcronymCase(file, inventory, config, findings));
|
|
705
|
-
});
|
|
706
1199
|
}
|
|
707
1200
|
|
|
708
|
-
|
|
1201
|
+
/**
|
|
1202
|
+
* Gate a single-rule pass on its enablement in config so disabled rules incur no execution cost.
|
|
1203
|
+
*
|
|
1204
|
+
* @param config - resolved scan configuration tested for rule enablement
|
|
1205
|
+
* @param ruleId - identifier of the rule guarded by this pass
|
|
1206
|
+
* @param action - callback executed only when config enables ruleId
|
|
1207
|
+
* @returns Nothing. Invokes action when ruleId is enabled; otherwise does nothing.
|
|
1208
|
+
*/
|
|
709
1209
|
function runRulePass(config: Config, ruleId: string, action: () => void): void {
|
|
710
1210
|
if (ruleEnabled(config, ruleId)) {
|
|
711
1211
|
action();
|
|
712
1212
|
}
|
|
713
1213
|
}
|
|
714
1214
|
|
|
715
|
-
|
|
1215
|
+
/**
|
|
1216
|
+
* Gate a multi-rule pass so it runs only when at least one rule in the group is enabled.
|
|
1217
|
+
*
|
|
1218
|
+
* @param config - resolved scan configuration tested against the rule group
|
|
1219
|
+
* @param ruleIds - rule identifiers belonging to the pass
|
|
1220
|
+
* @param action - callback executed only when at least one id in ruleIds is enabled
|
|
1221
|
+
* @returns Nothing. Invokes action if any rule in ruleIds is enabled; otherwise does nothing.
|
|
1222
|
+
*/
|
|
716
1223
|
function runRuleGroupPass(config: Config, ruleIds: readonly string[], action: () => void): void {
|
|
717
1224
|
if (isAnyRuleEnabled(config, ruleIds)) {
|
|
718
1225
|
action();
|
|
719
1226
|
}
|
|
720
1227
|
}
|
|
721
1228
|
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
1229
|
+
/**
|
|
1230
|
+
* Dispatch enabled rules for each parsed callable. Keep emission order stable because the report sort can preserve it for tied findings.
|
|
1231
|
+
*
|
|
1232
|
+
* @param file - source file whose path identifies the findings
|
|
1233
|
+
* @param source - original source text for test checks
|
|
1234
|
+
* @param codeSource - source with comments and literals masked for test checks
|
|
1235
|
+
* @param blocks - parsed callables to check
|
|
1236
|
+
* @param config - selects enabled rule groups and their settings
|
|
1237
|
+
* @param findings - caller's array to append rule results to
|
|
1238
|
+
* @returns Nothing. Appends enabled block, parameter naming and test findings to the caller's array.
|
|
1239
|
+
*/
|
|
726
1240
|
function analyseBlocks(file: SourceFile, source: string, codeSource: string, blocks: FunctionBlock[], config: Config, findings: Finding[]): void {
|
|
727
1241
|
const shouldAnalyseBlockRules = isAnyRuleEnabled(config, BLOCK_RULE_IDS);
|
|
728
1242
|
const shouldAnalyseParameterNaming = isAnyRuleEnabled(config, PARAMETER_NAMING_RULE_IDS);
|
|
@@ -743,32 +1257,48 @@ function analyseBlocks(file: SourceFile, source: string, codeSource: string, blo
|
|
|
743
1257
|
}
|
|
744
1258
|
}
|
|
745
1259
|
|
|
746
|
-
|
|
747
|
-
*
|
|
748
|
-
*
|
|
1260
|
+
/**
|
|
1261
|
+
* The naming contract exempts local bindings, tests, recognized comparator pairs, and `TestContext` `t` parameters from short-name checks.
|
|
1262
|
+
* Placeholder checks still cover every parameter.
|
|
1263
|
+
*
|
|
1264
|
+
* @param context - callable and location to check, configured rules, and destination findings array
|
|
1265
|
+
* @returns Nothing. Appends applicable parameter-name findings to the caller's array.
|
|
749
1266
|
*/
|
|
750
1267
|
function pushParameterNamingFindings(context: BlockRuleContext): void {
|
|
751
1268
|
const line = context.block.declarationLine;
|
|
752
1269
|
const params = parameterNames(context.block.params);
|
|
753
1270
|
const hasLocallyBoundParameters = isLocallyBoundParameterOwner(context.block);
|
|
1271
|
+
const isTestSourceFile = isTestPath(context.file.displayPath);
|
|
754
1272
|
for (const parameter of params) {
|
|
755
|
-
if (!hasLocallyBoundParameters && !isComparatorShortParameter(context, params, parameter.name)) {
|
|
1273
|
+
if (!hasLocallyBoundParameters && !isComparatorShortParameter(context, params, parameter.name) && !isTestContextShortParameter(parameter, isTestSourceFile)) {
|
|
756
1274
|
pushShortVariableAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
|
|
757
1275
|
}
|
|
758
1276
|
pushIdentifierQualityAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
|
|
759
|
-
if (isBooleanParameter(parameter.raw)) {
|
|
760
|
-
pushBooleanPrefixAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
|
|
761
|
-
pushNegativeBooleanAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
|
|
762
|
-
}
|
|
763
|
-
if (isGenericParameterCandidate(context, params.length, parameter.name)) {
|
|
764
|
-
pushGenericParameterAt(context.file, line, parameter.name, context.findings);
|
|
765
|
-
}
|
|
766
1277
|
}
|
|
767
1278
|
}
|
|
768
1279
|
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
1280
|
+
/**
|
|
1281
|
+
* Recognizes the standard `node:test` context parameter `t` so test helpers are not flagged as too short.
|
|
1282
|
+
* Matches when the parameter is named `t` and either lives in a test file or carries a `TestContext` type annotation.
|
|
1283
|
+
*
|
|
1284
|
+
* @param parameter - parsed parameter name and raw declaration text from the callable signature
|
|
1285
|
+
* @param isTestSourceFile - true when the enclosing file matches `isTestPath`
|
|
1286
|
+
* @returns True when parameter `t` qualifies for the test-context exemption; false for every other parameter.
|
|
1287
|
+
*/
|
|
1288
|
+
function isTestContextShortParameter(parameter: { name: string; raw: string }, isTestSourceFile: boolean): boolean {
|
|
1289
|
+
if (parameter.name !== "t") {
|
|
1290
|
+
return false;
|
|
1291
|
+
}
|
|
1292
|
+
return isTestSourceFile || /:\s*(?:import\([^)]+\)\.)?(?:[A-Za-z_$][A-Za-z0-9_$]*\.)?TestContext\b/.test(parameter.raw);
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
/**
|
|
1296
|
+
* Determine whether a callable's parameters are exempt from short-name checks as a test callback or local binding.
|
|
1297
|
+
* Exported bindings, declarations, methods, and unrecognized binding syntax remain covered.
|
|
1298
|
+
*
|
|
1299
|
+
* @param block - parsed function or callback block inspected for test status, export flag, and const/let binding
|
|
1300
|
+
* @returns True when block is a test callback or non-exported const/let-bound callable; false otherwise.
|
|
1301
|
+
*/
|
|
772
1302
|
function isLocallyBoundParameterOwner(block: FunctionBlock): boolean {
|
|
773
1303
|
if (block.isTest) {
|
|
774
1304
|
return true;
|
|
@@ -784,8 +1314,15 @@ function isLocallyBoundParameterOwner(block: FunctionBlock): boolean {
|
|
|
784
1314
|
return bindingName === block.name;
|
|
785
1315
|
}
|
|
786
1316
|
|
|
787
|
-
|
|
788
|
-
|
|
1317
|
+
/**
|
|
1318
|
+
* Check whether a parameter name qualifies for the conventional comparator exemption for the callable in context.
|
|
1319
|
+
* params must contain exactly `a` then `b`, and the callable's name or body must match comparator heuristics.
|
|
1320
|
+
*
|
|
1321
|
+
* @param context - callable block rule context supplying the enclosing callable's name and body
|
|
1322
|
+
* @param params - ordered parameter descriptors parsed from the callable signature
|
|
1323
|
+
* @param name - parameter name being evaluated for exemption
|
|
1324
|
+
* @returns True when name is `a` or `b` in an `(a, b)` comparator callable; false otherwise.
|
|
1325
|
+
*/
|
|
789
1326
|
function isComparatorShortParameter(context: BlockRuleContext, params: Array<{ name: string; raw: string }>, name: string): boolean {
|
|
790
1327
|
const names = params.map((parameter) => parameter.name);
|
|
791
1328
|
if (names.length !== 2 || names[0] !== "a" || names[1] !== "b" || (name !== "a" && name !== "b")) {
|
|
@@ -794,8 +1331,14 @@ function isComparatorShortParameter(context: BlockRuleContext, params: Array<{ n
|
|
|
794
1331
|
return isComparatorCallable(context.block.name, context.block.codeBody);
|
|
795
1332
|
}
|
|
796
1333
|
|
|
797
|
-
|
|
798
|
-
|
|
1334
|
+
/**
|
|
1335
|
+
* Test whether a callable's name or body matches comparator heuristics permitting conventional `(a, b)` parameters.
|
|
1336
|
+
* A dotted localeCompare matches with or without whitespace before the opening parenthesis, regardless of receiver or arguments.
|
|
1337
|
+
*
|
|
1338
|
+
* @param name - callable identifier tested against compare/Comparator/by naming prefixes
|
|
1339
|
+
* @param codeBody - comment-masked callable body tested for localeCompare or subtraction/comparison returns
|
|
1340
|
+
* @returns True when name or codeBody matches comparator heuristics; false otherwise.
|
|
1341
|
+
*/
|
|
799
1342
|
function isComparatorCallable(name: string, codeBody: string): boolean {
|
|
800
1343
|
return (
|
|
801
1344
|
/^(?:compare[A-Z0-9_]?|.*Comparator$|by[A-Z])/.test(name) ||
|
|
@@ -804,52 +1347,3 @@ function isComparatorCallable(name: string, codeBody: string): boolean {
|
|
|
804
1347
|
/\breturn\s+b\b[\s\S]*?(?:-\s*a\b|[<>]=?\s*a\b)/.test(codeBody)
|
|
805
1348
|
);
|
|
806
1349
|
}
|
|
807
|
-
|
|
808
|
-
// Generic-parameter rule is context-gated: only fires when the surrounding function is itself
|
|
809
|
-
// large enough to deserve attention (long, complex, or many parameters). Keeps noise down on
|
|
810
|
-
// trivial helpers that legitimately accept a `value` argument.
|
|
811
|
-
function isGenericParameterCandidate(context: BlockRuleContext, paramCount: number, name: string): boolean {
|
|
812
|
-
if (!context.config.placeholderNames.has(name.toLowerCase())) {
|
|
813
|
-
return false;
|
|
814
|
-
}
|
|
815
|
-
const minParameters = optionNumber(context.config, "naming.generic-parameter", "minParameters", 3);
|
|
816
|
-
const minLineCount = optionNumber(context.config, "naming.generic-parameter", "minLineCount", 30);
|
|
817
|
-
const minCyclomatic = optionNumber(context.config, "naming.generic-parameter", "minCyclomatic", 8);
|
|
818
|
-
return (
|
|
819
|
-
paramCount >= minParameters ||
|
|
820
|
-
context.block.lineCount >= minLineCount ||
|
|
821
|
-
context.cyclomatic >= minCyclomatic
|
|
822
|
-
);
|
|
823
|
-
}
|
|
824
|
-
|
|
825
|
-
// Only called after `isGenericParameterCandidate` has gated the placeholder check on the function's
|
|
826
|
-
// complexity and length - reaching this helper means the rule decided the finding is wanted.
|
|
827
|
-
// Reports the stable `naming.generic-parameter` finding.
|
|
828
|
-
function pushGenericParameterAt(file: SourceFile, line: number, name: string, findings: Finding[]): void {
|
|
829
|
-
findings.push(
|
|
830
|
-
makeFinding({
|
|
831
|
-
ruleId: "naming.generic-parameter",
|
|
832
|
-
message: `Parameter \`${name}\` uses a placeholder name in a function that meets context-gating thresholds.`,
|
|
833
|
-
filePath: file.displayPath,
|
|
834
|
-
line,
|
|
835
|
-
severity: "advisory",
|
|
836
|
-
pillar: "naming",
|
|
837
|
-
confidence: "medium",
|
|
838
|
-
symbol: name,
|
|
839
|
-
remediation: "Use a name that describes the parameter's role.",
|
|
840
|
-
metadata: { identifierName: name, surface: "parameter" },
|
|
841
|
-
}),
|
|
842
|
-
);
|
|
843
|
-
}
|
|
844
|
-
|
|
845
|
-
// Two positive cases: explicit `: boolean` annotation, or a default value of `true`/`false`.
|
|
846
|
-
// Explicit `as` casts are rejected so generic-call sites don't trip the boolean-name checks.
|
|
847
|
-
function isBooleanParameter(raw: string): boolean {
|
|
848
|
-
if (/:\s*boolean\b/.test(raw)) {
|
|
849
|
-
return true;
|
|
850
|
-
}
|
|
851
|
-
if (/\bas\b/.test(raw)) {
|
|
852
|
-
return false;
|
|
853
|
-
}
|
|
854
|
-
return /=\s*(?:true|false)\s*$/.test(raw);
|
|
855
|
-
}
|