@swayamkothari/codepulse 0.0.0-stage → 0.1.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/README.md +240 -2
- package/bin/codepulse.js +6 -0
- package/package.json +60 -4
- package/src/analyzers/complexity/cognitive.js +170 -0
- package/src/analyzers/complexity/cyclomatic.js +96 -0
- package/src/analyzers/complexity/index.js +232 -0
- package/src/analyzers/dependencies/cycle-detector.js +107 -0
- package/src/analyzers/dependencies/graph-builder.js +118 -0
- package/src/analyzers/dependencies/import-extractor.js +85 -0
- package/src/analyzers/dependencies/index.js +152 -0
- package/src/analyzers/duplication/index.js +366 -0
- package/src/analyzers/duplication/normalizer.js +238 -0
- package/src/analyzers/index.js +9 -0
- package/src/analyzers/smells/index.js +213 -0
- package/src/cli/argument-parser.js +45 -0
- package/src/cli/commands/analyze.js +146 -0
- package/src/cli/commands/compare.js +121 -0
- package/src/cli/commands/history.js +91 -0
- package/src/cli/commands/init.js +51 -0
- package/src/cli/commands/rules.js +110 -0
- package/src/config/loader.js +142 -0
- package/src/config/validator.js +130 -0
- package/src/core/analyzer.js +198 -0
- package/src/core/file-filter.js +95 -0
- package/src/core/project-scanner.js +119 -0
- package/src/history/comparison-engine.js +86 -0
- package/src/history/snapshot-manager.js +190 -0
- package/src/index.js +16 -0
- package/src/reporters/html.js +313 -0
- package/src/reporters/json.js +45 -0
- package/src/reporters/terminal.js +197 -0
- package/src/rules/defaults.js +145 -0
- package/src/rules/registry.js +75 -0
- package/src/scoring/score-calculator.js +299 -0
- package/src/scoring/weights.js +53 -0
- package/src/utils/ast-utils.js +173 -0
- package/src/utils/file-utils.js +64 -0
- package/src/utils/logger.js +54 -0
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Complexity Analyzer
|
|
3
|
+
*
|
|
4
|
+
* Measures per-function:
|
|
5
|
+
* • Cyclomatic complexity
|
|
6
|
+
* • Cognitive complexity
|
|
7
|
+
* • Maximum nesting depth
|
|
8
|
+
* • Parameter count
|
|
9
|
+
* • Function length (lines)
|
|
10
|
+
*
|
|
11
|
+
* Emits findings for any metric that exceeds its configured threshold.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { walkAST, getLine, getColumn, getFunctionName, isFunctionNode, nodeLength } from '../../utils/ast-utils.js';
|
|
15
|
+
import { getRule } from '../../rules/registry.js';
|
|
16
|
+
import { registerDefaultRules } from '../../rules/defaults.js';
|
|
17
|
+
import { computeCyclomatic } from './cyclomatic.js';
|
|
18
|
+
import { computeCognitive } from './cognitive.js';
|
|
19
|
+
|
|
20
|
+
export const name = 'complexity';
|
|
21
|
+
|
|
22
|
+
// ── Helpers ────────────────────────────────────────────────────────────────
|
|
23
|
+
|
|
24
|
+
const SKIP_KEYS = new Set([
|
|
25
|
+
'type', 'loc', 'start', 'end', 'extra',
|
|
26
|
+
'innerComments', 'leadingComments', 'trailingComments',
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
const NESTING_NODES = new Set([
|
|
30
|
+
'IfStatement', 'ForStatement', 'ForInStatement', 'ForOfStatement',
|
|
31
|
+
'WhileStatement', 'DoWhileStatement', 'SwitchStatement',
|
|
32
|
+
'TryStatement', 'CatchClause',
|
|
33
|
+
]);
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Collect every function node in the file, along with its parent node.
|
|
37
|
+
* We use Babel traverse so we get reliable parent references.
|
|
38
|
+
*/
|
|
39
|
+
function collectFunctions(ast) {
|
|
40
|
+
const functions = [];
|
|
41
|
+
walkAST(ast, {
|
|
42
|
+
FunctionDeclaration(path) {
|
|
43
|
+
functions.push({ node: path.node, parent: path.parent });
|
|
44
|
+
},
|
|
45
|
+
FunctionExpression(path) {
|
|
46
|
+
functions.push({ node: path.node, parent: path.parent });
|
|
47
|
+
},
|
|
48
|
+
ArrowFunctionExpression(path) {
|
|
49
|
+
functions.push({ node: path.node, parent: path.parent });
|
|
50
|
+
},
|
|
51
|
+
ObjectMethod(path) {
|
|
52
|
+
functions.push({ node: path.node, parent: path.parent });
|
|
53
|
+
},
|
|
54
|
+
ClassMethod(path) {
|
|
55
|
+
functions.push({ node: path.node, parent: path.parent });
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
return functions;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Compute the maximum nesting depth inside a function body,
|
|
63
|
+
* without descending into nested function definitions.
|
|
64
|
+
*/
|
|
65
|
+
function computeMaxNesting(funcNode) {
|
|
66
|
+
let maxDepth = 0;
|
|
67
|
+
|
|
68
|
+
function walk(node, depth) {
|
|
69
|
+
if (!node || typeof node !== 'object') return;
|
|
70
|
+
if (Array.isArray(node)) { for (const n of node) walk(n, depth); return; }
|
|
71
|
+
if (!node.type) return;
|
|
72
|
+
// Skip nested functions
|
|
73
|
+
if (node !== funcNode && isFunctionNode(node)) return;
|
|
74
|
+
|
|
75
|
+
const nextDepth = NESTING_NODES.has(node.type) ? depth + 1 : depth;
|
|
76
|
+
if (nextDepth > maxDepth) maxDepth = nextDepth;
|
|
77
|
+
|
|
78
|
+
for (const key of Object.keys(node)) {
|
|
79
|
+
if (SKIP_KEYS.has(key)) continue;
|
|
80
|
+
walk(node[key], nextDepth);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const body = funcNode.body ?? funcNode;
|
|
85
|
+
walk(body, 0);
|
|
86
|
+
return maxDepth;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Return the number of declared parameters, counting rest params as 1. */
|
|
90
|
+
function countParams(funcNode) {
|
|
91
|
+
return funcNode.params?.length ?? 0;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ── Finding factories ──────────────────────────────────────────────────────
|
|
95
|
+
|
|
96
|
+
function cyclomaticFinding(fileResult, funcName, line, col, value, threshold, severity) {
|
|
97
|
+
return {
|
|
98
|
+
ruleId: 'complexity/cyclomatic',
|
|
99
|
+
severity,
|
|
100
|
+
filePath: fileResult.path,
|
|
101
|
+
line,
|
|
102
|
+
column: col,
|
|
103
|
+
message: `Function "${funcName}" has cyclomatic complexity ${value} (threshold: ${threshold})`,
|
|
104
|
+
why: 'High cyclomatic complexity means more independent execution paths — each path is a potential test case you have to cover.',
|
|
105
|
+
suggestion: `Decompose "${funcName}" into smaller focused functions, each doing one thing. Extract complex conditionals into named predicates.`,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function cognitiveFinding(fileResult, funcName, line, col, value, threshold, severity) {
|
|
110
|
+
return {
|
|
111
|
+
ruleId: 'complexity/cognitive',
|
|
112
|
+
severity,
|
|
113
|
+
filePath: fileResult.path,
|
|
114
|
+
line,
|
|
115
|
+
column: col,
|
|
116
|
+
message: `Function "${funcName}" has cognitive complexity ${value} (threshold: ${threshold})`,
|
|
117
|
+
why: 'Cognitive complexity captures how hard code is to understand — deeply nested and highly branched functions are significantly harder to reason about.',
|
|
118
|
+
suggestion: `Flatten "${funcName}" by extracting nested blocks, inverting guard conditions, or splitting into separate helper functions.`,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function nestingFinding(fileResult, funcName, line, col, value, threshold, severity) {
|
|
123
|
+
return {
|
|
124
|
+
ruleId: 'complexity/nesting-depth',
|
|
125
|
+
severity,
|
|
126
|
+
filePath: fileResult.path,
|
|
127
|
+
line,
|
|
128
|
+
column: col,
|
|
129
|
+
message: `Function "${funcName}" has nesting depth ${value} (threshold: ${threshold})`,
|
|
130
|
+
why: 'Deep nesting forces readers to track multiple context levels simultaneously, dramatically increasing cognitive load.',
|
|
131
|
+
suggestion: 'Extract inner blocks into named functions, use early-return guard clauses, or flatten with async/await patterns.',
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function paramsFinding(fileResult, funcName, line, col, value, threshold, severity) {
|
|
136
|
+
return {
|
|
137
|
+
ruleId: 'complexity/parameters',
|
|
138
|
+
severity,
|
|
139
|
+
filePath: fileResult.path,
|
|
140
|
+
line,
|
|
141
|
+
column: col,
|
|
142
|
+
message: `Function "${funcName}" has ${value} parameters (threshold: ${threshold})`,
|
|
143
|
+
why: 'Functions with many parameters are harder to call correctly, harder to remember, and often indicate the function does too many things.',
|
|
144
|
+
suggestion: 'Group related parameters into an options object, or split the function into smaller functions that each accept fewer inputs.',
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function lengthFinding(fileResult, funcName, line, col, value, threshold, severity) {
|
|
149
|
+
return {
|
|
150
|
+
ruleId: 'complexity/function-length',
|
|
151
|
+
severity,
|
|
152
|
+
filePath: fileResult.path,
|
|
153
|
+
line,
|
|
154
|
+
column: col,
|
|
155
|
+
message: `Function "${funcName}" is ${value} lines long (threshold: ${threshold})`,
|
|
156
|
+
why: 'Very long functions are hard to read in full, hard to test exhaustively, and usually indicate multiple responsibilities.',
|
|
157
|
+
suggestion: `Split "${funcName}" into smaller helpers. A good function should fit on one screen without scrolling.`,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// ── Analyzer entry point ───────────────────────────────────────────────────
|
|
162
|
+
|
|
163
|
+
export async function analyze(fileResults, config) {
|
|
164
|
+
registerDefaultRules();
|
|
165
|
+
const findings = [];
|
|
166
|
+
|
|
167
|
+
// Pull thresholds from the registry (honours user config overrides)
|
|
168
|
+
const cyclomaticRule = getRule('complexity/cyclomatic');
|
|
169
|
+
const cognitiveRule = getRule('complexity/cognitive');
|
|
170
|
+
const nestingRule = getRule('complexity/nesting-depth');
|
|
171
|
+
const paramsRule = getRule('complexity/parameters');
|
|
172
|
+
const lengthRule = getRule('complexity/function-length');
|
|
173
|
+
|
|
174
|
+
const cyclomaticThreshold = config?.thresholds?.cyclomaticComplexity ?? cyclomaticRule?.defaultOptions?.threshold ?? 10;
|
|
175
|
+
const cognitiveThreshold = config?.thresholds?.cognitiveComplexity ?? cognitiveRule?.defaultOptions?.threshold ?? 15;
|
|
176
|
+
const nestingThreshold = config?.thresholds?.nestingDepth ?? nestingRule?.defaultOptions?.threshold ?? 4;
|
|
177
|
+
const paramsThreshold = config?.thresholds?.maxParams ?? paramsRule?.defaultOptions?.threshold ?? 5;
|
|
178
|
+
const lengthThreshold = config?.thresholds?.functionLength ?? lengthRule?.defaultOptions?.threshold ?? 50;
|
|
179
|
+
|
|
180
|
+
for (const fileResult of fileResults) {
|
|
181
|
+
if (!fileResult.ast || fileResult.error) continue;
|
|
182
|
+
|
|
183
|
+
const fns = collectFunctions(fileResult.ast);
|
|
184
|
+
const fnMetrics = [];
|
|
185
|
+
|
|
186
|
+
for (const { node, parent } of fns) {
|
|
187
|
+
const funcName = getFunctionName(node, parent);
|
|
188
|
+
const line = getLine(node);
|
|
189
|
+
const col = getColumn(node);
|
|
190
|
+
const length = nodeLength(node);
|
|
191
|
+
const params = countParams(node);
|
|
192
|
+
const cyclo = computeCyclomatic(node);
|
|
193
|
+
const cogni = computeCognitive(node);
|
|
194
|
+
const nesting = computeMaxNesting(node);
|
|
195
|
+
|
|
196
|
+
// Store per-function metrics on the fileResult for the scoring engine
|
|
197
|
+
fnMetrics.push({ name: funcName, line, cyclomatic: cyclo, cognitive: cogni, nesting, params, length });
|
|
198
|
+
|
|
199
|
+
// Emit findings that breach thresholds
|
|
200
|
+
if (cyclomaticRule?.enabled !== false && cyclo > cyclomaticThreshold) {
|
|
201
|
+
findings.push(cyclomaticFinding(fileResult, funcName, line, col, cyclo, cyclomaticThreshold, cyclomaticRule.severity));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (cognitiveRule?.enabled !== false && cogni > cognitiveThreshold) {
|
|
205
|
+
findings.push(cognitiveFinding(fileResult, funcName, line, col, cogni, cognitiveThreshold, cognitiveRule.severity));
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
if (nestingRule?.enabled !== false && nesting > nestingThreshold) {
|
|
209
|
+
findings.push(nestingFinding(fileResult, funcName, line, col, nesting, nestingThreshold, nestingRule.severity));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (paramsRule?.enabled !== false && params > paramsThreshold) {
|
|
213
|
+
findings.push(paramsFinding(fileResult, funcName, line, col, params, paramsThreshold, paramsRule.severity));
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (lengthRule?.enabled !== false && length > lengthThreshold) {
|
|
217
|
+
findings.push(lengthFinding(fileResult, funcName, line, col, length, lengthThreshold, lengthRule.severity));
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Attach aggregated metrics to the file result
|
|
222
|
+
fileResult.metrics.functions = fnMetrics;
|
|
223
|
+
fileResult.metrics.functionCount = fnMetrics.length;
|
|
224
|
+
if (fnMetrics.length > 0) {
|
|
225
|
+
fileResult.metrics.maxCyclomatic = Math.max(...fnMetrics.map(f => f.cyclomatic));
|
|
226
|
+
fileResult.metrics.avgCyclomatic = +(fnMetrics.reduce((s, f) => s + f.cyclomatic, 0) / fnMetrics.length).toFixed(2);
|
|
227
|
+
fileResult.metrics.maxNesting = Math.max(...fnMetrics.map(f => f.nesting));
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return findings;
|
|
232
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cycle Detector
|
|
3
|
+
*
|
|
4
|
+
* Uses iterative DFS with an explicit recursion stack to find all simple
|
|
5
|
+
* cycles in a directed dependency graph.
|
|
6
|
+
*
|
|
7
|
+
* A "simple cycle" is a cycle where no node appears twice in the path.
|
|
8
|
+
* Each unique cycle is reported exactly once — regardless of which node
|
|
9
|
+
* is used as the starting point — by normalising every cycle to start
|
|
10
|
+
* with its lexicographically smallest member.
|
|
11
|
+
*
|
|
12
|
+
* Result:
|
|
13
|
+
* Array of cycle paths, e.g.:
|
|
14
|
+
* [ ['/src/a.js', '/src/b.js', '/src/c.js'] ]
|
|
15
|
+
* meaning: a → b → c → a
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Detect all unique simple cycles in a directed graph.
|
|
20
|
+
*
|
|
21
|
+
* @param {Map<string, Set<string>>} graph — adjacency map (node → Set of neighbours)
|
|
22
|
+
* @returns {string[][]} — array of cycle paths (each path excludes the repeated start node)
|
|
23
|
+
*/
|
|
24
|
+
export function detectCycles(graph) {
|
|
25
|
+
// Node colours: 0 = unvisited, 1 = on current stack, 2 = fully processed
|
|
26
|
+
const color = new Map();
|
|
27
|
+
const parent = new Map();
|
|
28
|
+
|
|
29
|
+
for (const node of graph.keys()) color.set(node, 0);
|
|
30
|
+
|
|
31
|
+
const rawCycles = [];
|
|
32
|
+
|
|
33
|
+
function dfs(node, path) {
|
|
34
|
+
color.set(node, 1);
|
|
35
|
+
path.push(node);
|
|
36
|
+
|
|
37
|
+
for (const neighbour of graph.get(node) ?? []) {
|
|
38
|
+
if (!color.has(neighbour)) continue; // edge to unanalysed node
|
|
39
|
+
|
|
40
|
+
if (color.get(neighbour) === 1) {
|
|
41
|
+
// Back edge → cycle found. Extract from path.
|
|
42
|
+
const cycleStart = path.indexOf(neighbour);
|
|
43
|
+
if (cycleStart !== -1) {
|
|
44
|
+
rawCycles.push(path.slice(cycleStart));
|
|
45
|
+
}
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (color.get(neighbour) === 0) {
|
|
50
|
+
dfs(neighbour, path);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
path.pop();
|
|
55
|
+
color.set(node, 2);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
for (const node of graph.keys()) {
|
|
59
|
+
if (color.get(node) === 0) {
|
|
60
|
+
dfs(node, []);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Deduplicate: normalise each cycle by rotating to start at its
|
|
65
|
+
// lexicographically smallest element, then stringify for uniqueness.
|
|
66
|
+
const seen = new Set();
|
|
67
|
+
const unique = [];
|
|
68
|
+
|
|
69
|
+
for (const cycle of rawCycles) {
|
|
70
|
+
const canonical = _canonicalize(cycle);
|
|
71
|
+
const key = canonical.join('→');
|
|
72
|
+
if (!seen.has(key)) {
|
|
73
|
+
seen.add(key);
|
|
74
|
+
unique.push(canonical);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return unique;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Rotate a cycle array so it starts at the lexicographically smallest element.
|
|
83
|
+
*/
|
|
84
|
+
function _canonicalize(cycle) {
|
|
85
|
+
if (cycle.length === 0) return cycle;
|
|
86
|
+
let minIdx = 0;
|
|
87
|
+
for (let i = 1; i < cycle.length; i++) {
|
|
88
|
+
if (cycle[i] < cycle[minIdx]) minIdx = i;
|
|
89
|
+
}
|
|
90
|
+
return [...cycle.slice(minIdx), ...cycle.slice(0, minIdx)];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Build a human-readable label for a cycle path, using short relative names.
|
|
95
|
+
*
|
|
96
|
+
* @param {string[]} cycle — absolute file paths
|
|
97
|
+
* @param {string} rootDir — project root for path shortening
|
|
98
|
+
* @returns {string} — e.g. "a.js → b.js → c.js → a.js"
|
|
99
|
+
*/
|
|
100
|
+
export function formatCycle(cycle, rootDir) {
|
|
101
|
+
const shorten = (p) => {
|
|
102
|
+
const rel = p.startsWith(rootDir) ? p.slice(rootDir.length + 1) : p;
|
|
103
|
+
return rel;
|
|
104
|
+
};
|
|
105
|
+
const labels = cycle.map(shorten);
|
|
106
|
+
return [...labels, labels[0]].join(' → ');
|
|
107
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dependency Graph Builder
|
|
3
|
+
*
|
|
4
|
+
* Resolves raw import specifiers to absolute file paths, then builds:
|
|
5
|
+
* • graph — Map<filePath, Set<filePath>> (outgoing edges)
|
|
6
|
+
* • reverseGraph — Map<filePath, Set<filePath>> (incoming edges)
|
|
7
|
+
*
|
|
8
|
+
* Resolution order for a specifier like './utils' from '/src/api/handler.js':
|
|
9
|
+
* 1. /src/api/utils (as-is, if it has an extension and exists in the set)
|
|
10
|
+
* 2. /src/api/utils.js (direct extension variants)
|
|
11
|
+
* 3. /src/api/utils.mjs
|
|
12
|
+
* 4. /src/api/utils.cjs
|
|
13
|
+
* 5. /src/api/utils.jsx
|
|
14
|
+
* 6. /src/api/utils/index.js (index file variants)
|
|
15
|
+
* 7. /src/api/utils/index.mjs
|
|
16
|
+
* 8. /src/api/utils/index.cjs
|
|
17
|
+
* 9. /src/api/utils/index.jsx
|
|
18
|
+
*
|
|
19
|
+
* Only paths present in the `analyzedFileSet` are returned; unresolvable
|
|
20
|
+
* or external specifiers produce `null` and are excluded from the graph.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
|
|
25
|
+
const EXTENSIONS = ['.js', '.mjs', '.cjs', '.jsx'];
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Try to resolve an import specifier to one of the analyzed files.
|
|
29
|
+
*
|
|
30
|
+
* @param {string} source — raw specifier (e.g. './utils')
|
|
31
|
+
* @param {string} fromFile — absolute path of the importing file
|
|
32
|
+
* @param {Set<string>} analyzedFileSet — set of all absolute paths being analyzed
|
|
33
|
+
* @returns {string|null}
|
|
34
|
+
*/
|
|
35
|
+
export function resolveImport(source, fromFile, analyzedFileSet) {
|
|
36
|
+
if (!source.startsWith('.')) return null; // not a relative import
|
|
37
|
+
|
|
38
|
+
const dir = path.dirname(fromFile);
|
|
39
|
+
const absBase = path.resolve(dir, source);
|
|
40
|
+
|
|
41
|
+
// 1. As-is (source already includes an extension)
|
|
42
|
+
if (analyzedFileSet.has(absBase)) return absBase;
|
|
43
|
+
|
|
44
|
+
// 2. Direct extension variants
|
|
45
|
+
for (const ext of EXTENSIONS) {
|
|
46
|
+
const candidate = absBase + ext;
|
|
47
|
+
if (analyzedFileSet.has(candidate)) return candidate;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// 3. Index file variants
|
|
51
|
+
for (const ext of EXTENSIONS) {
|
|
52
|
+
const candidate = path.join(absBase, 'index' + ext);
|
|
53
|
+
if (analyzedFileSet.has(candidate)) return candidate;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Build a bidirectional dependency graph from already-extracted imports.
|
|
61
|
+
*
|
|
62
|
+
* Each fileResult must have a `.rawImports` array (from import-extractor).
|
|
63
|
+
*
|
|
64
|
+
* @param {object[]} fileResults — analyzer file result objects
|
|
65
|
+
* @param {Set<string>} analyzedFileSet — set of all analyzed file paths
|
|
66
|
+
* @returns {{ graph: Map, reverseGraph: Map, edges: object[] }}
|
|
67
|
+
*/
|
|
68
|
+
export function buildDependencyGraph(fileResults, analyzedFileSet) {
|
|
69
|
+
/** @type {Map<string, Set<string>>} */
|
|
70
|
+
const graph = new Map();
|
|
71
|
+
/** @type {Map<string, Set<string>>} */
|
|
72
|
+
const reverseGraph = new Map();
|
|
73
|
+
/** @type {Array<{from: string, to: string, kind: string, line: number}>} */
|
|
74
|
+
const edges = [];
|
|
75
|
+
|
|
76
|
+
// Initialise every node so isolated files appear in the graph
|
|
77
|
+
for (const { path: fp } of fileResults) {
|
|
78
|
+
if (!graph.has(fp)) graph.set(fp, new Set());
|
|
79
|
+
if (!reverseGraph.has(fp)) reverseGraph.set(fp, new Set());
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Add edges
|
|
83
|
+
for (const fileResult of fileResults) {
|
|
84
|
+
const from = fileResult.path;
|
|
85
|
+
for (const imp of fileResult.rawImports ?? []) {
|
|
86
|
+
const to = resolveImport(imp.source, from, analyzedFileSet);
|
|
87
|
+
if (!to) continue; // unresolvable or external
|
|
88
|
+
if (to === from) continue; // self-import (unusual but possible)
|
|
89
|
+
|
|
90
|
+
graph.get(from).add(to);
|
|
91
|
+
if (!reverseGraph.has(to)) reverseGraph.set(to, new Set());
|
|
92
|
+
reverseGraph.get(to).add(from);
|
|
93
|
+
|
|
94
|
+
edges.push({ from, to, kind: imp.kind, line: imp.line });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return { graph, reverseGraph, edges };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Compute per-file metrics from the dependency graph.
|
|
103
|
+
*
|
|
104
|
+
* @returns {Map<string, { inDegree, outDegree, fanIn, fanOut }>}
|
|
105
|
+
*/
|
|
106
|
+
export function computeGraphMetrics(graph, reverseGraph) {
|
|
107
|
+
const metrics = new Map();
|
|
108
|
+
|
|
109
|
+
for (const [file, deps] of graph) {
|
|
110
|
+
const inbound = reverseGraph.get(file) ?? new Set();
|
|
111
|
+
metrics.set(file, {
|
|
112
|
+
outDegree: deps.size, // how many files this one imports
|
|
113
|
+
inDegree: inbound.size, // how many files import this one
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return metrics;
|
|
118
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Import Extractor
|
|
3
|
+
*
|
|
4
|
+
* Collects every local import/require from a file's AST.
|
|
5
|
+
* Handles:
|
|
6
|
+
* • ES module static imports: import foo from './foo'
|
|
7
|
+
* • ES module dynamic imports: import('./foo')
|
|
8
|
+
* • CommonJS require: require('./foo')
|
|
9
|
+
* • require.resolve: require.resolve('./foo')
|
|
10
|
+
*
|
|
11
|
+
* Only LOCAL specifiers (starting with '.') are returned.
|
|
12
|
+
* Node built-ins and npm packages are intentionally ignored since they
|
|
13
|
+
* don't form part of the project's internal dependency graph.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { walkAST, getLine } from '../../utils/ast-utils.js';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @typedef {object} RawImport
|
|
20
|
+
* @property {string} source — the raw specifier as written in source (e.g. './utils')
|
|
21
|
+
* @property {string} kind — 'static' | 'dynamic' | 'require'
|
|
22
|
+
* @property {number} line — source line number
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Extract all local imports from a file's AST.
|
|
27
|
+
* @param {object} ast — Babel File node
|
|
28
|
+
* @param {string} filePath — absolute path of the containing file (unused here, kept for symmetry)
|
|
29
|
+
* @returns {RawImport[]}
|
|
30
|
+
*/
|
|
31
|
+
export function extractImports(ast, _filePath) {
|
|
32
|
+
if (!ast) return [];
|
|
33
|
+
const imports = [];
|
|
34
|
+
|
|
35
|
+
walkAST(ast, {
|
|
36
|
+
// import foo from './foo'
|
|
37
|
+
// import { a, b } from '../lib'
|
|
38
|
+
// import * as ns from './ns'
|
|
39
|
+
ImportDeclaration(path) {
|
|
40
|
+
const source = path.node.source?.value;
|
|
41
|
+
if (source && isLocal(source)) {
|
|
42
|
+
imports.push({ source, kind: 'static', line: getLine(path.node) });
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
|
|
46
|
+
CallExpression(path) {
|
|
47
|
+
const { callee, arguments: args } = path.node;
|
|
48
|
+
const firstArg = args?.[0];
|
|
49
|
+
if (!firstArg || firstArg.type !== 'StringLiteral') return;
|
|
50
|
+
|
|
51
|
+
// require('./foo')
|
|
52
|
+
if (callee.type === 'Identifier' && callee.name === 'require') {
|
|
53
|
+
if (isLocal(firstArg.value)) {
|
|
54
|
+
imports.push({ source: firstArg.value, kind: 'require', line: getLine(path.node) });
|
|
55
|
+
}
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// require.resolve('./foo')
|
|
60
|
+
if (
|
|
61
|
+
callee.type === 'MemberExpression' &&
|
|
62
|
+
callee.object?.name === 'require' &&
|
|
63
|
+
callee.property?.name === 'resolve'
|
|
64
|
+
) {
|
|
65
|
+
if (isLocal(firstArg.value)) {
|
|
66
|
+
imports.push({ source: firstArg.value, kind: 'require', line: getLine(path.node) });
|
|
67
|
+
}
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// import('./foo') — callee.type === 'Import'
|
|
72
|
+
if (callee.type === 'Import') {
|
|
73
|
+
if (isLocal(firstArg.value)) {
|
|
74
|
+
imports.push({ source: firstArg.value, kind: 'dynamic', line: getLine(path.node) });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
return imports;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function isLocal(source) {
|
|
84
|
+
return source.startsWith('./') || source.startsWith('../');
|
|
85
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dependency Analyzer
|
|
3
|
+
*
|
|
4
|
+
* Builds the full project dependency graph, then detects:
|
|
5
|
+
* • Circular dependencies (dependency/circular)
|
|
6
|
+
* • Files with too many imports (dependency/too-many-imports)
|
|
7
|
+
*
|
|
8
|
+
* Also attaches graph metrics (in-degree, out-degree, cycle membership) to
|
|
9
|
+
* each fileResult for use by the scoring engine.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { getRule } from '../../rules/registry.js';
|
|
14
|
+
import { registerDefaultRules } from '../../rules/defaults.js';
|
|
15
|
+
import { extractImports } from './import-extractor.js';
|
|
16
|
+
import { buildDependencyGraph, computeGraphMetrics } from './graph-builder.js';
|
|
17
|
+
import { detectCycles, formatCycle } from './cycle-detector.js';
|
|
18
|
+
|
|
19
|
+
export const name = 'dependencies';
|
|
20
|
+
|
|
21
|
+
// ── Finding factories ──────────────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
function circularFinding(filePath, cycle, rootDir, severity) {
|
|
24
|
+
const label = formatCycle(cycle, rootDir);
|
|
25
|
+
return {
|
|
26
|
+
ruleId: 'dependency/circular',
|
|
27
|
+
severity,
|
|
28
|
+
filePath,
|
|
29
|
+
line: 1,
|
|
30
|
+
column: 0,
|
|
31
|
+
message: `Circular dependency: ${label}`,
|
|
32
|
+
why: 'Circular imports can cause module initialisation failures (undefined values on first load) and tightly couple otherwise unrelated files, making refactoring painful.',
|
|
33
|
+
suggestion: 'Extract the shared logic into a third module that neither participant imports, breaking the cycle.',
|
|
34
|
+
metadata: { cycle },
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function tooManyImportsFinding(filePath, count, threshold, severity) {
|
|
39
|
+
return {
|
|
40
|
+
ruleId: 'dependency/too-many-imports',
|
|
41
|
+
severity,
|
|
42
|
+
filePath,
|
|
43
|
+
line: 1,
|
|
44
|
+
column: 0,
|
|
45
|
+
message: `File imports ${count} local modules (threshold: ${threshold})`,
|
|
46
|
+
why: 'Files that depend on many others often have too many responsibilities and become difficult to understand in isolation.',
|
|
47
|
+
suggestion: 'Consider grouping related imports behind a facade module, or splitting this file into focused sub-modules.',
|
|
48
|
+
metadata: { importCount: count },
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// ── Analyzer entry point ───────────────────────────────────────────────────
|
|
53
|
+
|
|
54
|
+
export async function analyze(fileResults, config) {
|
|
55
|
+
registerDefaultRules();
|
|
56
|
+
const findings = [];
|
|
57
|
+
|
|
58
|
+
const circularRule = getRule('dependency/circular');
|
|
59
|
+
const tooManyRule = getRule('dependency/too-many-imports');
|
|
60
|
+
|
|
61
|
+
const tooManyThreshold = config?.thresholds?.maxImports ?? tooManyRule?.defaultOptions?.threshold ?? 15;
|
|
62
|
+
|
|
63
|
+
// ── 1. Extract raw imports from every parsed file ──────────────────────
|
|
64
|
+
for (const fileResult of fileResults) {
|
|
65
|
+
if (!fileResult.ast || fileResult.error) {
|
|
66
|
+
fileResult.rawImports = [];
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
fileResult.rawImports = extractImports(fileResult.ast, fileResult.path);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ── 2. Build dependency graph ──────────────────────────────────────────
|
|
73
|
+
const analyzedFileSet = new Set(fileResults.map(f => f.path));
|
|
74
|
+
const { graph, reverseGraph, edges } = buildDependencyGraph(fileResults, analyzedFileSet);
|
|
75
|
+
const metrics = computeGraphMetrics(graph, reverseGraph);
|
|
76
|
+
|
|
77
|
+
// ── 3. Detect cycles ───────────────────────────────────────────────────
|
|
78
|
+
if (circularRule?.enabled !== false) {
|
|
79
|
+
const cycles = detectCycles(graph);
|
|
80
|
+
const rootDir = _inferRootDir(fileResults);
|
|
81
|
+
|
|
82
|
+
// Track which files are part of a cycle (for metrics)
|
|
83
|
+
const cycleMembers = new Set(cycles.flat());
|
|
84
|
+
|
|
85
|
+
for (const cycle of cycles) {
|
|
86
|
+
// Report the finding once, anchored to the first file in the cycle
|
|
87
|
+
const firstFile = cycle[0];
|
|
88
|
+
const fileResult = fileResults.find(f => f.path === firstFile);
|
|
89
|
+
if (fileResult) {
|
|
90
|
+
findings.push(circularFinding(firstFile, cycle, rootDir, circularRule.severity));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Attach to metrics
|
|
95
|
+
for (const fileResult of fileResults) {
|
|
96
|
+
if (!fileResult.error) {
|
|
97
|
+
fileResult.metrics.inCycle = cycleMembers.has(fileResult.path);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ── 4. Too many imports ────────────────────────────────────────────────
|
|
103
|
+
if (tooManyRule?.enabled !== false) {
|
|
104
|
+
for (const fileResult of fileResults) {
|
|
105
|
+
if (fileResult.error) continue;
|
|
106
|
+
const localImportCount = (graph.get(fileResult.path) ?? new Set()).size;
|
|
107
|
+
if (localImportCount > tooManyThreshold) {
|
|
108
|
+
findings.push(tooManyImportsFinding(fileResult.path, localImportCount, tooManyThreshold, tooManyRule.severity));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ── 5. Attach per-file dependency metrics ─────────────────────────────
|
|
114
|
+
for (const fileResult of fileResults) {
|
|
115
|
+
if (fileResult.error) continue;
|
|
116
|
+
const m = metrics.get(fileResult.path);
|
|
117
|
+
if (m) {
|
|
118
|
+
fileResult.metrics.outDegree = m.outDegree;
|
|
119
|
+
fileResult.metrics.inDegree = m.inDegree;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ── 6. Attach project-level dependency metrics to each file result ─────
|
|
124
|
+
// (Scoring engine reads these from the first file or from the
|
|
125
|
+
// aggregated result object — attached here for completeness.)
|
|
126
|
+
const totalEdges = edges.length;
|
|
127
|
+
const cycleCount = detectCycles(graph).length; // second call is cheap (same graph)
|
|
128
|
+
|
|
129
|
+
for (const fileResult of fileResults) {
|
|
130
|
+
if (!fileResult.error) {
|
|
131
|
+
fileResult.metrics.totalDependencyEdges = totalEdges;
|
|
132
|
+
fileResult.metrics.cycleCount = cycleCount;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return findings;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ── Helpers ────────────────────────────────────────────────────────────────
|
|
140
|
+
|
|
141
|
+
function _inferRootDir(fileResults) {
|
|
142
|
+
if (fileResults.length === 0) return process.cwd();
|
|
143
|
+
// Find the longest common prefix of all file paths
|
|
144
|
+
const paths = fileResults.map(f => f.path);
|
|
145
|
+
let prefix = path.dirname(paths[0]);
|
|
146
|
+
for (const p of paths) {
|
|
147
|
+
while (!p.startsWith(prefix + path.sep) && prefix !== path.dirname(prefix)) {
|
|
148
|
+
prefix = path.dirname(prefix);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return prefix;
|
|
152
|
+
}
|