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