@blundergoat/gruff-ts 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +123 -1
- package/CONTRIBUTING.md +32 -25
- package/README.md +55 -46
- package/SECURITY.md +18 -30
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -13
- package/docs/agent-hook.md +33 -24
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +173 -71
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -157
- package/docs/rules.md +140 -106
- package/package.json +10 -8
- package/src/analyser.ts +886 -282
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +85 -55
- package/src/blocks.ts +579 -364
- package/src/changed-regions.ts +414 -65
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +461 -302
- package/src/cli-program.ts +956 -166
- package/src/cli.ts +9 -2
- package/src/comment-rules.ts +277 -414
- package/src/comment-scanner.ts +363 -44
- package/src/complexity-metrics.ts +320 -0
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +778 -210
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +188 -61
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +521 -148
- package/src/doc-rules.ts +592 -147
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +240 -89
- package/src/findings.ts +48 -24
- package/src/fixture-purpose-rules.ts +226 -48
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +336 -106
- package/src/hook-contract.ts +708 -211
- package/src/init-config.ts +169 -114
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -419
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +33 -107
- package/src/parsed-script.ts +1206 -0
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +97 -71
- package/src/project-config-rules.ts +335 -146
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +284 -0
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +864 -195
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +255 -52
- package/src/security-flow-rules.ts +930 -109
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +502 -375
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +380 -148
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +422 -228
- package/src/text-scans.ts +67 -9
- package/src/types.ts +222 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -153
- package/src/test-fixtures.ts +0 -668
package/src/project-rules.ts
CHANGED
|
@@ -9,19 +9,18 @@ import { makeFinding } from "./findings.ts";
|
|
|
9
9
|
import { fileBaseName } from "./findings-helpers.ts";
|
|
10
10
|
import type { Config, Finding, Severity } from "./types.ts";
|
|
11
11
|
|
|
12
|
-
// Read-once snapshot of a discovered file
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
// (single/double-quoted strings stay intact), so syntax-pattern rules can skip fixture
|
|
16
|
-
// template-literal content without losing real `import ... from "..."` detection.
|
|
12
|
+
// Read-once snapshot of a discovered file for cross-file architecture rules. Stores only extracted
|
|
13
|
+
// import/export statements and substantive code-line count so multi-thousand-file repositories do
|
|
14
|
+
// not retain full line arrays in memory across the whole scan.
|
|
17
15
|
export interface ProjectSource {
|
|
18
16
|
file: SourceFile;
|
|
19
|
-
|
|
20
|
-
|
|
17
|
+
importStatements: ImportStatement[];
|
|
18
|
+
// Code lines only, so a module's share of production source does not grow with its documentation.
|
|
19
|
+
codeLineCount: number;
|
|
21
20
|
}
|
|
22
21
|
|
|
23
|
-
// Project-wide aggregate built once per scan and reused by every architecture rule (cycle detection
|
|
24
|
-
// large-module concentration
|
|
22
|
+
// Project-wide aggregate built once per scan and reused by every architecture rule (cycle detection and
|
|
23
|
+
// large-module concentration). `scriptSources` is a pre-filtered view of
|
|
25
24
|
// `sources` so per-rule code paths don't repeat the script-file check.
|
|
26
25
|
export interface ProjectIndex {
|
|
27
26
|
sources: ProjectSource[];
|
|
@@ -30,19 +29,18 @@ export interface ProjectIndex {
|
|
|
30
29
|
importsByFile: Map<string, ImportEdge[]>;
|
|
31
30
|
}
|
|
32
31
|
|
|
33
|
-
// One import statement in the graph. `
|
|
34
|
-
//
|
|
32
|
+
// One import statement in the graph. `targetPath` is set only when the specifier resolves to a file
|
|
33
|
+
// gruff has actually discovered.
|
|
35
34
|
interface ImportEdge {
|
|
36
35
|
specifier: string;
|
|
37
36
|
line: number;
|
|
38
|
-
parentSegments: number;
|
|
39
37
|
isTypeOnly: boolean;
|
|
40
38
|
targetPath?: string;
|
|
41
39
|
}
|
|
42
40
|
|
|
43
41
|
// Raw import/export statement span extracted before edge parsing. `line` anchors every edge found
|
|
44
42
|
// inside the statement, even when the specifier appears several physical lines later.
|
|
45
|
-
interface ImportStatement {
|
|
43
|
+
export interface ImportStatement {
|
|
46
44
|
source: string;
|
|
47
45
|
line: number;
|
|
48
46
|
}
|
|
@@ -82,8 +80,12 @@ interface ArchitectureRuleOptions {
|
|
|
82
80
|
shouldSkipCircularImports?: boolean;
|
|
83
81
|
}
|
|
84
82
|
|
|
85
|
-
|
|
86
|
-
|
|
83
|
+
/**
|
|
84
|
+
* Copies and sorts discovered sources by display path without reordering the input array so cross-file rules share a deterministic view.
|
|
85
|
+
*
|
|
86
|
+
* @param projectSources - discovered source snapshots to sort and index
|
|
87
|
+
* @returns Project index containing sorted sources, script sources, their path set, and resolved import edges.
|
|
88
|
+
*/
|
|
87
89
|
export function buildProjectIndex(projectSources: ProjectSource[]): ProjectIndex {
|
|
88
90
|
const sources = [...projectSources].sort((left, right) => left.file.displayPath.localeCompare(right.file.displayPath));
|
|
89
91
|
const scriptSources = sources.filter((source) => source.file.isScript);
|
|
@@ -95,12 +97,16 @@ export function buildProjectIndex(projectSources: ProjectSource[]): ProjectIndex
|
|
|
95
97
|
return { sources, scriptSources, sourcePaths, importsByFile };
|
|
96
98
|
}
|
|
97
99
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
+
/**
|
|
101
|
+
* Runs enabled circular-import and large-module concentration checks in that stable order.
|
|
102
|
+
*
|
|
103
|
+
* @param index - project index supplying sources and import edges
|
|
104
|
+
* @param config - rule configuration supplying enabled flags, thresholds, and severities
|
|
105
|
+
* @param findings - destination array for emitted findings
|
|
106
|
+
* @param options - optional switches that can suppress the circular-import check when already enabled
|
|
107
|
+
* @returns Nothing. Appends any reported findings to `findings`.
|
|
108
|
+
*/
|
|
100
109
|
export function analyseArchitectureRules(index: ProjectIndex, config: Config, findings: Finding[], options: ArchitectureRuleOptions = {}): void {
|
|
101
|
-
if (ruleEnabled(config, DEEP_RELATIVE_IMPORT_RULE_ID)) {
|
|
102
|
-
analyseDeepRelativeImports(index, config, findings);
|
|
103
|
-
}
|
|
104
110
|
if (!options.shouldSkipCircularImports && ruleEnabled(config, CIRCULAR_IMPORT_RULE_ID)) {
|
|
105
111
|
analyseCircularImportRule(index, findings);
|
|
106
112
|
}
|
|
@@ -109,46 +115,15 @@ export function analyseArchitectureRules(index: ProjectIndex, config: Config, fi
|
|
|
109
115
|
}
|
|
110
116
|
}
|
|
111
117
|
|
|
112
|
-
const DEEP_RELATIVE_IMPORT_RULE_ID = "design.deep-relative-import";
|
|
113
118
|
export const CIRCULAR_IMPORT_RULE_ID = "design.circular-import";
|
|
114
119
|
const LARGE_MODULE_CONCENTRATION_RULE_ID = "design.large-module-concentration";
|
|
115
120
|
|
|
116
|
-
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
*
|
|
121
|
-
|
|
122
|
-
function analyseDeepRelativeImports(index: ProjectIndex, config: Config, findings: Finding[]): void {
|
|
123
|
-
const maxParentSegments = threshold(config, "design.deep-relative-import", 2);
|
|
124
|
-
const severity = ruleSeverity(config, DEEP_RELATIVE_IMPORT_RULE_ID, "advisory");
|
|
125
|
-
for (const source of index.scriptSources) {
|
|
126
|
-
const edges = index.importsByFile.get(source.file.displayPath) ?? [];
|
|
127
|
-
for (const edge of edges) {
|
|
128
|
-
if (edge.parentSegments <= maxParentSegments) {
|
|
129
|
-
continue;
|
|
130
|
-
}
|
|
131
|
-
findings.push(
|
|
132
|
-
makeFinding({
|
|
133
|
-
ruleId: DEEP_RELATIVE_IMPORT_RULE_ID,
|
|
134
|
-
message: `Relative import \`${edge.specifier}\` climbs ${edge.parentSegments} directories.`,
|
|
135
|
-
filePath: source.file.displayPath,
|
|
136
|
-
line: edge.line,
|
|
137
|
-
severity,
|
|
138
|
-
pillar: "design",
|
|
139
|
-
confidence: "medium",
|
|
140
|
-
symbol: edge.specifier,
|
|
141
|
-
remediation: "Move the shared module closer to the caller or introduce a local barrel/module boundary.",
|
|
142
|
-
metadata: { specifier: edge.specifier, parentSegments: edge.parentSegments, maxParentSegments },
|
|
143
|
-
}),
|
|
144
|
-
);
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/*
|
|
150
|
-
* Reports one finding per strongly connected component in the runtime import graph. The component
|
|
151
|
-
* list comes back already deterministic from `importCycles`, so fingerprints are reproducible.
|
|
121
|
+
/**
|
|
122
|
+
* Records one finding for each cyclic runtime-import component in deterministic `importCycles` order, skipping components without an anchor.
|
|
123
|
+
*
|
|
124
|
+
* @param index - project index supplying script sources and import edges
|
|
125
|
+
* @param findings - destination array for qualifying circular-import findings
|
|
126
|
+
* @returns Nothing. Appends one finding to `findings` for each anchored component.
|
|
152
127
|
*/
|
|
153
128
|
export function analyseCircularImportRule(index: ProjectIndex, findings: Finding[]): void {
|
|
154
129
|
for (const cycle of importCycles(index)) {
|
|
@@ -159,9 +134,12 @@ export function analyseCircularImportRule(index: ProjectIndex, findings: Finding
|
|
|
159
134
|
}
|
|
160
135
|
}
|
|
161
136
|
|
|
162
|
-
|
|
163
|
-
*
|
|
164
|
-
*
|
|
137
|
+
/**
|
|
138
|
+
* Builds a circular-import finding anchored at the first file in the cycle so the stable fingerprint and reported line match across reruns.
|
|
139
|
+
*
|
|
140
|
+
* @param index - project index used to resolve the anchor script source and import line
|
|
141
|
+
* @param cycle - strongly connected import component with sorted files and representative cycle path
|
|
142
|
+
* @returns Finding anchored at the first cycle file, or undefined when no indexed script source matches that anchor.
|
|
165
143
|
*/
|
|
166
144
|
function circularImportFinding(index: ProjectIndex, cycle: ImportCycle): Finding | undefined {
|
|
167
145
|
const anchorPath = cycle.files[0] ?? "";
|
|
@@ -183,16 +161,27 @@ function circularImportFinding(index: ProjectIndex, cycle: ImportCycle): Finding
|
|
|
183
161
|
});
|
|
184
162
|
}
|
|
185
163
|
|
|
186
|
-
|
|
187
|
-
|
|
164
|
+
/**
|
|
165
|
+
* Locates the first non-type-only import line in the anchor file targeting another member of the cycle, keeping the anchor defined.
|
|
166
|
+
*
|
|
167
|
+
* @param index - project index mapping files to extracted import edges
|
|
168
|
+
* @param anchorPath - display path of the anchor file whose edges are searched
|
|
169
|
+
* @param cycle - cycle record listing member file paths
|
|
170
|
+
* @returns Line number of the first matching runtime import edge, or 1 when no qualifying edge exists.
|
|
171
|
+
*/
|
|
188
172
|
function circularImportLine(index: ProjectIndex, anchorPath: string, cycle: ImportCycle): number {
|
|
189
173
|
const anchorEdges = index.importsByFile.get(anchorPath) ?? [];
|
|
190
174
|
return anchorEdges.find((edge) => !edge.isTypeOnly && edge.targetPath && cycle.files.includes(edge.targetPath))?.line ?? 1;
|
|
191
175
|
}
|
|
192
176
|
|
|
193
|
-
|
|
194
|
-
*
|
|
195
|
-
*
|
|
177
|
+
/**
|
|
178
|
+
* Checks whether the largest production source file exceeds the configured share after the project and file size minimums are met.
|
|
179
|
+
* Emits at most one stable finding so the report points to the most concentrated module.
|
|
180
|
+
*
|
|
181
|
+
* @param index - project index supplying source files and their line counts
|
|
182
|
+
* @param config - supplies the concentration thresholds and finding severity
|
|
183
|
+
* @param findings - destination for the finding if the largest file qualifies
|
|
184
|
+
* @returns Nothing. Appends a finding only when the project and largest file meet the rule's conditions.
|
|
196
185
|
*/
|
|
197
186
|
function analyseLargeModuleConcentration(index: ProjectIndex, config: Config, findings: Finding[]): void {
|
|
198
187
|
const candidate = largeModuleCandidate(index, largeModuleThresholds(config));
|
|
@@ -202,8 +191,13 @@ function analyseLargeModuleConcentration(index: ProjectIndex, config: Config, fi
|
|
|
202
191
|
findings.push(largeModuleConcentrationFinding(candidate, ruleSeverity(config, "design.large-module-concentration", "advisory")));
|
|
203
192
|
}
|
|
204
193
|
|
|
205
|
-
|
|
206
|
-
|
|
194
|
+
/**
|
|
195
|
+
* Reads the large-module concentration limits from config so candidate selection requires both minima to be met and the share cap exceeded.
|
|
196
|
+
* Missing settings default to 4 production files, 80 lines for the largest file, and a 55 percent share cap.
|
|
197
|
+
*
|
|
198
|
+
* @param config - rule configuration providing optional `minFiles`, `minLines`, and share threshold overrides
|
|
199
|
+
* @returns Resolved thresholds for production file count, largest file line count, and share percentage cap.
|
|
200
|
+
*/
|
|
207
201
|
function largeModuleThresholds(config: Config): LargeModuleThresholds {
|
|
208
202
|
return {
|
|
209
203
|
minFiles: optionNumber(config, "design.large-module-concentration", "minFiles", 4),
|
|
@@ -212,8 +206,13 @@ function largeModuleThresholds(config: Config): LargeModuleThresholds {
|
|
|
212
206
|
};
|
|
213
207
|
}
|
|
214
208
|
|
|
215
|
-
|
|
216
|
-
|
|
209
|
+
/**
|
|
210
|
+
* Selects the largest production module when the project meets the file-count minimum and the module exceeds the size and dominance limits.
|
|
211
|
+
*
|
|
212
|
+
* @param index - project index supplying script sources and production line counts
|
|
213
|
+
* @param thresholds - resolved file-count, line-count, and share-percentage limits
|
|
214
|
+
* @returns Largest production module with total lines, share percentage, and thresholds, or undefined when ineligible.
|
|
215
|
+
*/
|
|
217
216
|
function largeModuleCandidate(index: ProjectIndex, thresholds: LargeModuleThresholds): LargeModuleCandidate | undefined {
|
|
218
217
|
const modules = productionModuleLineCounts(index);
|
|
219
218
|
if (modules.length < thresholds.minFiles) {
|
|
@@ -234,23 +233,38 @@ function largeModuleCandidate(index: ProjectIndex, thresholds: LargeModuleThresh
|
|
|
234
233
|
return { ...largest, totalLines, sharePercent, thresholds };
|
|
235
234
|
}
|
|
236
235
|
|
|
237
|
-
|
|
238
|
-
|
|
236
|
+
/**
|
|
237
|
+
* Evaluates whether the largest module meets the inclusive line minimum and exceeds the share cap so tiny dominant modules remain ineligible.
|
|
238
|
+
*
|
|
239
|
+
* @param largest - candidate module entry containing its production line count
|
|
240
|
+
* @param sharePercent - candidate module's rounded percentage of total production lines
|
|
241
|
+
* @param thresholds - resolved line minimum and maximum share percentage limits
|
|
242
|
+
* @returns True only when `largest.lines` meets `minLines` and `sharePercent` exceeds `maxSharePercent`.
|
|
243
|
+
*/
|
|
239
244
|
function exceedsLargeModuleThresholds(largest: ModuleLineCount, sharePercent: number, thresholds: LargeModuleThresholds): boolean {
|
|
240
245
|
return largest.lines >= thresholds.minLines && sharePercent > thresholds.maxSharePercent;
|
|
241
246
|
}
|
|
242
247
|
|
|
243
|
-
|
|
244
|
-
|
|
248
|
+
/**
|
|
249
|
+
* Collects production script line counts, excluding tests, fixtures, declarations, and generated paths, for deterministic largest-source selection.
|
|
250
|
+
*
|
|
251
|
+
* @param index - project index supplying script sources and cached code line counts
|
|
252
|
+
* @returns Module line-count entries sorted by descending line count then ascending display path.
|
|
253
|
+
*/
|
|
245
254
|
function productionModuleLineCounts(index: ProjectIndex): ModuleLineCount[] {
|
|
246
255
|
return index.scriptSources
|
|
247
256
|
.filter((source) => isProductionSourcePath(source.file.displayPath))
|
|
248
|
-
.map((source) => ({ source, lines: source.
|
|
257
|
+
.map((source) => ({ source, lines: source.codeLineCount }))
|
|
249
258
|
.sort((left, right) => right.lines - left.lines || left.source.file.displayPath.localeCompare(right.source.file.displayPath));
|
|
250
259
|
}
|
|
251
260
|
|
|
252
|
-
|
|
253
|
-
|
|
261
|
+
/**
|
|
262
|
+
* Builds a stable design finding with measured counts and all configured thresholds so reviewers can explain the result without rerunning.
|
|
263
|
+
*
|
|
264
|
+
* @param candidate - qualifying largest production module and its share metrics
|
|
265
|
+
* @param severity - configured severity level for the emitted finding
|
|
266
|
+
* @returns Design finding anchored at line 1 of the concentrated module.
|
|
267
|
+
*/
|
|
254
268
|
function largeModuleConcentrationFinding(candidate: LargeModuleCandidate, severity: Severity): Finding {
|
|
255
269
|
return makeFinding({
|
|
256
270
|
ruleId: LARGE_MODULE_CONCENTRATION_RULE_ID,
|
|
@@ -273,19 +287,28 @@ function largeModuleConcentrationFinding(candidate: LargeModuleCandidate, severi
|
|
|
273
287
|
});
|
|
274
288
|
}
|
|
275
289
|
|
|
276
|
-
|
|
277
|
-
|
|
290
|
+
/**
|
|
291
|
+
* Extracts relative import edges in deterministic order from pre-extracted imports, keeping unresolved edges for parent-hop checks.
|
|
292
|
+
*
|
|
293
|
+
* @param source - project source snapshot providing display path and pre-extracted import statements
|
|
294
|
+
* @param sourcePaths - set of discovered script display paths used to resolve relative targets
|
|
295
|
+
* @returns Relative import edges ordered by starting line then specifier, resolving targets only within `sourcePaths`.
|
|
296
|
+
*/
|
|
278
297
|
function importEdgesForSource(source: ProjectSource, sourcePaths: Set<string>): ImportEdge[] {
|
|
279
298
|
const edges: ImportEdge[] = [];
|
|
280
|
-
for (const statement of
|
|
299
|
+
for (const statement of source.importStatements) {
|
|
281
300
|
edges.push(...importEdgesForStatement(source.file.displayPath, statement, sourcePaths));
|
|
282
301
|
}
|
|
283
302
|
return edges.sort((left, right) => left.line - right.line || left.specifier.localeCompare(right.specifier));
|
|
284
303
|
}
|
|
285
304
|
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
305
|
+
/**
|
|
306
|
+
* Reassembles multi-line import/export spans from template-masked lines for graph extraction, skipping non-declaration lines and incomplete tails.
|
|
307
|
+
*
|
|
308
|
+
* @param lines - template-masked lines of a source file in line order
|
|
309
|
+
* @returns Complete import/export statement spans paired with their 1-based starting line numbers.
|
|
310
|
+
*/
|
|
311
|
+
export function extractImportStatements(lines: string[]): ImportStatement[] {
|
|
289
312
|
const statements: ImportStatement[] = [];
|
|
290
313
|
let current = "";
|
|
291
314
|
let startLine = 1;
|
|
@@ -309,15 +332,24 @@ function importStatements(lines: string[]): ImportStatement[] {
|
|
|
309
332
|
return statements;
|
|
310
333
|
}
|
|
311
334
|
|
|
312
|
-
|
|
313
|
-
|
|
335
|
+
/**
|
|
336
|
+
* Checks whether an accumulated import/export span has reached a quoted module specifier, covering bare side-effect imports and `from` clauses.
|
|
337
|
+
*
|
|
338
|
+
* @param statement - accumulated source text for a candidate import or export statement
|
|
339
|
+
* @returns True once `statement` contains a quoted specifier, otherwise false.
|
|
340
|
+
*/
|
|
314
341
|
function isImportStatementComplete(statement: string): boolean {
|
|
315
342
|
return /\b(?:from\s*)?["'][^"']+["']/.test(statement);
|
|
316
343
|
}
|
|
317
344
|
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
345
|
+
/**
|
|
346
|
+
* Extracts relative import and re-export edges anchored at the statement's starting line, omitting non-relative specifiers.
|
|
347
|
+
*
|
|
348
|
+
* @param importerPath - display path of the importing file used as the resolution base
|
|
349
|
+
* @param statement - complete import/export statement text and starting line
|
|
350
|
+
* @param sourcePaths - set of discovered script display paths used as target candidates
|
|
351
|
+
* @returns Relative import edges found in `statement`, leaving `targetPath` unset when unresolved.
|
|
352
|
+
*/
|
|
321
353
|
function importEdgesForStatement(importerPath: string, statement: ImportStatement, sourcePaths: Set<string>): ImportEdge[] {
|
|
322
354
|
const edges: ImportEdge[] = [];
|
|
323
355
|
for (const match of statement.source.matchAll(/\b(?:import|export)\b(?:[\s\S]*?\bfrom\s*)?\s*["']([^"']+)["']/g)) {
|
|
@@ -329,8 +361,16 @@ function importEdgesForStatement(importerPath: string, statement: ImportStatemen
|
|
|
329
361
|
return edges;
|
|
330
362
|
}
|
|
331
363
|
|
|
332
|
-
|
|
333
|
-
|
|
364
|
+
/**
|
|
365
|
+
* Builds an import-rule edge for a relative specifier while retaining its source line anchor and type-only classification.
|
|
366
|
+
*
|
|
367
|
+
* @param importerPath - display path of the importing file used as the resolution base
|
|
368
|
+
* @param specifier - module specifier text, including any relative parent hops
|
|
369
|
+
* @param line - 1-based starting line of the enclosing import or export statement
|
|
370
|
+
* @param sourcePaths - discovered script display paths eligible as resolution targets
|
|
371
|
+
* @param isTypeOnly - whether the statement uses an `import type` or `export type` prefix
|
|
372
|
+
* @returns Edge object (without `targetPath` when unresolved), or undefined for non-relative specifiers.
|
|
373
|
+
*/
|
|
334
374
|
function importEdgeForSpecifier(importerPath: string, specifier: string, line: number, sourcePaths: Set<string>, isTypeOnly: boolean): ImportEdge | undefined {
|
|
335
375
|
if (!specifier.startsWith(".")) {
|
|
336
376
|
return undefined;
|
|
@@ -339,19 +379,29 @@ function importEdgeForSpecifier(importerPath: string, specifier: string, line: n
|
|
|
339
379
|
return {
|
|
340
380
|
specifier,
|
|
341
381
|
line,
|
|
342
|
-
parentSegments: specifier.split("/").filter((segment) => segment === "..").length,
|
|
343
382
|
isTypeOnly,
|
|
344
383
|
...(targetPath ? { targetPath } : {}),
|
|
345
384
|
};
|
|
346
385
|
}
|
|
347
386
|
|
|
348
|
-
|
|
387
|
+
/**
|
|
388
|
+
* Detects an `import type` or `export type` prefix so cycle checks can exclude type-only edges; inline type specifiers are not matched.
|
|
389
|
+
*
|
|
390
|
+
* @param importStatement - matched import or export clause text up to its module specifier
|
|
391
|
+
* @returns True when `importStatement` starts a type-only import or export, otherwise false.
|
|
392
|
+
*/
|
|
349
393
|
function isTypeOnlyImportStatement(importStatement: string): boolean {
|
|
350
394
|
return /\b(?:import|export)\s+type\b/.test(importStatement);
|
|
351
395
|
}
|
|
352
396
|
|
|
353
|
-
|
|
354
|
-
|
|
397
|
+
/**
|
|
398
|
+
* Resolves a relative specifier from the importing file's directory in a stable candidate order so cycle output stays reproducible.
|
|
399
|
+
*
|
|
400
|
+
* @param importerPath - display path of the importing file providing the base directory
|
|
401
|
+
* @param specifier - relative module specifier to resolve
|
|
402
|
+
* @param sourcePaths - set of discovered script paths defining available targets
|
|
403
|
+
* @returns First candidate path present in `sourcePaths`, or undefined if none match.
|
|
404
|
+
*/
|
|
355
405
|
function resolveRelativeImport(importerPath: string, specifier: string, sourcePaths: Set<string>): string | undefined {
|
|
356
406
|
const basePath = normalizeDisplayPath(join(dirnamePath(importerPath), specifier));
|
|
357
407
|
for (const candidate of importPathCandidates(basePath)) {
|
|
@@ -362,8 +412,13 @@ function resolveRelativeImport(importerPath: string, specifier: string, sourcePa
|
|
|
362
412
|
return undefined;
|
|
363
413
|
}
|
|
364
414
|
|
|
365
|
-
|
|
366
|
-
|
|
415
|
+
/**
|
|
416
|
+
* Expands `basePath` into deduplicated resolution candidates: explicit extensions try the original path and script substitutions,
|
|
417
|
+
* while extensionless paths try script extensions and directory index files before normalization.
|
|
418
|
+
*
|
|
419
|
+
* @param basePath - joined and normalized relative target path before extension resolution
|
|
420
|
+
* @returns Ordered list of normalized candidate display paths without duplicates.
|
|
421
|
+
*/
|
|
367
422
|
function importPathCandidates(basePath: string): string[] {
|
|
368
423
|
const extensions = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
|
|
369
424
|
const candidates = new Set<string>();
|
|
@@ -382,8 +437,12 @@ function importPathCandidates(basePath: string): string[] {
|
|
|
382
437
|
return [...candidates].map(normalizeDisplayPath);
|
|
383
438
|
}
|
|
384
439
|
|
|
385
|
-
|
|
386
|
-
|
|
440
|
+
/**
|
|
441
|
+
* Derives deterministic cycle records from the import graph so circular-import reporting emits one finding per multi-file component.
|
|
442
|
+
*
|
|
443
|
+
* @param index - project index supplying script sources and resolved import edges
|
|
444
|
+
* @returns Sorted cycle records with sorted member files and a representative closed path, or an empty list when none qualify.
|
|
445
|
+
*/
|
|
387
446
|
function importCycles(index: ProjectIndex): ImportCycle[] {
|
|
388
447
|
return stronglyConnectedImportComponents(index)
|
|
389
448
|
.map((files) => ({ files, representativeCycle: representativeCycle(index, files) }))
|
|
@@ -401,8 +460,12 @@ interface StronglyConnectedState {
|
|
|
401
460
|
components: string[][];
|
|
402
461
|
}
|
|
403
462
|
|
|
404
|
-
|
|
405
|
-
|
|
463
|
+
/**
|
|
464
|
+
* Computes sorted multi-file strongly connected components from the import graph, excluding type-only edges and singletons, for stable findings.
|
|
465
|
+
*
|
|
466
|
+
* @param index - project index supplying files and resolved import edges
|
|
467
|
+
* @returns Sorted arrays of member file paths for components with two or more files, or an empty list when none exist.
|
|
468
|
+
*/
|
|
406
469
|
function stronglyConnectedImportComponents(index: ProjectIndex): string[][] {
|
|
407
470
|
const state: StronglyConnectedState = {
|
|
408
471
|
nextIndex: 0,
|
|
@@ -423,7 +486,14 @@ function stronglyConnectedImportComponents(index: ProjectIndex): string[][] {
|
|
|
423
486
|
.sort((left, right) => left.join("\0").localeCompare(right.join("\0")));
|
|
424
487
|
}
|
|
425
488
|
|
|
426
|
-
|
|
489
|
+
/**
|
|
490
|
+
* Runs Tarjan's DFS from `path`, mutating `state` to track discovery order and low-links while keeping non-root vertices on the stack until popped.
|
|
491
|
+
*
|
|
492
|
+
* @param index - project index supplying outgoing runtime import targets
|
|
493
|
+
* @param path - display path of the current vertex being visited
|
|
494
|
+
* @param state - mutable Tarjan traversal state recording indices, low-links, active stack, and completed components
|
|
495
|
+
* @returns Nothing. Mutates `state` in place and pushes completed strongly connected components onto `state.components`.
|
|
496
|
+
*/
|
|
427
497
|
function visitStronglyConnectedImportComponent(index: ProjectIndex, path: string, state: StronglyConnectedState): void {
|
|
428
498
|
state.indices.set(path, state.nextIndex);
|
|
429
499
|
state.lowLinks.set(path, state.nextIndex);
|
|
@@ -460,23 +530,46 @@ function visitStronglyConnectedImportComponent(index: ProjectIndex, path: string
|
|
|
460
530
|
state.components.push(component);
|
|
461
531
|
}
|
|
462
532
|
|
|
463
|
-
|
|
533
|
+
/**
|
|
534
|
+
* Reads `path`'s Tarjan discovery index from traversal state, defaulting absent entries to zero.
|
|
535
|
+
*
|
|
536
|
+
* @param state - mutable Tarjan traversal state holding discovery indices
|
|
537
|
+
* @param path - display path of the vertex to look up
|
|
538
|
+
* @returns Discovery index recorded for `path`, or 0 when absent.
|
|
539
|
+
*/
|
|
464
540
|
function indexFor(state: StronglyConnectedState, path: string): number {
|
|
465
541
|
return state.indices.get(path) ?? 0;
|
|
466
542
|
}
|
|
467
543
|
|
|
468
|
-
|
|
544
|
+
/**
|
|
545
|
+
* Reads `path`'s Tarjan low-link value from traversal state for component-root comparisons.
|
|
546
|
+
*
|
|
547
|
+
* @param state - mutable Tarjan traversal state holding low-link values
|
|
548
|
+
* @param path - display path of the vertex to look up
|
|
549
|
+
* @returns Low-link value recorded for `path`, or 0 when no value is recorded.
|
|
550
|
+
*/
|
|
469
551
|
function lowLinkFor(state: StronglyConnectedState, path: string): number {
|
|
470
552
|
return state.lowLinks.get(path) ?? 0;
|
|
471
553
|
}
|
|
472
554
|
|
|
473
|
-
|
|
555
|
+
/**
|
|
556
|
+
* Collects sorted, unique resolved value-import targets for a file under the stable runtime-cycle contract.
|
|
557
|
+
*
|
|
558
|
+
* @param index - project index mapping file paths to extracted import edges
|
|
559
|
+
* @param path - display path of the importing file
|
|
560
|
+
* @returns Sorted unique target paths for non-type-only resolved imports, or an empty list when none exist.
|
|
561
|
+
*/
|
|
474
562
|
function circularImportTargets(index: ProjectIndex, path: string): string[] {
|
|
475
563
|
return [...new Set((index.importsByFile.get(path) ?? []).filter((edge) => !edge.isTypeOnly).map((edge) => edge.targetPath).filter(isString))].sort();
|
|
476
564
|
}
|
|
477
565
|
|
|
478
|
-
|
|
479
|
-
|
|
566
|
+
/**
|
|
567
|
+
* Chooses a closed path through the component starting from the first member for a grouped cycle finding.
|
|
568
|
+
*
|
|
569
|
+
* @param index - project index supplying runtime import edges
|
|
570
|
+
* @param files - sorted member paths belonging to the strongly connected component
|
|
571
|
+
* @returns Closed path starting and ending at `files[0]`, an empty list if `files` is empty, or `files` unchanged if no closing path is found.
|
|
572
|
+
*/
|
|
480
573
|
function representativeCycle(index: ProjectIndex, files: string[]): string[] {
|
|
481
574
|
const anchor = files[0];
|
|
482
575
|
if (!anchor) {
|
|
@@ -498,7 +591,15 @@ interface ComponentPathSearch {
|
|
|
498
591
|
path: string[];
|
|
499
592
|
}
|
|
500
593
|
|
|
501
|
-
|
|
594
|
+
/**
|
|
595
|
+
* Finds a shortest directed runtime-import path between two component members while restricting traversal to `members` for a representative cycle.
|
|
596
|
+
*
|
|
597
|
+
* @param index - project index supplying runtime import targets
|
|
598
|
+
* @param start - starting member path for the breadth-first search
|
|
599
|
+
* @param end - target member path to reach
|
|
600
|
+
* @param members - set of component file paths allowed during traversal
|
|
601
|
+
* @returns Path including both `start` and `end`, or undefined when no directed path reaches `end`.
|
|
602
|
+
*/
|
|
502
603
|
function pathBetweenComponentMembers(index: ProjectIndex, start: string, end: string, members: Set<string>): string[] | undefined {
|
|
503
604
|
const queue: ComponentPathSearch[] = [{ current: start, path: [start] }];
|
|
504
605
|
const visited = new Set([start]);
|
|
@@ -521,31 +622,52 @@ function pathBetweenComponentMembers(index: ProjectIndex, start: string, end: st
|
|
|
521
622
|
return undefined;
|
|
522
623
|
}
|
|
523
624
|
|
|
524
|
-
|
|
525
|
-
|
|
625
|
+
/**
|
|
626
|
+
* Determines whether a path qualifies for production-only rules by excluding tests, declarations, fixtures, and slash-delimited `generated` segments.
|
|
627
|
+
*
|
|
628
|
+
* @param path - normalized display path to classify
|
|
629
|
+
* @returns True when `path` counts as production source code, otherwise false.
|
|
630
|
+
*/
|
|
526
631
|
export function isProductionSourcePath(path: string): boolean {
|
|
527
632
|
return !isTestPath(path) && !isDeclarationPath(path) && !isFixtureLikePath(path) && !path.split("/").includes("generated");
|
|
528
633
|
}
|
|
529
634
|
|
|
530
|
-
|
|
531
|
-
|
|
635
|
+
/**
|
|
636
|
+
* Classifies test paths because the production-source filter relies on this check to decide which files count as production code.
|
|
637
|
+
*
|
|
638
|
+
* @param path - normalized display path to inspect
|
|
639
|
+
* @returns True for paths under `__tests__`, `test`, `tests`, or `spec`, or filenames with `.test` or `.spec` before a JS/TS extension.
|
|
640
|
+
*/
|
|
532
641
|
export function isTestPath(path: string): boolean {
|
|
533
642
|
return /(?:^|\/)(?:__tests__|tests?|spec)\//.test(path) || /\.(?:test|spec)\.[cm]?[tj]sx?$/.test(path);
|
|
534
643
|
}
|
|
535
644
|
|
|
536
|
-
|
|
645
|
+
/**
|
|
646
|
+
* Identifies TypeScript declaration files so rule filters can exclude them from production source metrics.
|
|
647
|
+
*
|
|
648
|
+
* @param path - display path to inspect
|
|
649
|
+
* @returns True when `path` ends with `.d.ts`, `.d.cts`, or `.d.mts`.
|
|
650
|
+
*/
|
|
537
651
|
export function isDeclarationPath(path: string): boolean {
|
|
538
652
|
return /\.d\.[cm]?ts$/.test(path);
|
|
539
653
|
}
|
|
540
654
|
|
|
541
|
-
|
|
542
|
-
|
|
655
|
+
/**
|
|
656
|
+
* Identifies fixture-like directories because the production-source filter excludes them and `docs.fixture-purpose-missing` checks them.
|
|
657
|
+
*
|
|
658
|
+
* @param path - normalized display path to inspect
|
|
659
|
+
* @returns True for slash-separated paths under `__fixtures__`, `fixture`, `fixtures`, or `testdata`.
|
|
660
|
+
*/
|
|
543
661
|
export function isFixtureLikePath(path: string): boolean {
|
|
544
662
|
return /(?:^|\/)(?:__fixtures__|fixtures?|testdata)\//.test(path);
|
|
545
663
|
}
|
|
546
664
|
|
|
547
|
-
|
|
548
|
-
|
|
665
|
+
/**
|
|
666
|
+
* Converts platform-native paths to the POSIX-style report shape used in every `Finding`; must be idempotent across repeated calls.
|
|
667
|
+
*
|
|
668
|
+
* @param path - raw file or relative path string to normalize
|
|
669
|
+
* @returns Forward-slash path with any leading `./` prefix stripped.
|
|
670
|
+
*/
|
|
549
671
|
function normalizeDisplayPath(path: string): string {
|
|
550
672
|
return path.replaceAll("\\", "/").replace(/^\.\//, "");
|
|
551
673
|
}
|