@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,366 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Duplication Analyzer
|
|
3
|
+
*
|
|
4
|
+
* Two complementary strategies:
|
|
5
|
+
*
|
|
6
|
+
* 1. Function-level comparison — hash each function's normalized body.
|
|
7
|
+
* Two functions with identical structure (after identifier/literal erasure)
|
|
8
|
+
* are reported as duplicates regardless of their size.
|
|
9
|
+
*
|
|
10
|
+
* 2. Statement-sequence sliding window — for every block of statements in
|
|
11
|
+
* every file, generate windows of `minStatements` consecutive statements,
|
|
12
|
+
* hash their normalized form, and find windows that match across locations.
|
|
13
|
+
* Adjacent matching windows are merged into the largest continuous region.
|
|
14
|
+
*
|
|
15
|
+
* Both strategies use the same AST normalizer, so naming differences alone
|
|
16
|
+
* never cause a false negative.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { walkAST, getLine, getEndLine, getColumn, getFunctionName, isFunctionNode, nodeLength } from '../../utils/ast-utils.js';
|
|
20
|
+
import { getRule } from '../../rules/registry.js';
|
|
21
|
+
import { registerDefaultRules } from '../../rules/defaults.js';
|
|
22
|
+
import { normalizeNode, normalizeStatements } from './normalizer.js';
|
|
23
|
+
|
|
24
|
+
export const name = 'duplication';
|
|
25
|
+
|
|
26
|
+
// ── Statement list extraction ──────────────────────────────────────────────
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Collect all non-trivial statement arrays from a file's AST.
|
|
30
|
+
* Includes the Program body and every BlockStatement body.
|
|
31
|
+
* Skips blocks with fewer than `minStatements` statements.
|
|
32
|
+
*/
|
|
33
|
+
function collectStatementLists(ast, filePath, minStatements) {
|
|
34
|
+
const lists = [];
|
|
35
|
+
|
|
36
|
+
// Program top-level
|
|
37
|
+
if (ast.program?.body?.length >= minStatements) {
|
|
38
|
+
lists.push({ stmts: ast.program.body, filePath });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
walkAST(ast, {
|
|
42
|
+
BlockStatement(path) {
|
|
43
|
+
const { body } = path.node;
|
|
44
|
+
if (body.length >= minStatements) {
|
|
45
|
+
lists.push({ stmts: body, filePath });
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
return lists;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ── Window hash index ──────────────────────────────────────────────────────
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Generate all sliding windows of exactly `windowSize` statements.
|
|
57
|
+
* Returns an array of window descriptors.
|
|
58
|
+
*/
|
|
59
|
+
function generateWindows(stmts, filePath, windowSize) {
|
|
60
|
+
const windows = [];
|
|
61
|
+
for (let start = 0; start <= stmts.length - windowSize; start++) {
|
|
62
|
+
const slice = stmts.slice(start, start + windowSize);
|
|
63
|
+
const startLine = getLine(slice[0]);
|
|
64
|
+
const endLine = getEndLine(slice[slice.length - 1]);
|
|
65
|
+
if (!startLine || !endLine) continue;
|
|
66
|
+
|
|
67
|
+
windows.push({
|
|
68
|
+
filePath,
|
|
69
|
+
stmtIndex: start,
|
|
70
|
+
startLine,
|
|
71
|
+
endLine,
|
|
72
|
+
hash: normalizeStatements(slice),
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return windows;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Find all windows whose normalized hash matches at least one other window
|
|
80
|
+
* in a different location, then merge adjacent consecutive matches into the
|
|
81
|
+
* largest continuous duplicate region.
|
|
82
|
+
*
|
|
83
|
+
* Returns an array of merged duplicate pairs:
|
|
84
|
+
* { fileA, startLineA, endLineA, fileB, startLineB, endLineB, lineCount }
|
|
85
|
+
*/
|
|
86
|
+
function findAndMergeDuplicateWindows(allWindows, minLines) {
|
|
87
|
+
// 1. Build hash → windows index
|
|
88
|
+
const hashIndex = new Map();
|
|
89
|
+
for (const w of allWindows) {
|
|
90
|
+
if (!hashIndex.has(w.hash)) hashIndex.set(w.hash, []);
|
|
91
|
+
hashIndex.get(w.hash).push(w);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// 2. Build quick-lookup: "filePath:stmtIndex" → window
|
|
95
|
+
const windowMap = new Map();
|
|
96
|
+
for (const w of allWindows) {
|
|
97
|
+
windowMap.set(`${w.filePath}:${w.stmtIndex}`, w);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// 3. Collect all matching pairs (a.location ≠ b.location)
|
|
101
|
+
const pairMap = new Map(); // "fileA:idxA|fileB:idxB" → {a, b}
|
|
102
|
+
for (const [, windows] of hashIndex) {
|
|
103
|
+
if (windows.length < 2) continue;
|
|
104
|
+
for (let i = 0; i < windows.length; i++) {
|
|
105
|
+
for (let j = i + 1; j < windows.length; j++) {
|
|
106
|
+
const a = windows[i];
|
|
107
|
+
const b = windows[j];
|
|
108
|
+
// Skip exact same location (same file, same start line)
|
|
109
|
+
if (a.filePath === b.filePath && a.stmtIndex === b.stmtIndex) continue;
|
|
110
|
+
const key = `${a.filePath}:${a.stmtIndex}|${b.filePath}:${b.stmtIndex}`;
|
|
111
|
+
pairMap.set(key, { a, b });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// 4. Find the start of each chain (a pair that is NOT preceded by another match)
|
|
117
|
+
const visitedKeys = new Set();
|
|
118
|
+
const merged = [];
|
|
119
|
+
|
|
120
|
+
for (const [key, { a, b }] of pairMap) {
|
|
121
|
+
if (visitedKeys.has(key)) continue;
|
|
122
|
+
|
|
123
|
+
// Is there a match one step back? If so, this pair is in the middle of a chain.
|
|
124
|
+
const prevKey = `${a.filePath}:${a.stmtIndex - 1}|${b.filePath}:${b.stmtIndex - 1}`;
|
|
125
|
+
if (pairMap.has(prevKey)) continue; // not the chain start
|
|
126
|
+
|
|
127
|
+
// This is the start of a chain — extend forward
|
|
128
|
+
let curA = a;
|
|
129
|
+
let curB = b;
|
|
130
|
+
visitedKeys.add(key);
|
|
131
|
+
|
|
132
|
+
while (true) {
|
|
133
|
+
const nextKey = `${curA.filePath}:${curA.stmtIndex + 1}|${curB.filePath}:${curB.stmtIndex + 1}`;
|
|
134
|
+
const nextPair = pairMap.get(nextKey);
|
|
135
|
+
if (!nextPair) break;
|
|
136
|
+
visitedKeys.add(nextKey);
|
|
137
|
+
curA = nextPair.a;
|
|
138
|
+
curB = nextPair.b;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// The duplicate region spans from the first window's start to the last window's end
|
|
142
|
+
const startLineA = a.startLine;
|
|
143
|
+
const endLineA = curA.endLine;
|
|
144
|
+
const startLineB = b.startLine;
|
|
145
|
+
const endLineB = curB.endLine;
|
|
146
|
+
const lineCount = Math.max(endLineA - startLineA + 1, endLineB - startLineB + 1);
|
|
147
|
+
|
|
148
|
+
if (lineCount < minLines) continue;
|
|
149
|
+
|
|
150
|
+
merged.push({
|
|
151
|
+
fileA: a.filePath, startLineA, endLineA,
|
|
152
|
+
fileB: b.filePath, startLineB, endLineB,
|
|
153
|
+
lineCount,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return merged;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ── Function-level duplicate detection ────────────────────────────────────
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Hash the normalized body of every function.
|
|
164
|
+
* Functions with identical structure (regardless of naming) are duplicates.
|
|
165
|
+
*/
|
|
166
|
+
function findFunctionDuplicates(fileResults, minLines) {
|
|
167
|
+
const bodyIndex = new Map(); // normalizedHash → [{filePath, name, startLine, endLine, lines}]
|
|
168
|
+
|
|
169
|
+
for (const fileResult of fileResults) {
|
|
170
|
+
if (!fileResult.ast) continue;
|
|
171
|
+
|
|
172
|
+
walkAST(fileResult.ast, {
|
|
173
|
+
FunctionDeclaration(path) { _indexFn(path, fileResult.path, bodyIndex, minLines); },
|
|
174
|
+
FunctionExpression(path) { _indexFn(path, fileResult.path, bodyIndex, minLines); },
|
|
175
|
+
ArrowFunctionExpression(path) { _indexFn(path, fileResult.path, bodyIndex, minLines); },
|
|
176
|
+
ObjectMethod(path) { _indexFn(path, fileResult.path, bodyIndex, minLines); },
|
|
177
|
+
ClassMethod(path) { _indexFn(path, fileResult.path, bodyIndex, minLines); },
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const duplicates = [];
|
|
182
|
+
for (const [, locs] of bodyIndex) {
|
|
183
|
+
if (locs.length >= 2) duplicates.push(locs);
|
|
184
|
+
}
|
|
185
|
+
return duplicates;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function _indexFn(path, filePath, bodyIndex, minLines) {
|
|
189
|
+
const lines = nodeLength(path.node);
|
|
190
|
+
if (lines < minLines) return;
|
|
191
|
+
|
|
192
|
+
// Hash only the body, not the function signature (name/params may differ)
|
|
193
|
+
const hash = normalizeNode(path.node.body ?? path.node);
|
|
194
|
+
if (!bodyIndex.has(hash)) bodyIndex.set(hash, []);
|
|
195
|
+
|
|
196
|
+
const name = getFunctionName(path.node, path.parent);
|
|
197
|
+
bodyIndex.get(hash).push({
|
|
198
|
+
filePath,
|
|
199
|
+
name,
|
|
200
|
+
startLine: getLine(path.node),
|
|
201
|
+
endLine: getEndLine(path.node),
|
|
202
|
+
lines,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ── Duplication percentage ─────────────────────────────────────────────────
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Calculate what fraction of total lines in a project are part of a duplicate.
|
|
210
|
+
* This is a rough estimate: we mark all lines covered by any duplicate region.
|
|
211
|
+
*/
|
|
212
|
+
function computeDuplicationPercentage(allDuplicateRegions, fileResults) {
|
|
213
|
+
const totalLines = fileResults.reduce((s, f) => s + (f.lines ?? 0), 0);
|
|
214
|
+
if (totalLines === 0) return 0;
|
|
215
|
+
|
|
216
|
+
// Count unique lines involved in duplicates per file
|
|
217
|
+
const coveredLines = new Map(); // filePath → Set<lineNumber>
|
|
218
|
+
for (const { fileA, startLineA, endLineA, fileB, startLineB, endLineB } of allDuplicateRegions) {
|
|
219
|
+
_markLines(coveredLines, fileA, startLineA, endLineA);
|
|
220
|
+
_markLines(coveredLines, fileB, startLineB, endLineB);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
let duplicatedLines = 0;
|
|
224
|
+
for (const [, lineSet] of coveredLines) {
|
|
225
|
+
duplicatedLines += lineSet.size;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return Math.min(100, Math.round((duplicatedLines / totalLines) * 100));
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function _markLines(map, filePath, start, end) {
|
|
232
|
+
if (!map.has(filePath)) map.set(filePath, new Set());
|
|
233
|
+
const set = map.get(filePath);
|
|
234
|
+
for (let l = start; l <= end; l++) set.add(l);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ── Finding factories ──────────────────────────────────────────────────────
|
|
238
|
+
|
|
239
|
+
function windowDuplicateFinding(fileResult, region, severity) {
|
|
240
|
+
const { fileA, startLineA, endLineA, fileB, startLineB, endLineB, lineCount } = region;
|
|
241
|
+
const isSameFile = fileA === fileB;
|
|
242
|
+
|
|
243
|
+
const otherLocation = isSameFile
|
|
244
|
+
? `same file, line ${startLineB}`
|
|
245
|
+
: `${fileB.replace(process.cwd() + '/', '')}:${startLineB}`;
|
|
246
|
+
|
|
247
|
+
return {
|
|
248
|
+
ruleId: 'duplication/block',
|
|
249
|
+
severity,
|
|
250
|
+
filePath: fileA,
|
|
251
|
+
line: startLineA,
|
|
252
|
+
column: 0,
|
|
253
|
+
message: `Duplicate code block (${lineCount} lines) also found at ${otherLocation}`,
|
|
254
|
+
why: 'Duplicated code means bugs must be fixed in multiple places and logic drift is inevitable. It is a maintenance liability.',
|
|
255
|
+
suggestion: 'Extract the shared logic into a named function or module, then call it from both locations.',
|
|
256
|
+
metadata: {
|
|
257
|
+
duplicate: {
|
|
258
|
+
filePath: fileB,
|
|
259
|
+
startLine: startLineB,
|
|
260
|
+
endLine: endLineB,
|
|
261
|
+
},
|
|
262
|
+
lineCount,
|
|
263
|
+
},
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function functionDuplicateFinding(fileResult, loc, otherLocs, severity) {
|
|
268
|
+
const others = otherLocs
|
|
269
|
+
.map(l => `"${l.name}" at ${l.filePath.replace(process.cwd() + '/', '')}:${l.startLine}`)
|
|
270
|
+
.join(', ');
|
|
271
|
+
|
|
272
|
+
return {
|
|
273
|
+
ruleId: 'duplication/block',
|
|
274
|
+
severity,
|
|
275
|
+
filePath: loc.filePath,
|
|
276
|
+
line: loc.startLine,
|
|
277
|
+
column: 0,
|
|
278
|
+
message: `Function "${loc.name}" (${loc.lines} lines) is structurally identical to: ${others}`,
|
|
279
|
+
why: 'Duplicate functions diverge over time — one gets bugfixes, the other does not.',
|
|
280
|
+
suggestion: `Merge these functions into one and import it where needed. Even if they differ slightly, consider parameterising the difference.`,
|
|
281
|
+
metadata: {
|
|
282
|
+
duplicateFunctions: otherLocs.map(l => ({ filePath: l.filePath, name: l.name, startLine: l.startLine })),
|
|
283
|
+
},
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// ── Analyzer entry point ───────────────────────────────────────────────────
|
|
288
|
+
|
|
289
|
+
export async function analyze(fileResults, config) {
|
|
290
|
+
registerDefaultRules();
|
|
291
|
+
const findings = [];
|
|
292
|
+
|
|
293
|
+
const rule = getRule('duplication/block');
|
|
294
|
+
if (rule?.enabled === false) return findings;
|
|
295
|
+
|
|
296
|
+
const severity = rule?.severity ?? 'medium';
|
|
297
|
+
const minLines = config?.thresholds?.duplicationMinLines ?? rule?.defaultOptions?.minLines ?? 6;
|
|
298
|
+
const minStatements = config?.thresholds?.duplicationMinStatements ?? 4;
|
|
299
|
+
|
|
300
|
+
// ── 1. Statement-sequence detection ───────────────────────────────────
|
|
301
|
+
const allWindows = [];
|
|
302
|
+
for (const fileResult of fileResults) {
|
|
303
|
+
if (!fileResult.ast || fileResult.error) continue;
|
|
304
|
+
const lists = collectStatementLists(fileResult.ast, fileResult.path, minStatements);
|
|
305
|
+
for (const { stmts, filePath } of lists) {
|
|
306
|
+
allWindows.push(...generateWindows(stmts, filePath, minStatements));
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const windowDuplicates = findAndMergeDuplicateWindows(allWindows, minLines);
|
|
311
|
+
|
|
312
|
+
// Track which (fileA, startLineA) pairs we've already reported to avoid
|
|
313
|
+
// reporting both directions of the same pair.
|
|
314
|
+
const reportedPairs = new Set();
|
|
315
|
+
|
|
316
|
+
for (const region of windowDuplicates) {
|
|
317
|
+
const fwdKey = `${region.fileA}:${region.startLineA}|${region.fileB}:${region.startLineB}`;
|
|
318
|
+
const revKey = `${region.fileB}:${region.startLineB}|${region.fileA}:${region.startLineA}`;
|
|
319
|
+
if (reportedPairs.has(fwdKey) || reportedPairs.has(revKey)) continue;
|
|
320
|
+
reportedPairs.add(fwdKey);
|
|
321
|
+
reportedPairs.add(revKey);
|
|
322
|
+
|
|
323
|
+
const fileResult = fileResults.find(f => f.path === region.fileA);
|
|
324
|
+
if (fileResult) findings.push(windowDuplicateFinding(fileResult, region, severity));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// ── 2. Function-level detection ────────────────────────────────────────
|
|
328
|
+
const fnDuplicateGroups = findFunctionDuplicates(fileResults, minLines);
|
|
329
|
+
|
|
330
|
+
for (const group of fnDuplicateGroups) {
|
|
331
|
+
// Emit one finding per occurrence, pointing to all others in the group
|
|
332
|
+
for (let i = 0; i < group.length; i++) {
|
|
333
|
+
const loc = group[i];
|
|
334
|
+
const otherLocs = group.filter((_, j) => j !== i);
|
|
335
|
+
const fileResult = fileResults.find(f => f.path === loc.filePath);
|
|
336
|
+
if (!fileResult) continue;
|
|
337
|
+
|
|
338
|
+
// Avoid duplicate reports: only report from the first occurrence
|
|
339
|
+
// (the others will reference back via the finding's metadata)
|
|
340
|
+
if (i === 0) {
|
|
341
|
+
findings.push(functionDuplicateFinding(fileResult, loc, otherLocs, severity));
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// ── 3. Attach aggregate metrics ───────────────────────────────────────
|
|
347
|
+
const allRegions = [
|
|
348
|
+
...windowDuplicates,
|
|
349
|
+
...fnDuplicateGroups.flatMap(g =>
|
|
350
|
+
g.map((loc, i) => i === 0 ? null : {
|
|
351
|
+
fileA: g[0].filePath, startLineA: g[0].startLine, endLineA: g[0].endLine,
|
|
352
|
+
fileB: loc.filePath, startLineB: loc.startLine, endLineB: loc.endLine,
|
|
353
|
+
})
|
|
354
|
+
).filter(Boolean),
|
|
355
|
+
];
|
|
356
|
+
|
|
357
|
+
const dupPercent = computeDuplicationPercentage(allRegions, fileResults);
|
|
358
|
+
|
|
359
|
+
for (const fileResult of fileResults) {
|
|
360
|
+
if (!fileResult.error) {
|
|
361
|
+
fileResult.metrics.duplicationPercent = dupPercent;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
return findings;
|
|
366
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AST Normalizer for duplication detection.
|
|
3
|
+
*
|
|
4
|
+
* Converts an AST node (or array of statement nodes) into a canonical
|
|
5
|
+
* string that is structurally identical for code that differs only in:
|
|
6
|
+
* • Variable / function names → 'V'
|
|
7
|
+
* • String literal values → 'S'
|
|
8
|
+
* • Numeric literal values → 'N'
|
|
9
|
+
* • Boolean literal values → 'B'
|
|
10
|
+
* • Template literal contents → 'TPL'
|
|
11
|
+
*
|
|
12
|
+
* Structural features preserved:
|
|
13
|
+
* • Node types (IfStatement, ForStatement, ReturnStatement, …)
|
|
14
|
+
* • Operator types (+, *, &&, ===, …)
|
|
15
|
+
* • Parameter counts
|
|
16
|
+
* • Nesting depth / block structure
|
|
17
|
+
* • Array and object shapes
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Normalize an array of statement nodes to a comparable string.
|
|
22
|
+
* @param {object[]} stmts — Babel AST statement nodes
|
|
23
|
+
* @returns {string}
|
|
24
|
+
*/
|
|
25
|
+
export function normalizeStatements(stmts) {
|
|
26
|
+
return stmts.map(normalizeNode).join(';');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Normalize a single AST node.
|
|
31
|
+
* @param {object|null} node
|
|
32
|
+
* @returns {string}
|
|
33
|
+
*/
|
|
34
|
+
export function normalizeNode(node) {
|
|
35
|
+
if (node === null || node === undefined) return 'nil';
|
|
36
|
+
if (typeof node !== 'object') return String(node);
|
|
37
|
+
if (Array.isArray(node)) return '[' + node.map(normalizeNode).join(',') + ']';
|
|
38
|
+
if (!node.type) return '?';
|
|
39
|
+
|
|
40
|
+
switch (node.type) {
|
|
41
|
+
// ── Literals (erase values, keep type) ──────────────────────────────
|
|
42
|
+
case 'Identifier':
|
|
43
|
+
return 'V';
|
|
44
|
+
|
|
45
|
+
case 'StringLiteral':
|
|
46
|
+
case 'DirectiveLiteral':
|
|
47
|
+
return 'S';
|
|
48
|
+
|
|
49
|
+
case 'NumericLiteral':
|
|
50
|
+
return 'N';
|
|
51
|
+
|
|
52
|
+
case 'BigIntLiteral':
|
|
53
|
+
return 'BIG';
|
|
54
|
+
|
|
55
|
+
case 'BooleanLiteral':
|
|
56
|
+
return 'B';
|
|
57
|
+
|
|
58
|
+
case 'NullLiteral':
|
|
59
|
+
return 'null';
|
|
60
|
+
|
|
61
|
+
case 'RegExpLiteral':
|
|
62
|
+
return 'RE';
|
|
63
|
+
|
|
64
|
+
case 'TemplateLiteral':
|
|
65
|
+
// Normalize quasis and expressions
|
|
66
|
+
return `TPL(${node.expressions.map(normalizeNode).join(',')})`;
|
|
67
|
+
|
|
68
|
+
case 'TaggedTemplateExpression':
|
|
69
|
+
return `Tagged(${normalizeNode(node.tag)},${normalizeNode(node.quasi)})`;
|
|
70
|
+
|
|
71
|
+
// ── Expressions ───────────────────────────────────────────────────────
|
|
72
|
+
case 'BinaryExpression':
|
|
73
|
+
return `Bin(${normalizeNode(node.left)},${node.operator},${normalizeNode(node.right)})`;
|
|
74
|
+
|
|
75
|
+
case 'LogicalExpression':
|
|
76
|
+
return `Log(${normalizeNode(node.left)},${node.operator},${normalizeNode(node.right)})`;
|
|
77
|
+
|
|
78
|
+
case 'AssignmentExpression':
|
|
79
|
+
return `Assign(${node.operator},${normalizeNode(node.left)},${normalizeNode(node.right)})`;
|
|
80
|
+
|
|
81
|
+
case 'UnaryExpression':
|
|
82
|
+
return `Unary(${node.operator},${normalizeNode(node.argument)})`;
|
|
83
|
+
|
|
84
|
+
case 'UpdateExpression':
|
|
85
|
+
return `Update(${node.operator},${node.prefix},${normalizeNode(node.argument)})`;
|
|
86
|
+
|
|
87
|
+
case 'MemberExpression':
|
|
88
|
+
// Keep the structure but erase names
|
|
89
|
+
return `Mem(${normalizeNode(node.object)},V)`;
|
|
90
|
+
|
|
91
|
+
case 'OptionalMemberExpression':
|
|
92
|
+
return `OptMem(${normalizeNode(node.object)},V)`;
|
|
93
|
+
|
|
94
|
+
case 'CallExpression':
|
|
95
|
+
return `Call(${normalizeNode(node.callee)},${node.arguments.map(normalizeNode).join(',')})`;
|
|
96
|
+
|
|
97
|
+
case 'OptionalCallExpression':
|
|
98
|
+
return `OptCall(${normalizeNode(node.callee)},${node.arguments.map(normalizeNode).join(',')})`;
|
|
99
|
+
|
|
100
|
+
case 'NewExpression':
|
|
101
|
+
return `New(${normalizeNode(node.callee)},${node.arguments.map(normalizeNode).join(',')})`;
|
|
102
|
+
|
|
103
|
+
case 'ConditionalExpression':
|
|
104
|
+
return `Cond(${normalizeNode(node.test)},${normalizeNode(node.consequent)},${normalizeNode(node.alternate)})`;
|
|
105
|
+
|
|
106
|
+
case 'AwaitExpression':
|
|
107
|
+
return `Await(${normalizeNode(node.argument)})`;
|
|
108
|
+
|
|
109
|
+
case 'YieldExpression':
|
|
110
|
+
return `Yield(${node.delegate},${normalizeNode(node.argument)})`;
|
|
111
|
+
|
|
112
|
+
case 'SequenceExpression':
|
|
113
|
+
return `Seq(${node.expressions.map(normalizeNode).join(',')})`;
|
|
114
|
+
|
|
115
|
+
case 'SpreadElement':
|
|
116
|
+
case 'RestElement':
|
|
117
|
+
return `Spread(${normalizeNode(node.argument)})`;
|
|
118
|
+
|
|
119
|
+
case 'ArrayExpression':
|
|
120
|
+
return `Arr(${node.elements.map(e => e ? normalizeNode(e) : 'hole').join(',')})`;
|
|
121
|
+
|
|
122
|
+
case 'ObjectExpression':
|
|
123
|
+
return `Obj(${node.properties.map(normalizeNode).join(',')})`;
|
|
124
|
+
|
|
125
|
+
case 'ObjectProperty':
|
|
126
|
+
case 'Property':
|
|
127
|
+
return `Prop(V,${normalizeNode(node.value)},${node.computed})`;
|
|
128
|
+
|
|
129
|
+
case 'ObjectMethod':
|
|
130
|
+
return `ObjMeth(V,${node.params.length},${normalizeNode(node.body)})`;
|
|
131
|
+
|
|
132
|
+
case 'AssignmentPattern':
|
|
133
|
+
return `Default(${normalizeNode(node.left)},${normalizeNode(node.right)})`;
|
|
134
|
+
|
|
135
|
+
case 'ArrayPattern':
|
|
136
|
+
return `ArrPat(${node.elements.map(e => e ? normalizeNode(e) : 'hole').join(',')})`;
|
|
137
|
+
|
|
138
|
+
case 'ObjectPattern':
|
|
139
|
+
return `ObjPat(${node.properties.map(normalizeNode).join(',')})`;
|
|
140
|
+
|
|
141
|
+
case 'ChainExpression':
|
|
142
|
+
return `Chain(${normalizeNode(node.expression)})`;
|
|
143
|
+
|
|
144
|
+
// ── Statements ────────────────────────────────────────────────────────
|
|
145
|
+
case 'ExpressionStatement':
|
|
146
|
+
return `Expr(${normalizeNode(node.expression)})`;
|
|
147
|
+
|
|
148
|
+
case 'BlockStatement':
|
|
149
|
+
return `{${node.body.map(normalizeNode).join(';')}}`;
|
|
150
|
+
|
|
151
|
+
case 'ReturnStatement':
|
|
152
|
+
return `Ret(${normalizeNode(node.argument)})`;
|
|
153
|
+
|
|
154
|
+
case 'ThrowStatement':
|
|
155
|
+
return `Throw(${normalizeNode(node.argument)})`;
|
|
156
|
+
|
|
157
|
+
case 'VariableDeclaration':
|
|
158
|
+
return `Var(${node.kind},${node.declarations.map(normalizeNode).join(',')})`;
|
|
159
|
+
|
|
160
|
+
case 'VariableDeclarator':
|
|
161
|
+
return `Decl(${normalizeNode(node.id)},${normalizeNode(node.init)})`;
|
|
162
|
+
|
|
163
|
+
case 'IfStatement':
|
|
164
|
+
return `If(${normalizeNode(node.test)},${normalizeNode(node.consequent)},${normalizeNode(node.alternate)})`;
|
|
165
|
+
|
|
166
|
+
case 'ForStatement':
|
|
167
|
+
return `For(${normalizeNode(node.init)},${normalizeNode(node.test)},${normalizeNode(node.update)},${normalizeNode(node.body)})`;
|
|
168
|
+
|
|
169
|
+
case 'ForInStatement':
|
|
170
|
+
return `ForIn(${normalizeNode(node.left)},${normalizeNode(node.right)},${normalizeNode(node.body)})`;
|
|
171
|
+
|
|
172
|
+
case 'ForOfStatement':
|
|
173
|
+
return `ForOf(${node.await},${normalizeNode(node.left)},${normalizeNode(node.right)},${normalizeNode(node.body)})`;
|
|
174
|
+
|
|
175
|
+
case 'WhileStatement':
|
|
176
|
+
return `While(${normalizeNode(node.test)},${normalizeNode(node.body)})`;
|
|
177
|
+
|
|
178
|
+
case 'DoWhileStatement':
|
|
179
|
+
return `DoWhile(${normalizeNode(node.test)},${normalizeNode(node.body)})`;
|
|
180
|
+
|
|
181
|
+
case 'SwitchStatement':
|
|
182
|
+
return `Switch(${normalizeNode(node.discriminant)},${node.cases.map(normalizeNode).join(',')})`;
|
|
183
|
+
|
|
184
|
+
case 'SwitchCase':
|
|
185
|
+
return `Case(${normalizeNode(node.test)},${node.consequent.map(normalizeNode).join(';')})`;
|
|
186
|
+
|
|
187
|
+
case 'TryStatement':
|
|
188
|
+
return `Try(${normalizeNode(node.block)},${normalizeNode(node.handler)},${normalizeNode(node.finalizer)})`;
|
|
189
|
+
|
|
190
|
+
case 'CatchClause':
|
|
191
|
+
return `Catch(${normalizeNode(node.param)},${normalizeNode(node.body)})`;
|
|
192
|
+
|
|
193
|
+
case 'BreakStatement':
|
|
194
|
+
return 'Break';
|
|
195
|
+
|
|
196
|
+
case 'ContinueStatement':
|
|
197
|
+
return 'Continue';
|
|
198
|
+
|
|
199
|
+
case 'LabeledStatement':
|
|
200
|
+
return `Label(${normalizeNode(node.body)})`;
|
|
201
|
+
|
|
202
|
+
case 'WithStatement':
|
|
203
|
+
return `With(${normalizeNode(node.object)},${normalizeNode(node.body)})`;
|
|
204
|
+
|
|
205
|
+
// ── Functions ──────────────────────────────────────────────────────────
|
|
206
|
+
case 'FunctionDeclaration':
|
|
207
|
+
case 'FunctionExpression':
|
|
208
|
+
return `Fn(${node.async},${node.generator},${node.params.length},${normalizeNode(node.body)})`;
|
|
209
|
+
|
|
210
|
+
case 'ArrowFunctionExpression':
|
|
211
|
+
return `Arrow(${node.async},${node.params.length},${normalizeNode(node.body)})`;
|
|
212
|
+
|
|
213
|
+
case 'ClassDeclaration':
|
|
214
|
+
case 'ClassExpression':
|
|
215
|
+
return `Class(${node.superClass ? 'ext' : ''},${node.body.body.map(normalizeNode).join(';')})`;
|
|
216
|
+
|
|
217
|
+
case 'ClassMethod':
|
|
218
|
+
return `CMeth(${node.kind},V,${node.static},${node.async},${node.params.length},${normalizeNode(node.body)})`;
|
|
219
|
+
|
|
220
|
+
// ── Imports / Exports ──────────────────────────────────────────────────
|
|
221
|
+
case 'ImportDeclaration':
|
|
222
|
+
return `Import(${node.specifiers.length})`;
|
|
223
|
+
|
|
224
|
+
case 'ExportNamedDeclaration':
|
|
225
|
+
return `Export(${normalizeNode(node.declaration)})`;
|
|
226
|
+
|
|
227
|
+
case 'ExportDefaultDeclaration':
|
|
228
|
+
return `ExportDefault(${normalizeNode(node.declaration)})`;
|
|
229
|
+
|
|
230
|
+
// ── Misc ──────────────────────────────────────────────────────────────
|
|
231
|
+
case 'EmptyStatement':
|
|
232
|
+
return 'Empty';
|
|
233
|
+
|
|
234
|
+
default:
|
|
235
|
+
// Fall back to just the type name so unknown nodes don't crash
|
|
236
|
+
return node.type;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Re-exports all built-in analyzer modules so the CLI and
|
|
3
|
+
* programmatic API have a single import point.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export * as complexityAnalyzer from './complexity/index.js';
|
|
7
|
+
export * as smellsAnalyzer from './smells/index.js';
|
|
8
|
+
export * as duplicationAnalyzer from './duplication/index.js';
|
|
9
|
+
export * as dependencyAnalyzer from './dependencies/index.js';
|