@aiready/pattern-detect 0.9.14 → 0.9.19
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/dist/chunk-CMT3MWWO.mjs +948 -0
- package/dist/chunk-EFUKPMBE.mjs +950 -0
- package/dist/chunk-UKIKN27B.mjs +950 -0
- package/dist/chunk-X4GR2N2M.mjs +947 -0
- package/dist/chunk-Z6GBFFOV.mjs +1040 -0
- package/dist/cli.js +357 -6
- package/dist/cli.mjs +76 -6
- package/dist/index.d.mts +56 -2
- package/dist/index.d.ts +56 -2
- package/dist/index.js +373 -1
- package/dist/index.mjs +3 -1
- package/package.json +2 -2
|
@@ -0,0 +1,948 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { readFileContent } from "@aiready/core";
|
|
3
|
+
|
|
4
|
+
// src/detector.ts
|
|
5
|
+
import { estimateTokens } from "@aiready/core";
|
|
6
|
+
|
|
7
|
+
// src/context-rules.ts
|
|
8
|
+
var CONTEXT_RULES = [
|
|
9
|
+
// Test Fixtures - Intentional duplication for test isolation
|
|
10
|
+
{
|
|
11
|
+
name: "test-fixtures",
|
|
12
|
+
detect: (file, code) => {
|
|
13
|
+
const isTestFile = file.includes(".test.") || file.includes(".spec.") || file.includes("__tests__") || file.includes("/test/") || file.includes("/tests/");
|
|
14
|
+
const hasTestFixtures = code.includes("beforeAll") || code.includes("afterAll") || code.includes("beforeEach") || code.includes("afterEach") || code.includes("setUp") || code.includes("tearDown");
|
|
15
|
+
return isTestFile && hasTestFixtures;
|
|
16
|
+
},
|
|
17
|
+
severity: "info",
|
|
18
|
+
reason: "Test fixture duplication is intentional for test isolation",
|
|
19
|
+
suggestion: "Consider if shared test setup would improve maintainability without coupling tests"
|
|
20
|
+
},
|
|
21
|
+
// Email/Document Templates - Often intentionally similar for consistency
|
|
22
|
+
{
|
|
23
|
+
name: "templates",
|
|
24
|
+
detect: (file, code) => {
|
|
25
|
+
const isTemplate = file.includes("/templates/") || file.includes("-template") || file.includes("/email-templates/") || file.includes("/emails/");
|
|
26
|
+
const hasTemplateContent = (code.includes("return") || code.includes("export")) && (code.includes("html") || code.includes("subject") || code.includes("body"));
|
|
27
|
+
return isTemplate && hasTemplateContent;
|
|
28
|
+
},
|
|
29
|
+
severity: "minor",
|
|
30
|
+
reason: "Template duplication may be intentional for maintainability and branding consistency",
|
|
31
|
+
suggestion: "Extract shared structure only if templates become hard to maintain"
|
|
32
|
+
},
|
|
33
|
+
// E2E/Integration Test Page Objects - Test independence
|
|
34
|
+
{
|
|
35
|
+
name: "e2e-page-objects",
|
|
36
|
+
detect: (file, code) => {
|
|
37
|
+
const isE2ETest = file.includes("e2e/") || file.includes("/e2e/") || file.includes(".e2e.") || file.includes("/playwright/") || file.includes("playwright/") || file.includes("/cypress/") || file.includes("cypress/") || file.includes("/integration/") || file.includes("integration/");
|
|
38
|
+
const hasPageObjectPatterns = code.includes("page.") || code.includes("await page") || code.includes("locator") || code.includes("getBy") || code.includes("selector") || code.includes("click(") || code.includes("fill(");
|
|
39
|
+
return isE2ETest && hasPageObjectPatterns;
|
|
40
|
+
},
|
|
41
|
+
severity: "minor",
|
|
42
|
+
reason: "E2E test duplication ensures test independence and reduces coupling",
|
|
43
|
+
suggestion: "Consider page object pattern only if duplication causes maintenance issues"
|
|
44
|
+
},
|
|
45
|
+
// Configuration Files - Often necessarily similar by design
|
|
46
|
+
{
|
|
47
|
+
name: "config-files",
|
|
48
|
+
detect: (file) => {
|
|
49
|
+
return file.endsWith(".config.ts") || file.endsWith(".config.js") || file.includes("jest.config") || file.includes("vite.config") || file.includes("webpack.config") || file.includes("rollup.config") || file.includes("tsconfig");
|
|
50
|
+
},
|
|
51
|
+
severity: "minor",
|
|
52
|
+
reason: "Configuration files often have similar structure by design",
|
|
53
|
+
suggestion: "Consider shared config base only if configurations become hard to maintain"
|
|
54
|
+
},
|
|
55
|
+
// Type Definitions - Duplication for type safety and module independence
|
|
56
|
+
{
|
|
57
|
+
name: "type-definitions",
|
|
58
|
+
detect: (file, code) => {
|
|
59
|
+
const isTypeFile = file.endsWith(".d.ts") || file.includes("/types/");
|
|
60
|
+
const hasTypeDefinitions = code.includes("interface ") || code.includes("type ") || code.includes("enum ");
|
|
61
|
+
return isTypeFile && hasTypeDefinitions;
|
|
62
|
+
},
|
|
63
|
+
severity: "info",
|
|
64
|
+
reason: "Type duplication may be intentional for module independence and type safety",
|
|
65
|
+
suggestion: "Extract to shared types package only if causing maintenance burden"
|
|
66
|
+
},
|
|
67
|
+
// Migration Scripts - One-off scripts that are similar by nature
|
|
68
|
+
{
|
|
69
|
+
name: "migration-scripts",
|
|
70
|
+
detect: (file) => {
|
|
71
|
+
return file.includes("/migrations/") || file.includes("/migrate/") || file.includes(".migration.");
|
|
72
|
+
},
|
|
73
|
+
severity: "info",
|
|
74
|
+
reason: "Migration scripts are typically one-off and intentionally similar",
|
|
75
|
+
suggestion: "Duplication is acceptable for migration scripts"
|
|
76
|
+
},
|
|
77
|
+
// Mock Data - Test data intentionally duplicated
|
|
78
|
+
{
|
|
79
|
+
name: "mock-data",
|
|
80
|
+
detect: (file, code) => {
|
|
81
|
+
const isMockFile = file.includes("/mocks/") || file.includes("/__mocks__/") || file.includes("/fixtures/") || file.includes(".mock.") || file.includes(".fixture.");
|
|
82
|
+
const hasMockData = code.includes("mock") || code.includes("Mock") || code.includes("fixture") || code.includes("stub") || code.includes("export const");
|
|
83
|
+
return isMockFile && hasMockData;
|
|
84
|
+
},
|
|
85
|
+
severity: "info",
|
|
86
|
+
reason: "Mock data duplication is expected for comprehensive test coverage",
|
|
87
|
+
suggestion: "Consider shared factories only for complex mock generation"
|
|
88
|
+
}
|
|
89
|
+
];
|
|
90
|
+
function calculateSeverity(file1, file2, code, similarity, linesOfCode) {
|
|
91
|
+
for (const rule of CONTEXT_RULES) {
|
|
92
|
+
if (rule.detect(file1, code) || rule.detect(file2, code)) {
|
|
93
|
+
return {
|
|
94
|
+
severity: rule.severity,
|
|
95
|
+
reason: rule.reason,
|
|
96
|
+
suggestion: rule.suggestion,
|
|
97
|
+
matchedRule: rule.name
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (similarity >= 0.95 && linesOfCode >= 30) {
|
|
102
|
+
return {
|
|
103
|
+
severity: "critical",
|
|
104
|
+
reason: "Large nearly-identical code blocks waste tokens and create maintenance burden",
|
|
105
|
+
suggestion: "Extract to shared utility module immediately"
|
|
106
|
+
};
|
|
107
|
+
} else if (similarity >= 0.95 && linesOfCode >= 15) {
|
|
108
|
+
return {
|
|
109
|
+
severity: "major",
|
|
110
|
+
reason: "Nearly identical code should be consolidated",
|
|
111
|
+
suggestion: "Move to shared utility file"
|
|
112
|
+
};
|
|
113
|
+
} else if (similarity >= 0.85) {
|
|
114
|
+
return {
|
|
115
|
+
severity: "major",
|
|
116
|
+
reason: "High similarity indicates significant duplication",
|
|
117
|
+
suggestion: "Extract common logic to shared function"
|
|
118
|
+
};
|
|
119
|
+
} else if (similarity >= 0.7) {
|
|
120
|
+
return {
|
|
121
|
+
severity: "minor",
|
|
122
|
+
reason: "Moderate similarity detected",
|
|
123
|
+
suggestion: "Consider extracting shared patterns if code evolves together"
|
|
124
|
+
};
|
|
125
|
+
} else {
|
|
126
|
+
return {
|
|
127
|
+
severity: "minor",
|
|
128
|
+
reason: "Minor similarity detected",
|
|
129
|
+
suggestion: "Monitor but refactoring may not be worthwhile"
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function getSeverityLabel(severity) {
|
|
134
|
+
const labels = {
|
|
135
|
+
critical: "\u{1F534} CRITICAL",
|
|
136
|
+
major: "\u{1F7E1} MAJOR",
|
|
137
|
+
minor: "\u{1F535} MINOR",
|
|
138
|
+
info: "\u2139\uFE0F INFO"
|
|
139
|
+
};
|
|
140
|
+
return labels[severity];
|
|
141
|
+
}
|
|
142
|
+
function filterBySeverity(duplicates, minSeverity) {
|
|
143
|
+
const severityOrder = ["info", "minor", "major", "critical"];
|
|
144
|
+
const minIndex = severityOrder.indexOf(minSeverity);
|
|
145
|
+
if (minIndex === -1) return duplicates;
|
|
146
|
+
return duplicates.filter((dup) => {
|
|
147
|
+
const dupIndex = severityOrder.indexOf(dup.severity);
|
|
148
|
+
return dupIndex >= minIndex;
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// src/detector.ts
|
|
153
|
+
function categorizePattern(code) {
|
|
154
|
+
const lower = code.toLowerCase();
|
|
155
|
+
if (lower.includes("request") && lower.includes("response") || lower.includes("router.") || lower.includes("app.get") || lower.includes("app.post") || lower.includes("express") || lower.includes("ctx.body")) {
|
|
156
|
+
return "api-handler";
|
|
157
|
+
}
|
|
158
|
+
if (lower.includes("validate") || lower.includes("schema") || lower.includes("zod") || lower.includes("yup") || lower.includes("if") && lower.includes("throw")) {
|
|
159
|
+
return "validator";
|
|
160
|
+
}
|
|
161
|
+
if (lower.includes("return (") || lower.includes("jsx") || lower.includes("component") || lower.includes("props")) {
|
|
162
|
+
return "component";
|
|
163
|
+
}
|
|
164
|
+
if (lower.includes("class ") || lower.includes("this.")) {
|
|
165
|
+
return "class-method";
|
|
166
|
+
}
|
|
167
|
+
if (lower.includes("return ") && !lower.includes("this") && !lower.includes("new ")) {
|
|
168
|
+
return "utility";
|
|
169
|
+
}
|
|
170
|
+
if (lower.includes("function") || lower.includes("=>")) {
|
|
171
|
+
return "function";
|
|
172
|
+
}
|
|
173
|
+
return "unknown";
|
|
174
|
+
}
|
|
175
|
+
function extractCodeBlocks(content, minLines) {
|
|
176
|
+
const lines = content.split("\n");
|
|
177
|
+
const blocks = [];
|
|
178
|
+
let currentBlock = [];
|
|
179
|
+
let blockStart = 0;
|
|
180
|
+
let braceDepth = 0;
|
|
181
|
+
let inFunction = false;
|
|
182
|
+
for (let i = 0; i < lines.length; i++) {
|
|
183
|
+
const line = lines[i];
|
|
184
|
+
const trimmed = line.trim();
|
|
185
|
+
if (!inFunction && (trimmed.includes("function ") || trimmed.includes("=>") || trimmed.includes("async ") || /^(export\s+)?(async\s+)?function\s+/.test(trimmed) || /^(export\s+)?const\s+\w+\s*=\s*(async\s*)?\(/.test(trimmed))) {
|
|
186
|
+
inFunction = true;
|
|
187
|
+
blockStart = i;
|
|
188
|
+
}
|
|
189
|
+
for (const char of line) {
|
|
190
|
+
if (char === "{") braceDepth++;
|
|
191
|
+
if (char === "}") braceDepth--;
|
|
192
|
+
}
|
|
193
|
+
if (inFunction) {
|
|
194
|
+
currentBlock.push(line);
|
|
195
|
+
}
|
|
196
|
+
if (inFunction && braceDepth === 0 && currentBlock.length >= minLines) {
|
|
197
|
+
const blockContent = currentBlock.join("\n");
|
|
198
|
+
const linesOfCode = currentBlock.filter(
|
|
199
|
+
(l) => l.trim() && !l.trim().startsWith("//")
|
|
200
|
+
).length;
|
|
201
|
+
blocks.push({
|
|
202
|
+
content: blockContent,
|
|
203
|
+
startLine: blockStart + 1,
|
|
204
|
+
endLine: i + 1,
|
|
205
|
+
patternType: categorizePattern(blockContent),
|
|
206
|
+
linesOfCode
|
|
207
|
+
});
|
|
208
|
+
currentBlock = [];
|
|
209
|
+
inFunction = false;
|
|
210
|
+
} else if (inFunction && braceDepth === 0) {
|
|
211
|
+
currentBlock = [];
|
|
212
|
+
inFunction = false;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return blocks;
|
|
216
|
+
}
|
|
217
|
+
function normalizeCode(code) {
|
|
218
|
+
return code.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "").replace(/"[^"]*"/g, '"STR"').replace(/'[^']*'/g, "'STR'").replace(/`[^`]*`/g, "`STR`").replace(/\b\d+\b/g, "NUM").replace(/\s+/g, " ").trim();
|
|
219
|
+
}
|
|
220
|
+
function jaccardSimilarity(tokens1, tokens2) {
|
|
221
|
+
const set1 = new Set(tokens1);
|
|
222
|
+
const set2 = new Set(tokens2);
|
|
223
|
+
let intersection = 0;
|
|
224
|
+
for (const token of set1) {
|
|
225
|
+
if (set2.has(token)) intersection++;
|
|
226
|
+
}
|
|
227
|
+
const union = set1.size + set2.size - intersection;
|
|
228
|
+
return union === 0 ? 0 : intersection / union;
|
|
229
|
+
}
|
|
230
|
+
async function detectDuplicatePatterns(files, options) {
|
|
231
|
+
const {
|
|
232
|
+
minSimilarity,
|
|
233
|
+
minLines,
|
|
234
|
+
batchSize = 100,
|
|
235
|
+
approx = true,
|
|
236
|
+
minSharedTokens = 8,
|
|
237
|
+
maxCandidatesPerBlock = 100,
|
|
238
|
+
streamResults = false
|
|
239
|
+
} = options;
|
|
240
|
+
const duplicates = [];
|
|
241
|
+
const maxComparisons = approx ? Infinity : 5e5;
|
|
242
|
+
const allBlocks = files.flatMap(
|
|
243
|
+
(file) => extractCodeBlocks(file.content, minLines).map((block) => ({
|
|
244
|
+
content: block.content,
|
|
245
|
+
startLine: block.startLine,
|
|
246
|
+
endLine: block.endLine,
|
|
247
|
+
file: file.file,
|
|
248
|
+
normalized: normalizeCode(block.content),
|
|
249
|
+
patternType: block.patternType,
|
|
250
|
+
tokenCost: estimateTokens(block.content),
|
|
251
|
+
linesOfCode: block.linesOfCode
|
|
252
|
+
}))
|
|
253
|
+
);
|
|
254
|
+
console.log(`Extracted ${allBlocks.length} code blocks for analysis`);
|
|
255
|
+
if (!approx && allBlocks.length > 500) {
|
|
256
|
+
console.log(`\u26A0\uFE0F Using --no-approx mode with ${allBlocks.length} blocks may be slow (O(B\xB2) complexity).`);
|
|
257
|
+
console.log(` Consider using approximate mode (default) for better performance.`);
|
|
258
|
+
}
|
|
259
|
+
const stopwords = /* @__PURE__ */ new Set([
|
|
260
|
+
"return",
|
|
261
|
+
"const",
|
|
262
|
+
"let",
|
|
263
|
+
"var",
|
|
264
|
+
"function",
|
|
265
|
+
"class",
|
|
266
|
+
"new",
|
|
267
|
+
"if",
|
|
268
|
+
"else",
|
|
269
|
+
"for",
|
|
270
|
+
"while",
|
|
271
|
+
"async",
|
|
272
|
+
"await",
|
|
273
|
+
"try",
|
|
274
|
+
"catch",
|
|
275
|
+
"switch",
|
|
276
|
+
"case",
|
|
277
|
+
"default",
|
|
278
|
+
"import",
|
|
279
|
+
"export",
|
|
280
|
+
"from",
|
|
281
|
+
"true",
|
|
282
|
+
"false",
|
|
283
|
+
"null",
|
|
284
|
+
"undefined",
|
|
285
|
+
"this"
|
|
286
|
+
]);
|
|
287
|
+
const tokenize = (norm) => norm.split(/[\s(){}\[\];,\.]+/).filter((t) => t && t.length >= 3 && !stopwords.has(t.toLowerCase()));
|
|
288
|
+
const blockTokens = allBlocks.map((b) => tokenize(b.normalized));
|
|
289
|
+
const invertedIndex = /* @__PURE__ */ new Map();
|
|
290
|
+
if (approx) {
|
|
291
|
+
for (let i = 0; i < blockTokens.length; i++) {
|
|
292
|
+
for (const tok of blockTokens[i]) {
|
|
293
|
+
let arr = invertedIndex.get(tok);
|
|
294
|
+
if (!arr) {
|
|
295
|
+
arr = [];
|
|
296
|
+
invertedIndex.set(tok, arr);
|
|
297
|
+
}
|
|
298
|
+
arr.push(i);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
const totalComparisons = approx ? void 0 : allBlocks.length * (allBlocks.length - 1) / 2;
|
|
303
|
+
if (totalComparisons !== void 0) {
|
|
304
|
+
console.log(`Processing ${totalComparisons.toLocaleString()} comparisons in batches...`);
|
|
305
|
+
} else {
|
|
306
|
+
console.log(`Using approximate candidate selection to reduce comparisons...`);
|
|
307
|
+
}
|
|
308
|
+
let comparisonsProcessed = 0;
|
|
309
|
+
let comparisonsBudgetExhausted = false;
|
|
310
|
+
const startTime = Date.now();
|
|
311
|
+
for (let i = 0; i < allBlocks.length; i++) {
|
|
312
|
+
if (maxComparisons && comparisonsProcessed >= maxComparisons) {
|
|
313
|
+
comparisonsBudgetExhausted = true;
|
|
314
|
+
break;
|
|
315
|
+
}
|
|
316
|
+
if (i % batchSize === 0 && i > 0) {
|
|
317
|
+
const elapsed = ((Date.now() - startTime) / 1e3).toFixed(1);
|
|
318
|
+
const duplicatesFound = duplicates.length;
|
|
319
|
+
if (totalComparisons !== void 0) {
|
|
320
|
+
const progress = (comparisonsProcessed / totalComparisons * 100).toFixed(1);
|
|
321
|
+
const remaining = totalComparisons - comparisonsProcessed;
|
|
322
|
+
const rate = comparisonsProcessed / parseFloat(elapsed);
|
|
323
|
+
const eta = remaining > 0 ? (remaining / rate).toFixed(0) : 0;
|
|
324
|
+
console.log(` ${progress}% (${comparisonsProcessed.toLocaleString()}/${totalComparisons.toLocaleString()} comparisons, ${elapsed}s elapsed, ~${eta}s remaining, ${duplicatesFound} duplicates)`);
|
|
325
|
+
} else {
|
|
326
|
+
console.log(` Processed ${i.toLocaleString()}/${allBlocks.length} blocks (${elapsed}s elapsed, ${duplicatesFound} duplicates)`);
|
|
327
|
+
}
|
|
328
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
329
|
+
}
|
|
330
|
+
const block1 = allBlocks[i];
|
|
331
|
+
let candidates = null;
|
|
332
|
+
if (approx) {
|
|
333
|
+
const counts = /* @__PURE__ */ new Map();
|
|
334
|
+
const block1Tokens = new Set(blockTokens[i]);
|
|
335
|
+
const block1Size = block1Tokens.size;
|
|
336
|
+
const rareTokens = blockTokens[i].filter((tok) => {
|
|
337
|
+
const blocksWithToken = invertedIndex.get(tok)?.length || 0;
|
|
338
|
+
return blocksWithToken < allBlocks.length * 0.1;
|
|
339
|
+
});
|
|
340
|
+
for (const tok of rareTokens) {
|
|
341
|
+
const ids = invertedIndex.get(tok);
|
|
342
|
+
if (!ids) continue;
|
|
343
|
+
for (const j of ids) {
|
|
344
|
+
if (j <= i) continue;
|
|
345
|
+
if (allBlocks[j].file === block1.file) continue;
|
|
346
|
+
counts.set(j, (counts.get(j) || 0) + 1);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
candidates = Array.from(counts.entries()).filter(([j, shared]) => {
|
|
350
|
+
const block2Tokens = blockTokens[j];
|
|
351
|
+
const block2Size = block2Tokens.length;
|
|
352
|
+
const minSize = Math.min(block1Size, block2Size);
|
|
353
|
+
const sharedPercentage = shared / minSize;
|
|
354
|
+
return shared >= minSharedTokens && sharedPercentage >= 0.3;
|
|
355
|
+
}).sort((a, b) => b[1] - a[1]).slice(0, Math.min(maxCandidatesPerBlock, 5)).map(([j, shared]) => ({ j, shared }));
|
|
356
|
+
}
|
|
357
|
+
if (approx && candidates) {
|
|
358
|
+
for (const { j } of candidates) {
|
|
359
|
+
if (!approx && maxComparisons !== Infinity && comparisonsProcessed >= maxComparisons) {
|
|
360
|
+
console.log(`\u26A0\uFE0F Comparison safety limit reached (${maxComparisons.toLocaleString()} comparisons in --no-approx mode).`);
|
|
361
|
+
console.log(` This prevents excessive runtime on large repos. Consider using approximate mode (default) or --min-lines to reduce blocks.`);
|
|
362
|
+
break;
|
|
363
|
+
}
|
|
364
|
+
comparisonsProcessed++;
|
|
365
|
+
const block2 = allBlocks[j];
|
|
366
|
+
const similarity = jaccardSimilarity(blockTokens[i], blockTokens[j]);
|
|
367
|
+
if (similarity >= minSimilarity) {
|
|
368
|
+
const { severity, reason, suggestion, matchedRule } = calculateSeverity(
|
|
369
|
+
block1.file,
|
|
370
|
+
block2.file,
|
|
371
|
+
block1.content,
|
|
372
|
+
similarity,
|
|
373
|
+
block1.linesOfCode
|
|
374
|
+
);
|
|
375
|
+
const duplicate = {
|
|
376
|
+
file1: block1.file,
|
|
377
|
+
file2: block2.file,
|
|
378
|
+
line1: block1.startLine,
|
|
379
|
+
line2: block2.startLine,
|
|
380
|
+
endLine1: block1.endLine,
|
|
381
|
+
endLine2: block2.endLine,
|
|
382
|
+
similarity,
|
|
383
|
+
snippet: block1.content.split("\n").slice(0, 5).join("\n") + "\n...",
|
|
384
|
+
patternType: block1.patternType,
|
|
385
|
+
tokenCost: block1.tokenCost + block2.tokenCost,
|
|
386
|
+
linesOfCode: block1.linesOfCode,
|
|
387
|
+
severity,
|
|
388
|
+
reason,
|
|
389
|
+
suggestion,
|
|
390
|
+
matchedRule
|
|
391
|
+
};
|
|
392
|
+
duplicates.push(duplicate);
|
|
393
|
+
if (streamResults) {
|
|
394
|
+
console.log(`
|
|
395
|
+
\u2705 Found: ${duplicate.patternType} ${Math.round(similarity * 100)}% similar`);
|
|
396
|
+
console.log(` ${duplicate.file1}:${duplicate.line1}-${duplicate.endLine1} \u21D4 ${duplicate.file2}:${duplicate.line2}-${duplicate.endLine2}`);
|
|
397
|
+
console.log(` Token cost: ${duplicate.tokenCost.toLocaleString()}`);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
} else {
|
|
402
|
+
for (let j = i + 1; j < allBlocks.length; j++) {
|
|
403
|
+
if (maxComparisons && comparisonsProcessed >= maxComparisons) break;
|
|
404
|
+
comparisonsProcessed++;
|
|
405
|
+
const block2 = allBlocks[j];
|
|
406
|
+
if (block1.file === block2.file) continue;
|
|
407
|
+
const similarity = jaccardSimilarity(blockTokens[i], blockTokens[j]);
|
|
408
|
+
if (similarity >= minSimilarity) {
|
|
409
|
+
const { severity, reason, suggestion, matchedRule } = calculateSeverity(
|
|
410
|
+
block1.file,
|
|
411
|
+
block2.file,
|
|
412
|
+
block1.content,
|
|
413
|
+
similarity,
|
|
414
|
+
block1.linesOfCode
|
|
415
|
+
);
|
|
416
|
+
const duplicate = {
|
|
417
|
+
file1: block1.file,
|
|
418
|
+
file2: block2.file,
|
|
419
|
+
line1: block1.startLine,
|
|
420
|
+
line2: block2.startLine,
|
|
421
|
+
endLine1: block1.endLine,
|
|
422
|
+
endLine2: block2.endLine,
|
|
423
|
+
similarity,
|
|
424
|
+
snippet: block1.content.split("\n").slice(0, 5).join("\n") + "\n...",
|
|
425
|
+
patternType: block1.patternType,
|
|
426
|
+
tokenCost: block1.tokenCost + block2.tokenCost,
|
|
427
|
+
linesOfCode: block1.linesOfCode,
|
|
428
|
+
severity,
|
|
429
|
+
reason,
|
|
430
|
+
suggestion,
|
|
431
|
+
matchedRule
|
|
432
|
+
};
|
|
433
|
+
duplicates.push(duplicate);
|
|
434
|
+
if (streamResults) {
|
|
435
|
+
console.log(`
|
|
436
|
+
\u2705 Found: ${duplicate.patternType} ${Math.round(similarity * 100)}% similar`);
|
|
437
|
+
console.log(` ${duplicate.file1}:${duplicate.line1}-${duplicate.endLine1} \u21D4 ${duplicate.file2}:${duplicate.line2}-${duplicate.endLine2}`);
|
|
438
|
+
console.log(` Token cost: ${duplicate.tokenCost.toLocaleString()}`);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (comparisonsBudgetExhausted) {
|
|
445
|
+
console.log(`\u26A0\uFE0F Comparison budget exhausted (${maxComparisons.toLocaleString()} comparisons). Use --max-comparisons to increase.`);
|
|
446
|
+
}
|
|
447
|
+
return duplicates.sort(
|
|
448
|
+
(a, b) => b.similarity - a.similarity || b.tokenCost - a.tokenCost
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// src/grouping.ts
|
|
453
|
+
function normalizeFilePair(file1, file2) {
|
|
454
|
+
return file1 < file2 ? `${file1}::${file2}` : `${file2}::${file1}`;
|
|
455
|
+
}
|
|
456
|
+
function rangesOverlap(start1, end1, start2, end2, tolerance = 5) {
|
|
457
|
+
return start1 <= end2 + tolerance && start2 <= end1 + tolerance;
|
|
458
|
+
}
|
|
459
|
+
function groupDuplicatesByFilePair(duplicates) {
|
|
460
|
+
const groups = /* @__PURE__ */ new Map();
|
|
461
|
+
for (const dup of duplicates) {
|
|
462
|
+
const key = normalizeFilePair(dup.file1, dup.file2);
|
|
463
|
+
if (!groups.has(key)) {
|
|
464
|
+
groups.set(key, []);
|
|
465
|
+
}
|
|
466
|
+
groups.get(key).push(dup);
|
|
467
|
+
}
|
|
468
|
+
const result = [];
|
|
469
|
+
for (const [filePair, groupDups] of groups.entries()) {
|
|
470
|
+
const deduplicated = deduplicateOverlappingRanges(groupDups);
|
|
471
|
+
const totalTokenCost = deduplicated.reduce((sum, d) => sum + d.tokenCost, 0);
|
|
472
|
+
const averageSimilarity = deduplicated.reduce((sum, d) => sum + d.similarity, 0) / deduplicated.length;
|
|
473
|
+
const maxSimilarity = Math.max(...deduplicated.map((d) => d.similarity));
|
|
474
|
+
const severity = getHighestSeverity(deduplicated.map((d) => d.severity));
|
|
475
|
+
const patternType = getMostCommonPatternType(deduplicated);
|
|
476
|
+
const lineRanges = deduplicated.map((d) => ({
|
|
477
|
+
file1: { start: d.line1, end: d.endLine1 },
|
|
478
|
+
file2: { start: d.line2, end: d.endLine2 }
|
|
479
|
+
}));
|
|
480
|
+
result.push({
|
|
481
|
+
filePair,
|
|
482
|
+
duplicates: deduplicated,
|
|
483
|
+
totalTokenCost,
|
|
484
|
+
averageSimilarity,
|
|
485
|
+
maxSimilarity,
|
|
486
|
+
severity,
|
|
487
|
+
patternType,
|
|
488
|
+
occurrences: deduplicated.length,
|
|
489
|
+
lineRanges
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
return result.sort((a, b) => b.totalTokenCost - a.totalTokenCost);
|
|
493
|
+
}
|
|
494
|
+
function deduplicateOverlappingRanges(duplicates) {
|
|
495
|
+
if (duplicates.length === 0) return [];
|
|
496
|
+
const sorted = [...duplicates].sort((a, b) => {
|
|
497
|
+
if (a.line1 !== b.line1) return a.line1 - b.line1;
|
|
498
|
+
return b.similarity - a.similarity;
|
|
499
|
+
});
|
|
500
|
+
const result = [];
|
|
501
|
+
let current = null;
|
|
502
|
+
for (const dup of sorted) {
|
|
503
|
+
if (!current) {
|
|
504
|
+
current = dup;
|
|
505
|
+
result.push(dup);
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
const overlapsFile1 = rangesOverlap(
|
|
509
|
+
current.line1,
|
|
510
|
+
current.endLine1,
|
|
511
|
+
dup.line1,
|
|
512
|
+
dup.endLine1
|
|
513
|
+
);
|
|
514
|
+
const overlapsFile2 = rangesOverlap(
|
|
515
|
+
current.line2,
|
|
516
|
+
current.endLine2,
|
|
517
|
+
dup.line2,
|
|
518
|
+
dup.endLine2
|
|
519
|
+
);
|
|
520
|
+
if (overlapsFile1 && overlapsFile2) {
|
|
521
|
+
current = {
|
|
522
|
+
...current,
|
|
523
|
+
endLine1: Math.max(current.endLine1, dup.endLine1),
|
|
524
|
+
endLine2: Math.max(current.endLine2, dup.endLine2),
|
|
525
|
+
tokenCost: Math.max(current.tokenCost, dup.tokenCost)
|
|
526
|
+
};
|
|
527
|
+
result[result.length - 1] = current;
|
|
528
|
+
} else {
|
|
529
|
+
current = dup;
|
|
530
|
+
result.push(dup);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
return result;
|
|
534
|
+
}
|
|
535
|
+
function createRefactorClusters(duplicates) {
|
|
536
|
+
const clusters = /* @__PURE__ */ new Map();
|
|
537
|
+
for (const dup of duplicates) {
|
|
538
|
+
const clusterId = identifyCluster(dup);
|
|
539
|
+
if (!clusters.has(clusterId)) {
|
|
540
|
+
clusters.set(clusterId, []);
|
|
541
|
+
}
|
|
542
|
+
clusters.get(clusterId).push(dup);
|
|
543
|
+
}
|
|
544
|
+
const result = [];
|
|
545
|
+
for (const [clusterId, clusterDups] of clusters.entries()) {
|
|
546
|
+
if (clusterDups.length < 2) continue;
|
|
547
|
+
const files = getUniqueFiles(clusterDups);
|
|
548
|
+
const totalTokenCost = clusterDups.reduce((sum, d) => sum + d.tokenCost, 0);
|
|
549
|
+
const averageSimilarity = clusterDups.reduce((sum, d) => sum + d.similarity, 0) / clusterDups.length;
|
|
550
|
+
const severity = getHighestSeverity(clusterDups.map((d) => d.severity));
|
|
551
|
+
const patternType = getMostCommonPatternType(clusterDups);
|
|
552
|
+
const clusterInfo = getClusterInfo(clusterId, patternType, files.length);
|
|
553
|
+
result.push({
|
|
554
|
+
id: clusterId,
|
|
555
|
+
name: clusterInfo.name,
|
|
556
|
+
files,
|
|
557
|
+
patternType,
|
|
558
|
+
severity,
|
|
559
|
+
totalTokenCost,
|
|
560
|
+
averageSimilarity,
|
|
561
|
+
duplicateCount: clusterDups.length,
|
|
562
|
+
suggestion: clusterInfo.suggestion,
|
|
563
|
+
reason: clusterInfo.reason
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
return result.sort((a, b) => b.totalTokenCost - a.totalTokenCost);
|
|
567
|
+
}
|
|
568
|
+
function identifyCluster(dup) {
|
|
569
|
+
const file1 = dup.file1.toLowerCase();
|
|
570
|
+
const file2 = dup.file2.toLowerCase();
|
|
571
|
+
if ((file1.includes("/blog/") || file1.includes("/articles/")) && (file2.includes("/blog/") || file2.includes("/articles/"))) {
|
|
572
|
+
return "blog-seo-boilerplate";
|
|
573
|
+
}
|
|
574
|
+
if (file1.includes("/components/") && file2.includes("/components/") && dup.patternType === "component") {
|
|
575
|
+
const component1 = extractComponentName(file1);
|
|
576
|
+
const component2 = extractComponentName(file2);
|
|
577
|
+
if (component1 && component2 && areSimilarComponents(component1, component2)) {
|
|
578
|
+
return `component-${getComponentCategory(component1)}`;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
if ((file1.includes("/e2e/") || file1.includes(".e2e.")) && (file2.includes("/e2e/") || file2.includes(".e2e."))) {
|
|
582
|
+
return "e2e-test-patterns";
|
|
583
|
+
}
|
|
584
|
+
if (dup.patternType === "api-handler") {
|
|
585
|
+
return "api-handlers";
|
|
586
|
+
}
|
|
587
|
+
if (dup.patternType === "validator") {
|
|
588
|
+
return "validators";
|
|
589
|
+
}
|
|
590
|
+
if ((file1.includes("/scripts/") || file1.includes("/infra/")) && (file2.includes("/scripts/") || file2.includes("/infra/"))) {
|
|
591
|
+
return "infrastructure-scripts";
|
|
592
|
+
}
|
|
593
|
+
return `${dup.patternType}-patterns`;
|
|
594
|
+
}
|
|
595
|
+
function extractComponentName(filePath) {
|
|
596
|
+
const match = filePath.match(/\/([A-Z][a-zA-Z0-9]*)\.(tsx|jsx|ts|js)$/);
|
|
597
|
+
return match ? match[1] : null;
|
|
598
|
+
}
|
|
599
|
+
function areSimilarComponents(name1, name2) {
|
|
600
|
+
const category1 = getComponentCategory(name1);
|
|
601
|
+
const category2 = getComponentCategory(name2);
|
|
602
|
+
return category1 === category2;
|
|
603
|
+
}
|
|
604
|
+
function getComponentCategory(name) {
|
|
605
|
+
name = name.toLowerCase();
|
|
606
|
+
if (name.includes("button") || name.includes("btn")) return "button";
|
|
607
|
+
if (name.includes("card")) return "card";
|
|
608
|
+
if (name.includes("modal") || name.includes("dialog")) return "modal";
|
|
609
|
+
if (name.includes("form")) return "form";
|
|
610
|
+
if (name.includes("input") || name.includes("field")) return "input";
|
|
611
|
+
if (name.includes("table") || name.includes("grid")) return "table";
|
|
612
|
+
if (name.includes("nav") || name.includes("menu")) return "navigation";
|
|
613
|
+
if (name.includes("header") || name.includes("footer")) return "layout";
|
|
614
|
+
return "misc";
|
|
615
|
+
}
|
|
616
|
+
function getUniqueFiles(duplicates) {
|
|
617
|
+
const files = /* @__PURE__ */ new Set();
|
|
618
|
+
for (const dup of duplicates) {
|
|
619
|
+
files.add(dup.file1);
|
|
620
|
+
files.add(dup.file2);
|
|
621
|
+
}
|
|
622
|
+
return Array.from(files).sort();
|
|
623
|
+
}
|
|
624
|
+
function getHighestSeverity(severities) {
|
|
625
|
+
const order = {
|
|
626
|
+
critical: 5,
|
|
627
|
+
high: 4,
|
|
628
|
+
medium: 3,
|
|
629
|
+
low: 2,
|
|
630
|
+
info: 1
|
|
631
|
+
};
|
|
632
|
+
let highest = "info";
|
|
633
|
+
let highestValue = 0;
|
|
634
|
+
for (const sev of severities) {
|
|
635
|
+
if (order[sev] > highestValue) {
|
|
636
|
+
highestValue = order[sev];
|
|
637
|
+
highest = sev;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
return highest;
|
|
641
|
+
}
|
|
642
|
+
function getMostCommonPatternType(duplicates) {
|
|
643
|
+
const counts = /* @__PURE__ */ new Map();
|
|
644
|
+
for (const dup of duplicates) {
|
|
645
|
+
counts.set(dup.patternType, (counts.get(dup.patternType) || 0) + 1);
|
|
646
|
+
}
|
|
647
|
+
let mostCommon = "unknown";
|
|
648
|
+
let maxCount = 0;
|
|
649
|
+
for (const [type, count] of counts.entries()) {
|
|
650
|
+
if (count > maxCount) {
|
|
651
|
+
maxCount = count;
|
|
652
|
+
mostCommon = type;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
return mostCommon;
|
|
656
|
+
}
|
|
657
|
+
function getClusterInfo(clusterId, patternType, fileCount) {
|
|
658
|
+
const templates = {
|
|
659
|
+
"blog-seo-boilerplate": {
|
|
660
|
+
name: `Blog SEO Boilerplate (${fileCount} files)`,
|
|
661
|
+
suggestion: "Create BlogPageLayout component with SEO schema generator, breadcrumb component, and metadata helpers",
|
|
662
|
+
reason: "SEO boilerplate duplication increases maintenance burden and schema consistency risk"
|
|
663
|
+
},
|
|
664
|
+
"e2e-test-patterns": {
|
|
665
|
+
name: `E2E Test Patterns (${fileCount} files)`,
|
|
666
|
+
suggestion: "Extract page object helpers and common test utilities (waitFor, fillForm, etc.)",
|
|
667
|
+
reason: "Test helper extraction improves maintainability while preserving test independence"
|
|
668
|
+
},
|
|
669
|
+
"api-handlers": {
|
|
670
|
+
name: `API Handler Patterns (${fileCount} files)`,
|
|
671
|
+
suggestion: "Extract common middleware, error handling, and response formatting",
|
|
672
|
+
reason: "API handler duplication leads to inconsistent error handling and response formats"
|
|
673
|
+
},
|
|
674
|
+
"validators": {
|
|
675
|
+
name: `Validator Patterns (${fileCount} files)`,
|
|
676
|
+
suggestion: "Consolidate into shared schema validators (Zod/Yup) with reusable rules",
|
|
677
|
+
reason: "Validator duplication causes inconsistent validation and harder maintenance"
|
|
678
|
+
},
|
|
679
|
+
"infrastructure-scripts": {
|
|
680
|
+
name: `Infrastructure Scripts (${fileCount} files)`,
|
|
681
|
+
suggestion: "Extract common CLI parsing, file I/O, and error handling utilities",
|
|
682
|
+
reason: "Script duplication is often acceptable for one-off tasks, but common patterns can be shared"
|
|
683
|
+
},
|
|
684
|
+
"component-button": {
|
|
685
|
+
name: `Button Component Variants (${fileCount} files)`,
|
|
686
|
+
suggestion: "Create unified Button component with variant props",
|
|
687
|
+
reason: "Multiple button variants should share base styles and behavior"
|
|
688
|
+
},
|
|
689
|
+
"component-card": {
|
|
690
|
+
name: `Card Component Variants (${fileCount} files)`,
|
|
691
|
+
suggestion: "Create unified Card component with composition pattern",
|
|
692
|
+
reason: "Card variants should share layout structure and styling"
|
|
693
|
+
},
|
|
694
|
+
"component-modal": {
|
|
695
|
+
name: `Modal Component Variants (${fileCount} files)`,
|
|
696
|
+
suggestion: "Create base Modal component with customizable content",
|
|
697
|
+
reason: "Modal variants should share overlay, animation, and accessibility logic"
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
if (templates[clusterId]) {
|
|
701
|
+
return templates[clusterId];
|
|
702
|
+
}
|
|
703
|
+
return {
|
|
704
|
+
name: `${patternType} Cluster (${fileCount} files)`,
|
|
705
|
+
suggestion: `Extract common ${patternType} patterns into shared utilities`,
|
|
706
|
+
reason: `Multiple similar ${patternType} patterns detected across ${fileCount} files`
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
function filterClustersByImpact(clusters, minTokenCost = 1e3, minFileCount = 3) {
|
|
710
|
+
return clusters.filter(
|
|
711
|
+
(cluster) => cluster.totalTokenCost >= minTokenCost || cluster.files.length >= minFileCount
|
|
712
|
+
);
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// src/index.ts
|
|
716
|
+
function getRefactoringSuggestion(patternType, similarity) {
|
|
717
|
+
const baseMessages = {
|
|
718
|
+
"api-handler": "Extract common middleware or create a base handler class",
|
|
719
|
+
validator: "Consolidate validation logic into shared schema validators (Zod/Yup)",
|
|
720
|
+
utility: "Move to a shared utilities file and reuse across modules",
|
|
721
|
+
"class-method": "Consider inheritance or composition to share behavior",
|
|
722
|
+
component: "Extract shared logic into a custom hook or HOC",
|
|
723
|
+
function: "Extract into a shared helper function",
|
|
724
|
+
unknown: "Extract common logic into a reusable module"
|
|
725
|
+
};
|
|
726
|
+
const urgency = similarity > 0.95 ? " (CRITICAL: Nearly identical code)" : similarity > 0.9 ? " (HIGH: Very similar, refactor soon)" : "";
|
|
727
|
+
return baseMessages[patternType] + urgency;
|
|
728
|
+
}
|
|
729
|
+
async function getSmartDefaults(directory, userOptions) {
|
|
730
|
+
if (userOptions.useSmartDefaults === false) {
|
|
731
|
+
return {
|
|
732
|
+
rootDir: directory,
|
|
733
|
+
minSimilarity: 0.6,
|
|
734
|
+
minLines: 8,
|
|
735
|
+
batchSize: 100,
|
|
736
|
+
approx: true,
|
|
737
|
+
minSharedTokens: 12,
|
|
738
|
+
maxCandidatesPerBlock: 5,
|
|
739
|
+
streamResults: false,
|
|
740
|
+
severity: "all",
|
|
741
|
+
includeTests: false
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
const scanOptions = {
|
|
745
|
+
rootDir: directory,
|
|
746
|
+
include: userOptions.include || ["**/*.{ts,tsx,js,jsx,py,java}"],
|
|
747
|
+
exclude: userOptions.exclude
|
|
748
|
+
};
|
|
749
|
+
const { scanFiles: scanFiles2 } = await import("@aiready/core");
|
|
750
|
+
const files = await scanFiles2(scanOptions);
|
|
751
|
+
const estimatedBlocks = files.length * 3;
|
|
752
|
+
const maxCandidatesPerBlock = Math.max(3, Math.min(10, Math.floor(3e4 / estimatedBlocks)));
|
|
753
|
+
const minSimilarity = Math.min(0.75, 0.5 + estimatedBlocks / 1e4 * 0.25);
|
|
754
|
+
const minLines = Math.max(6, Math.min(12, 6 + Math.floor(estimatedBlocks / 2e3)));
|
|
755
|
+
const minSharedTokens = Math.max(10, Math.min(20, 10 + Math.floor(estimatedBlocks / 2e3)));
|
|
756
|
+
const batchSize = estimatedBlocks > 1e3 ? 200 : 100;
|
|
757
|
+
const severity = estimatedBlocks > 5e3 ? "high" : "all";
|
|
758
|
+
let defaults = {
|
|
759
|
+
rootDir: directory,
|
|
760
|
+
minSimilarity,
|
|
761
|
+
minLines,
|
|
762
|
+
batchSize,
|
|
763
|
+
approx: true,
|
|
764
|
+
minSharedTokens,
|
|
765
|
+
maxCandidatesPerBlock,
|
|
766
|
+
streamResults: false,
|
|
767
|
+
severity,
|
|
768
|
+
includeTests: false
|
|
769
|
+
};
|
|
770
|
+
const result = { ...defaults };
|
|
771
|
+
for (const [key, value] of Object.entries(defaults)) {
|
|
772
|
+
if (key in userOptions && userOptions[key] !== void 0) {
|
|
773
|
+
result[key] = userOptions[key];
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
return result;
|
|
777
|
+
}
|
|
778
|
+
function logConfiguration(config, estimatedBlocks) {
|
|
779
|
+
console.log("\u{1F4CB} Configuration:");
|
|
780
|
+
console.log(` Repository size: ~${estimatedBlocks} code blocks`);
|
|
781
|
+
console.log(` Similarity threshold: ${config.minSimilarity}`);
|
|
782
|
+
console.log(` Minimum lines: ${config.minLines}`);
|
|
783
|
+
console.log(` Approximate mode: ${config.approx ? "enabled" : "disabled"}`);
|
|
784
|
+
console.log(` Max candidates per block: ${config.maxCandidatesPerBlock}`);
|
|
785
|
+
console.log(` Min shared tokens: ${config.minSharedTokens}`);
|
|
786
|
+
console.log(` Severity filter: ${config.severity}`);
|
|
787
|
+
console.log(` Include tests: ${config.includeTests}`);
|
|
788
|
+
console.log("");
|
|
789
|
+
}
|
|
790
|
+
async function analyzePatterns(options) {
|
|
791
|
+
const smartDefaults = await getSmartDefaults(options.rootDir || ".", options);
|
|
792
|
+
const finalOptions = { ...smartDefaults, ...options };
|
|
793
|
+
const {
|
|
794
|
+
minSimilarity = 0.4,
|
|
795
|
+
minLines = 5,
|
|
796
|
+
batchSize = 100,
|
|
797
|
+
approx = true,
|
|
798
|
+
minSharedTokens = 8,
|
|
799
|
+
maxCandidatesPerBlock = 100,
|
|
800
|
+
streamResults = false,
|
|
801
|
+
severity = "all",
|
|
802
|
+
includeTests = false,
|
|
803
|
+
groupByFilePair = true,
|
|
804
|
+
createClusters = true,
|
|
805
|
+
minClusterTokenCost = 1e3,
|
|
806
|
+
minClusterFiles = 3,
|
|
807
|
+
...scanOptions
|
|
808
|
+
} = finalOptions;
|
|
809
|
+
const { scanFiles: scanFiles2 } = await import("@aiready/core");
|
|
810
|
+
const files = await scanFiles2(scanOptions);
|
|
811
|
+
const estimatedBlocks = files.length * 3;
|
|
812
|
+
logConfiguration(finalOptions, estimatedBlocks);
|
|
813
|
+
const results = [];
|
|
814
|
+
const fileContents = await Promise.all(
|
|
815
|
+
files.map(async (file) => ({
|
|
816
|
+
file,
|
|
817
|
+
content: await readFileContent(file)
|
|
818
|
+
}))
|
|
819
|
+
);
|
|
820
|
+
const duplicates = await detectDuplicatePatterns(fileContents, {
|
|
821
|
+
minSimilarity,
|
|
822
|
+
minLines,
|
|
823
|
+
batchSize,
|
|
824
|
+
approx,
|
|
825
|
+
minSharedTokens,
|
|
826
|
+
maxCandidatesPerBlock,
|
|
827
|
+
streamResults
|
|
828
|
+
});
|
|
829
|
+
for (const file of files) {
|
|
830
|
+
const fileDuplicates = duplicates.filter(
|
|
831
|
+
(dup) => dup.file1 === file || dup.file2 === file
|
|
832
|
+
);
|
|
833
|
+
const issues = fileDuplicates.map((dup) => {
|
|
834
|
+
const otherFile = dup.file1 === file ? dup.file2 : dup.file1;
|
|
835
|
+
const severity2 = dup.similarity > 0.95 ? "critical" : dup.similarity > 0.9 ? "major" : "minor";
|
|
836
|
+
return {
|
|
837
|
+
type: "duplicate-pattern",
|
|
838
|
+
severity: severity2,
|
|
839
|
+
message: `${dup.patternType} pattern ${Math.round(dup.similarity * 100)}% similar to ${otherFile} (${dup.tokenCost} tokens wasted)`,
|
|
840
|
+
location: {
|
|
841
|
+
file,
|
|
842
|
+
line: dup.file1 === file ? dup.line1 : dup.line2
|
|
843
|
+
},
|
|
844
|
+
suggestion: getRefactoringSuggestion(dup.patternType, dup.similarity)
|
|
845
|
+
};
|
|
846
|
+
});
|
|
847
|
+
let filteredIssues = issues;
|
|
848
|
+
if (severity !== "all") {
|
|
849
|
+
const severityMap = {
|
|
850
|
+
critical: ["critical"],
|
|
851
|
+
high: ["critical", "major"],
|
|
852
|
+
medium: ["critical", "major", "minor"]
|
|
853
|
+
};
|
|
854
|
+
const allowedSeverities = severityMap[severity] || ["critical", "major", "minor"];
|
|
855
|
+
filteredIssues = issues.filter((issue) => allowedSeverities.includes(issue.severity));
|
|
856
|
+
}
|
|
857
|
+
const totalTokenCost = fileDuplicates.reduce(
|
|
858
|
+
(sum, dup) => sum + dup.tokenCost,
|
|
859
|
+
0
|
|
860
|
+
);
|
|
861
|
+
results.push({
|
|
862
|
+
fileName: file,
|
|
863
|
+
issues: filteredIssues,
|
|
864
|
+
metrics: {
|
|
865
|
+
tokenCost: totalTokenCost,
|
|
866
|
+
consistencyScore: Math.max(0, 1 - fileDuplicates.length * 0.1)
|
|
867
|
+
}
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
let groups;
|
|
871
|
+
let clusters;
|
|
872
|
+
if (groupByFilePair) {
|
|
873
|
+
groups = groupDuplicatesByFilePair(duplicates);
|
|
874
|
+
console.log(`
|
|
875
|
+
\u2705 Grouped ${duplicates.length} duplicates into ${groups.length} file pairs`);
|
|
876
|
+
}
|
|
877
|
+
if (createClusters) {
|
|
878
|
+
const allClusters = createRefactorClusters(duplicates);
|
|
879
|
+
clusters = filterClustersByImpact(allClusters, minClusterTokenCost, minClusterFiles);
|
|
880
|
+
console.log(`\u2705 Created ${clusters.length} refactor clusters (${allClusters.length - clusters.length} filtered by impact)`);
|
|
881
|
+
}
|
|
882
|
+
return { results, duplicates, files, groups, clusters };
|
|
883
|
+
}
|
|
884
|
+
function generateSummary(results) {
|
|
885
|
+
const allIssues = results.flatMap((r) => r.issues);
|
|
886
|
+
const totalTokenCost = results.reduce(
|
|
887
|
+
(sum, r) => sum + (r.metrics.tokenCost || 0),
|
|
888
|
+
0
|
|
889
|
+
);
|
|
890
|
+
const patternsByType = {
|
|
891
|
+
"api-handler": 0,
|
|
892
|
+
validator: 0,
|
|
893
|
+
utility: 0,
|
|
894
|
+
"class-method": 0,
|
|
895
|
+
component: 0,
|
|
896
|
+
function: 0,
|
|
897
|
+
unknown: 0
|
|
898
|
+
};
|
|
899
|
+
allIssues.forEach((issue) => {
|
|
900
|
+
const match = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
|
|
901
|
+
if (match) {
|
|
902
|
+
const type = match[1];
|
|
903
|
+
patternsByType[type] = (patternsByType[type] || 0) + 1;
|
|
904
|
+
}
|
|
905
|
+
});
|
|
906
|
+
const topDuplicates = allIssues.slice(0, 10).map((issue) => {
|
|
907
|
+
const similarityMatch = issue.message.match(/(\d+)% similar/);
|
|
908
|
+
const tokenMatch = issue.message.match(/\((\d+) tokens/);
|
|
909
|
+
const typeMatch = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
|
|
910
|
+
const fileMatch = issue.message.match(/similar to (.+?) \(/);
|
|
911
|
+
return {
|
|
912
|
+
files: [
|
|
913
|
+
{
|
|
914
|
+
path: issue.location.file,
|
|
915
|
+
startLine: issue.location.line,
|
|
916
|
+
endLine: 0
|
|
917
|
+
// Not available from Issue
|
|
918
|
+
},
|
|
919
|
+
{
|
|
920
|
+
path: fileMatch?.[1] || "unknown",
|
|
921
|
+
startLine: 0,
|
|
922
|
+
// Not available from Issue
|
|
923
|
+
endLine: 0
|
|
924
|
+
// Not available from Issue
|
|
925
|
+
}
|
|
926
|
+
],
|
|
927
|
+
similarity: similarityMatch ? parseInt(similarityMatch[1]) / 100 : 0,
|
|
928
|
+
patternType: typeMatch?.[1] || "unknown",
|
|
929
|
+
tokenCost: tokenMatch ? parseInt(tokenMatch[1]) : 0
|
|
930
|
+
};
|
|
931
|
+
});
|
|
932
|
+
return {
|
|
933
|
+
totalPatterns: allIssues.length,
|
|
934
|
+
totalTokenCost,
|
|
935
|
+
patternsByType,
|
|
936
|
+
topDuplicates
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
export {
|
|
941
|
+
calculateSeverity,
|
|
942
|
+
getSeverityLabel,
|
|
943
|
+
filterBySeverity,
|
|
944
|
+
detectDuplicatePatterns,
|
|
945
|
+
getSmartDefaults,
|
|
946
|
+
analyzePatterns,
|
|
947
|
+
generateSummary
|
|
948
|
+
};
|