@aiready/pattern-detect 0.1.2 → 0.1.3

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.
@@ -0,0 +1,400 @@
1
+ // src/index.ts
2
+ import { scanFiles, readFileContent } from "@aiready/core";
3
+
4
+ // src/detector.ts
5
+ import { similarityScore, estimateTokens } from "@aiready/core";
6
+ function categorizePattern(code) {
7
+ const lower = code.toLowerCase();
8
+ 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")) {
9
+ return "api-handler";
10
+ }
11
+ if (lower.includes("validate") || lower.includes("schema") || lower.includes("zod") || lower.includes("yup") || lower.includes("if") && lower.includes("throw")) {
12
+ return "validator";
13
+ }
14
+ if (lower.includes("return (") || lower.includes("jsx") || lower.includes("component") || lower.includes("props")) {
15
+ return "component";
16
+ }
17
+ if (lower.includes("class ") || lower.includes("this.")) {
18
+ return "class-method";
19
+ }
20
+ if (lower.includes("return ") && !lower.includes("this") && !lower.includes("new ")) {
21
+ return "utility";
22
+ }
23
+ if (lower.includes("function") || lower.includes("=>")) {
24
+ return "function";
25
+ }
26
+ return "unknown";
27
+ }
28
+ function extractCodeBlocks(content, minLines) {
29
+ const lines = content.split("\n");
30
+ const blocks = [];
31
+ let currentBlock = [];
32
+ let blockStart = 0;
33
+ let braceDepth = 0;
34
+ let inFunction = false;
35
+ for (let i = 0; i < lines.length; i++) {
36
+ const line = lines[i];
37
+ const trimmed = line.trim();
38
+ 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))) {
39
+ inFunction = true;
40
+ blockStart = i;
41
+ }
42
+ for (const char of line) {
43
+ if (char === "{") braceDepth++;
44
+ if (char === "}") braceDepth--;
45
+ }
46
+ if (inFunction) {
47
+ currentBlock.push(line);
48
+ }
49
+ if (inFunction && braceDepth === 0 && currentBlock.length >= minLines) {
50
+ const blockContent = currentBlock.join("\n");
51
+ const linesOfCode = currentBlock.filter(
52
+ (l) => l.trim() && !l.trim().startsWith("//")
53
+ ).length;
54
+ blocks.push({
55
+ content: blockContent,
56
+ startLine: blockStart + 1,
57
+ patternType: categorizePattern(blockContent),
58
+ linesOfCode
59
+ });
60
+ currentBlock = [];
61
+ inFunction = false;
62
+ } else if (inFunction && braceDepth === 0) {
63
+ currentBlock = [];
64
+ inFunction = false;
65
+ }
66
+ }
67
+ return blocks;
68
+ }
69
+ function normalizeCode(code) {
70
+ 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();
71
+ }
72
+ function jaccardSimilarity(tokens1, tokens2) {
73
+ const set1 = new Set(tokens1);
74
+ const set2 = new Set(tokens2);
75
+ let intersection = 0;
76
+ for (const token of set1) {
77
+ if (set2.has(token)) intersection++;
78
+ }
79
+ const union = set1.size + set2.size - intersection;
80
+ return union === 0 ? 0 : intersection / union;
81
+ }
82
+ function calculateSimilarity(block1, block2) {
83
+ const norm1 = normalizeCode(block1);
84
+ const norm2 = normalizeCode(block2);
85
+ const baseSimilarity = similarityScore(norm1, norm2);
86
+ const tokens1 = norm1.split(/[\s(){}[\];,]+/).filter(Boolean);
87
+ const tokens2 = norm2.split(/[\s(){}[\];,]+/).filter(Boolean);
88
+ const tokenSimilarity = similarityScore(tokens1.join(" "), tokens2.join(" "));
89
+ return baseSimilarity * 0.4 + tokenSimilarity * 0.6;
90
+ }
91
+ async function detectDuplicatePatterns(files, options) {
92
+ const {
93
+ minSimilarity,
94
+ minLines,
95
+ maxBlocks = 500,
96
+ batchSize = 100,
97
+ approx = true,
98
+ minSharedTokens = 8,
99
+ maxCandidatesPerBlock = 100,
100
+ fastMode = true,
101
+ maxComparisons = 5e4,
102
+ // Cap at 50K comparisons by default
103
+ streamResults = false
104
+ } = options;
105
+ const duplicates = [];
106
+ let allBlocks = files.flatMap(
107
+ (file) => extractCodeBlocks(file.content, minLines).map((block) => ({
108
+ ...block,
109
+ file: file.file,
110
+ normalized: normalizeCode(block.content),
111
+ tokenCost: estimateTokens(block.content)
112
+ }))
113
+ );
114
+ console.log(`Extracted ${allBlocks.length} code blocks for analysis`);
115
+ if (allBlocks.length > maxBlocks) {
116
+ console.log(`\u26A0\uFE0F Limiting to ${maxBlocks} blocks (sorted by size) to prevent memory issues`);
117
+ console.log(` Use --max-blocks to increase limit or --min-lines to filter smaller blocks`);
118
+ allBlocks = allBlocks.sort((a, b) => b.linesOfCode - a.linesOfCode).slice(0, maxBlocks);
119
+ }
120
+ const stopwords = /* @__PURE__ */ new Set([
121
+ "return",
122
+ "const",
123
+ "let",
124
+ "var",
125
+ "function",
126
+ "class",
127
+ "new",
128
+ "if",
129
+ "else",
130
+ "for",
131
+ "while",
132
+ "async",
133
+ "await",
134
+ "try",
135
+ "catch",
136
+ "switch",
137
+ "case",
138
+ "default",
139
+ "import",
140
+ "export",
141
+ "from",
142
+ "true",
143
+ "false",
144
+ "null",
145
+ "undefined",
146
+ "this"
147
+ ]);
148
+ const tokenize = (norm) => norm.split(/[\s(){}\[\];,\.]+/).filter((t) => t && t.length >= 3 && !stopwords.has(t.toLowerCase()));
149
+ const blockTokens = allBlocks.map((b) => tokenize(b.normalized));
150
+ const invertedIndex = /* @__PURE__ */ new Map();
151
+ if (approx) {
152
+ for (let i = 0; i < blockTokens.length; i++) {
153
+ for (const tok of blockTokens[i]) {
154
+ let arr = invertedIndex.get(tok);
155
+ if (!arr) {
156
+ arr = [];
157
+ invertedIndex.set(tok, arr);
158
+ }
159
+ arr.push(i);
160
+ }
161
+ }
162
+ }
163
+ const totalComparisons = approx ? void 0 : allBlocks.length * (allBlocks.length - 1) / 2;
164
+ if (totalComparisons !== void 0) {
165
+ console.log(`Processing ${totalComparisons.toLocaleString()} comparisons in batches...`);
166
+ } else {
167
+ console.log(`Using approximate candidate selection to reduce comparisons...`);
168
+ }
169
+ let comparisonsProcessed = 0;
170
+ let comparisonsBudgetExhausted = false;
171
+ const startTime = Date.now();
172
+ for (let i = 0; i < allBlocks.length; i++) {
173
+ if (maxComparisons && comparisonsProcessed >= maxComparisons) {
174
+ comparisonsBudgetExhausted = true;
175
+ break;
176
+ }
177
+ if (i % batchSize === 0 && i > 0) {
178
+ const elapsed = ((Date.now() - startTime) / 1e3).toFixed(1);
179
+ const duplicatesFound = duplicates.length;
180
+ if (totalComparisons !== void 0) {
181
+ const progress = (comparisonsProcessed / totalComparisons * 100).toFixed(1);
182
+ const remaining = totalComparisons - comparisonsProcessed;
183
+ const rate = comparisonsProcessed / parseFloat(elapsed);
184
+ const eta = remaining > 0 ? (remaining / rate).toFixed(0) : 0;
185
+ console.log(` ${progress}% (${comparisonsProcessed.toLocaleString()}/${totalComparisons.toLocaleString()} comparisons, ${elapsed}s elapsed, ~${eta}s remaining, ${duplicatesFound} duplicates)`);
186
+ } else {
187
+ console.log(` Processed ${i.toLocaleString()}/${allBlocks.length} blocks (${elapsed}s elapsed, ${duplicatesFound} duplicates)`);
188
+ }
189
+ await new Promise((resolve) => setImmediate(resolve));
190
+ }
191
+ const block1 = allBlocks[i];
192
+ let candidates = null;
193
+ if (approx) {
194
+ const counts = /* @__PURE__ */ new Map();
195
+ for (const tok of blockTokens[i]) {
196
+ const ids = invertedIndex.get(tok);
197
+ if (!ids) continue;
198
+ for (const j of ids) {
199
+ if (j <= i) continue;
200
+ if (allBlocks[j].file === block1.file) continue;
201
+ counts.set(j, (counts.get(j) || 0) + 1);
202
+ }
203
+ }
204
+ candidates = Array.from(counts.entries()).filter(([, shared]) => shared >= minSharedTokens).sort((a, b) => b[1] - a[1]).slice(0, maxCandidatesPerBlock).map(([j, shared]) => ({ j, shared }));
205
+ }
206
+ if (approx && candidates) {
207
+ for (const { j } of candidates) {
208
+ if (maxComparisons && comparisonsProcessed >= maxComparisons) break;
209
+ comparisonsProcessed++;
210
+ const block2 = allBlocks[j];
211
+ const similarity = fastMode ? jaccardSimilarity(blockTokens[i], blockTokens[j]) : calculateSimilarity(block1.content, block2.content);
212
+ if (similarity >= minSimilarity) {
213
+ const duplicate = {
214
+ file1: block1.file,
215
+ file2: block2.file,
216
+ line1: block1.startLine,
217
+ line2: block2.startLine,
218
+ similarity,
219
+ snippet: block1.content.split("\n").slice(0, 5).join("\n") + "\n...",
220
+ patternType: block1.patternType,
221
+ tokenCost: block1.tokenCost + block2.tokenCost,
222
+ linesOfCode: block1.linesOfCode
223
+ };
224
+ duplicates.push(duplicate);
225
+ if (streamResults) {
226
+ console.log(`
227
+ \u2705 Found: ${duplicate.patternType} ${Math.round(similarity * 100)}% similar`);
228
+ console.log(` ${duplicate.file1}:${duplicate.line1} \u21D4 ${duplicate.file2}:${duplicate.line2}`);
229
+ console.log(` Token cost: ${duplicate.tokenCost.toLocaleString()}`);
230
+ }
231
+ }
232
+ }
233
+ } else {
234
+ for (let j = i + 1; j < allBlocks.length; j++) {
235
+ if (maxComparisons && comparisonsProcessed >= maxComparisons) break;
236
+ comparisonsProcessed++;
237
+ const block2 = allBlocks[j];
238
+ if (block1.file === block2.file) continue;
239
+ const similarity = fastMode ? jaccardSimilarity(blockTokens[i], blockTokens[j]) : calculateSimilarity(block1.content, block2.content);
240
+ if (similarity >= minSimilarity) {
241
+ const duplicate = {
242
+ file1: block1.file,
243
+ file2: block2.file,
244
+ line1: block1.startLine,
245
+ line2: block2.startLine,
246
+ similarity,
247
+ snippet: block1.content.split("\n").slice(0, 5).join("\n") + "\n...",
248
+ patternType: block1.patternType,
249
+ tokenCost: block1.tokenCost + block2.tokenCost,
250
+ linesOfCode: block1.linesOfCode
251
+ };
252
+ duplicates.push(duplicate);
253
+ if (streamResults) {
254
+ console.log(`
255
+ \u2705 Found: ${duplicate.patternType} ${Math.round(similarity * 100)}% similar`);
256
+ console.log(` ${duplicate.file1}:${duplicate.line1} \u21D4 ${duplicate.file2}:${duplicate.line2}`);
257
+ console.log(` Token cost: ${duplicate.tokenCost.toLocaleString()}`);
258
+ }
259
+ }
260
+ }
261
+ }
262
+ }
263
+ if (comparisonsBudgetExhausted) {
264
+ console.log(`\u26A0\uFE0F Comparison budget exhausted (${maxComparisons.toLocaleString()} comparisons). Use --max-comparisons to increase.`);
265
+ }
266
+ return duplicates.sort(
267
+ (a, b) => b.similarity - a.similarity || b.tokenCost - a.tokenCost
268
+ );
269
+ }
270
+
271
+ // src/index.ts
272
+ function getRefactoringSuggestion(patternType, similarity) {
273
+ const baseMessages = {
274
+ "api-handler": "Extract common middleware or create a base handler class",
275
+ validator: "Consolidate validation logic into shared schema validators (Zod/Yup)",
276
+ utility: "Move to a shared utilities file and reuse across modules",
277
+ "class-method": "Consider inheritance or composition to share behavior",
278
+ component: "Extract shared logic into a custom hook or HOC",
279
+ function: "Extract into a shared helper function",
280
+ unknown: "Extract common logic into a reusable module"
281
+ };
282
+ const urgency = similarity > 0.95 ? " (CRITICAL: Nearly identical code)" : similarity > 0.9 ? " (HIGH: Very similar, refactor soon)" : "";
283
+ return baseMessages[patternType] + urgency;
284
+ }
285
+ async function analyzePatterns(options) {
286
+ const {
287
+ minSimilarity = 0.65,
288
+ // Lower default for fast Jaccard mode (Levenshtein would be 0.85+)
289
+ minLines = 5,
290
+ maxBlocks = 500,
291
+ batchSize = 100,
292
+ approx = true,
293
+ minSharedTokens = 8,
294
+ maxCandidatesPerBlock = 100,
295
+ fastMode = true,
296
+ maxComparisons = 5e4,
297
+ streamResults = false,
298
+ ...scanOptions
299
+ } = options;
300
+ const files = await scanFiles(scanOptions);
301
+ const results = [];
302
+ const fileContents = await Promise.all(
303
+ files.map(async (file) => ({
304
+ file,
305
+ content: await readFileContent(file)
306
+ }))
307
+ );
308
+ const duplicates = await detectDuplicatePatterns(fileContents, {
309
+ minSimilarity,
310
+ minLines,
311
+ maxBlocks,
312
+ batchSize,
313
+ approx,
314
+ minSharedTokens,
315
+ maxCandidatesPerBlock,
316
+ fastMode,
317
+ maxComparisons,
318
+ streamResults
319
+ });
320
+ for (const file of files) {
321
+ const fileDuplicates = duplicates.filter(
322
+ (dup) => dup.file1 === file || dup.file2 === file
323
+ );
324
+ const issues = fileDuplicates.map((dup) => {
325
+ const otherFile = dup.file1 === file ? dup.file2 : dup.file1;
326
+ const severity = dup.similarity > 0.95 ? "critical" : dup.similarity > 0.9 ? "major" : "minor";
327
+ return {
328
+ type: "duplicate-pattern",
329
+ severity,
330
+ message: `${dup.patternType} pattern ${Math.round(dup.similarity * 100)}% similar to ${otherFile} (${dup.tokenCost} tokens wasted)`,
331
+ location: {
332
+ file,
333
+ line: dup.file1 === file ? dup.line1 : dup.line2
334
+ },
335
+ suggestion: getRefactoringSuggestion(dup.patternType, dup.similarity)
336
+ };
337
+ });
338
+ const totalTokenCost = fileDuplicates.reduce(
339
+ (sum, dup) => sum + dup.tokenCost,
340
+ 0
341
+ );
342
+ results.push({
343
+ fileName: file,
344
+ issues,
345
+ metrics: {
346
+ tokenCost: totalTokenCost,
347
+ consistencyScore: Math.max(0, 1 - fileDuplicates.length * 0.1)
348
+ }
349
+ });
350
+ }
351
+ return results;
352
+ }
353
+ function generateSummary(results) {
354
+ const allIssues = results.flatMap((r) => r.issues);
355
+ const totalTokenCost = results.reduce(
356
+ (sum, r) => sum + (r.metrics.tokenCost || 0),
357
+ 0
358
+ );
359
+ const patternsByType = {
360
+ "api-handler": 0,
361
+ validator: 0,
362
+ utility: 0,
363
+ "class-method": 0,
364
+ component: 0,
365
+ function: 0,
366
+ unknown: 0
367
+ };
368
+ allIssues.forEach((issue) => {
369
+ const match = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
370
+ if (match) {
371
+ const type = match[1];
372
+ patternsByType[type] = (patternsByType[type] || 0) + 1;
373
+ }
374
+ });
375
+ const topDuplicates = allIssues.slice(0, 10).map((issue) => {
376
+ const similarityMatch = issue.message.match(/(\d+)% similar/);
377
+ const tokenMatch = issue.message.match(/\((\d+) tokens/);
378
+ const typeMatch = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
379
+ const fileMatch = issue.message.match(/similar to (.+?) \(/);
380
+ return {
381
+ file1: issue.location.file,
382
+ file2: fileMatch?.[1] || "unknown",
383
+ similarity: similarityMatch ? parseInt(similarityMatch[1]) / 100 : 0,
384
+ patternType: typeMatch?.[1] || "unknown",
385
+ tokenCost: tokenMatch ? parseInt(tokenMatch[1]) : 0
386
+ };
387
+ });
388
+ return {
389
+ totalPatterns: allIssues.length,
390
+ totalTokenCost,
391
+ patternsByType,
392
+ topDuplicates
393
+ };
394
+ }
395
+
396
+ export {
397
+ detectDuplicatePatterns,
398
+ analyzePatterns,
399
+ generateSummary
400
+ };
@@ -0,0 +1,245 @@
1
+ // src/index.ts
2
+ import { scanFiles, readFileContent } from "@aiready/core";
3
+
4
+ // src/detector.ts
5
+ import { similarityScore, estimateTokens } from "@aiready/core";
6
+ function categorizePattern(code) {
7
+ const lower = code.toLowerCase();
8
+ 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")) {
9
+ return "api-handler";
10
+ }
11
+ if (lower.includes("validate") || lower.includes("schema") || lower.includes("zod") || lower.includes("yup") || lower.includes("if") && lower.includes("throw")) {
12
+ return "validator";
13
+ }
14
+ if (lower.includes("return (") || lower.includes("jsx") || lower.includes("component") || lower.includes("props")) {
15
+ return "component";
16
+ }
17
+ if (lower.includes("class ") || lower.includes("this.")) {
18
+ return "class-method";
19
+ }
20
+ if (lower.includes("return ") && !lower.includes("this") && !lower.includes("new ")) {
21
+ return "utility";
22
+ }
23
+ if (lower.includes("function") || lower.includes("=>")) {
24
+ return "function";
25
+ }
26
+ return "unknown";
27
+ }
28
+ function extractCodeBlocks(content, minLines) {
29
+ const lines = content.split("\n");
30
+ const blocks = [];
31
+ let currentBlock = [];
32
+ let blockStart = 0;
33
+ let braceDepth = 0;
34
+ let inFunction = false;
35
+ for (let i = 0; i < lines.length; i++) {
36
+ const line = lines[i];
37
+ const trimmed = line.trim();
38
+ 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))) {
39
+ inFunction = true;
40
+ blockStart = i;
41
+ }
42
+ for (const char of line) {
43
+ if (char === "{") braceDepth++;
44
+ if (char === "}") braceDepth--;
45
+ }
46
+ if (inFunction) {
47
+ currentBlock.push(line);
48
+ }
49
+ if (inFunction && braceDepth === 0 && currentBlock.length >= minLines) {
50
+ const blockContent = currentBlock.join("\n");
51
+ const linesOfCode = currentBlock.filter(
52
+ (l) => l.trim() && !l.trim().startsWith("//")
53
+ ).length;
54
+ blocks.push({
55
+ content: blockContent,
56
+ startLine: blockStart + 1,
57
+ patternType: categorizePattern(blockContent),
58
+ linesOfCode
59
+ });
60
+ currentBlock = [];
61
+ inFunction = false;
62
+ } else if (inFunction && braceDepth === 0) {
63
+ currentBlock = [];
64
+ inFunction = false;
65
+ }
66
+ }
67
+ return blocks;
68
+ }
69
+ function normalizeCode(code) {
70
+ 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();
71
+ }
72
+ function calculateSimilarity(block1, block2) {
73
+ const norm1 = normalizeCode(block1);
74
+ const norm2 = normalizeCode(block2);
75
+ const baseSimilarity = similarityScore(norm1, norm2);
76
+ const tokens1 = norm1.split(/[\s(){}[\];,]+/).filter(Boolean);
77
+ const tokens2 = norm2.split(/[\s(){}[\];,]+/).filter(Boolean);
78
+ const tokenSimilarity = similarityScore(tokens1.join(" "), tokens2.join(" "));
79
+ return baseSimilarity * 0.4 + tokenSimilarity * 0.6;
80
+ }
81
+ async function detectDuplicatePatterns(files, options) {
82
+ const { minSimilarity, minLines, maxBlocks = 500, batchSize = 100 } = options;
83
+ const duplicates = [];
84
+ let allBlocks = files.flatMap(
85
+ (file) => extractCodeBlocks(file.content, minLines).map((block) => ({
86
+ ...block,
87
+ file: file.file,
88
+ normalized: normalizeCode(block.content),
89
+ tokenCost: estimateTokens(block.content)
90
+ }))
91
+ );
92
+ console.log(`Extracted ${allBlocks.length} code blocks for analysis`);
93
+ if (allBlocks.length > maxBlocks) {
94
+ console.log(`\u26A0\uFE0F Limiting to ${maxBlocks} blocks (sorted by size) to prevent memory issues`);
95
+ console.log(` Use --max-blocks to increase limit or --min-lines to filter smaller blocks`);
96
+ allBlocks = allBlocks.sort((a, b) => b.linesOfCode - a.linesOfCode).slice(0, maxBlocks);
97
+ }
98
+ const totalComparisons = allBlocks.length * (allBlocks.length - 1) / 2;
99
+ console.log(`Processing ${totalComparisons.toLocaleString()} comparisons in batches...`);
100
+ let comparisonsProcessed = 0;
101
+ const startTime = Date.now();
102
+ for (let i = 0; i < allBlocks.length; i++) {
103
+ if (i % batchSize === 0 && i > 0) {
104
+ const progress = (comparisonsProcessed / totalComparisons * 100).toFixed(1);
105
+ const elapsed = ((Date.now() - startTime) / 1e3).toFixed(1);
106
+ console.log(` ${progress}% complete (${comparisonsProcessed.toLocaleString()}/${totalComparisons.toLocaleString()} comparisons, ${elapsed}s elapsed)`);
107
+ await new Promise((resolve) => setImmediate(resolve));
108
+ }
109
+ for (let j = i + 1; j < allBlocks.length; j++) {
110
+ comparisonsProcessed++;
111
+ const block1 = allBlocks[i];
112
+ const block2 = allBlocks[j];
113
+ if (block1.file === block2.file) continue;
114
+ const similarity = calculateSimilarity(block1.content, block2.content);
115
+ if (similarity >= minSimilarity) {
116
+ duplicates.push({
117
+ file1: block1.file,
118
+ file2: block2.file,
119
+ line1: block1.startLine,
120
+ line2: block2.startLine,
121
+ similarity,
122
+ snippet: block1.content.split("\n").slice(0, 5).join("\n") + "\n...",
123
+ patternType: block1.patternType,
124
+ tokenCost: block1.tokenCost + block2.tokenCost,
125
+ linesOfCode: block1.linesOfCode
126
+ });
127
+ }
128
+ }
129
+ }
130
+ return duplicates.sort(
131
+ (a, b) => b.similarity - a.similarity || b.tokenCost - a.tokenCost
132
+ );
133
+ }
134
+
135
+ // src/index.ts
136
+ function getRefactoringSuggestion(patternType, similarity) {
137
+ const baseMessages = {
138
+ "api-handler": "Extract common middleware or create a base handler class",
139
+ validator: "Consolidate validation logic into shared schema validators (Zod/Yup)",
140
+ utility: "Move to a shared utilities file and reuse across modules",
141
+ "class-method": "Consider inheritance or composition to share behavior",
142
+ component: "Extract shared logic into a custom hook or HOC",
143
+ function: "Extract into a shared helper function",
144
+ unknown: "Extract common logic into a reusable module"
145
+ };
146
+ const urgency = similarity > 0.95 ? " (CRITICAL: Nearly identical code)" : similarity > 0.9 ? " (HIGH: Very similar, refactor soon)" : "";
147
+ return baseMessages[patternType] + urgency;
148
+ }
149
+ async function analyzePatterns(options) {
150
+ const { minSimilarity = 0.85, minLines = 5, maxBlocks = 500, batchSize = 100, ...scanOptions } = options;
151
+ const files = await scanFiles(scanOptions);
152
+ const results = [];
153
+ const fileContents = await Promise.all(
154
+ files.map(async (file) => ({
155
+ file,
156
+ content: await readFileContent(file)
157
+ }))
158
+ );
159
+ const duplicates = await detectDuplicatePatterns(fileContents, {
160
+ minSimilarity,
161
+ minLines,
162
+ maxBlocks,
163
+ batchSize
164
+ });
165
+ for (const file of files) {
166
+ const fileDuplicates = duplicates.filter(
167
+ (dup) => dup.file1 === file || dup.file2 === file
168
+ );
169
+ const issues = fileDuplicates.map((dup) => {
170
+ const otherFile = dup.file1 === file ? dup.file2 : dup.file1;
171
+ const severity = dup.similarity > 0.95 ? "critical" : dup.similarity > 0.9 ? "major" : "minor";
172
+ return {
173
+ type: "duplicate-pattern",
174
+ severity,
175
+ message: `${dup.patternType} pattern ${Math.round(dup.similarity * 100)}% similar to ${otherFile} (${dup.tokenCost} tokens wasted)`,
176
+ location: {
177
+ file,
178
+ line: dup.file1 === file ? dup.line1 : dup.line2
179
+ },
180
+ suggestion: getRefactoringSuggestion(dup.patternType, dup.similarity)
181
+ };
182
+ });
183
+ const totalTokenCost = fileDuplicates.reduce(
184
+ (sum, dup) => sum + dup.tokenCost,
185
+ 0
186
+ );
187
+ results.push({
188
+ fileName: file,
189
+ issues,
190
+ metrics: {
191
+ tokenCost: totalTokenCost,
192
+ consistencyScore: Math.max(0, 1 - fileDuplicates.length * 0.1)
193
+ }
194
+ });
195
+ }
196
+ return results;
197
+ }
198
+ function generateSummary(results) {
199
+ const allIssues = results.flatMap((r) => r.issues);
200
+ const totalTokenCost = results.reduce(
201
+ (sum, r) => sum + (r.metrics.tokenCost || 0),
202
+ 0
203
+ );
204
+ const patternsByType = {
205
+ "api-handler": 0,
206
+ validator: 0,
207
+ utility: 0,
208
+ "class-method": 0,
209
+ component: 0,
210
+ function: 0,
211
+ unknown: 0
212
+ };
213
+ allIssues.forEach((issue) => {
214
+ const match = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
215
+ if (match) {
216
+ const type = match[1];
217
+ patternsByType[type] = (patternsByType[type] || 0) + 1;
218
+ }
219
+ });
220
+ const topDuplicates = allIssues.slice(0, 10).map((issue) => {
221
+ const similarityMatch = issue.message.match(/(\d+)% similar/);
222
+ const tokenMatch = issue.message.match(/\((\d+) tokens/);
223
+ const typeMatch = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
224
+ const fileMatch = issue.message.match(/similar to (.+?) \(/);
225
+ return {
226
+ file1: issue.location.file,
227
+ file2: fileMatch?.[1] || "unknown",
228
+ similarity: similarityMatch ? parseInt(similarityMatch[1]) / 100 : 0,
229
+ patternType: typeMatch?.[1] || "unknown",
230
+ tokenCost: tokenMatch ? parseInt(tokenMatch[1]) : 0
231
+ };
232
+ });
233
+ return {
234
+ totalPatterns: allIssues.length,
235
+ totalTokenCost,
236
+ patternsByType,
237
+ topDuplicates
238
+ };
239
+ }
240
+
241
+ export {
242
+ detectDuplicatePatterns,
243
+ analyzePatterns,
244
+ generateSummary
245
+ };