@aiready/pattern-detect 0.1.3 → 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.
@@ -1,227 +0,0 @@
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
- function detectDuplicatePatterns(files, options) {
82
- const { minSimilarity, minLines } = options;
83
- const duplicates = [];
84
- const 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
- for (let i = 0; i < allBlocks.length; i++) {
94
- for (let j = i + 1; j < allBlocks.length; j++) {
95
- const block1 = allBlocks[i];
96
- const block2 = allBlocks[j];
97
- if (block1.file === block2.file) continue;
98
- const similarity = calculateSimilarity(block1.content, block2.content);
99
- if (similarity >= minSimilarity) {
100
- duplicates.push({
101
- file1: block1.file,
102
- file2: block2.file,
103
- line1: block1.startLine,
104
- line2: block2.startLine,
105
- similarity,
106
- snippet: block1.content.split("\n").slice(0, 5).join("\n") + "\n...",
107
- patternType: block1.patternType,
108
- tokenCost: block1.tokenCost + block2.tokenCost,
109
- linesOfCode: block1.linesOfCode
110
- });
111
- }
112
- }
113
- }
114
- return duplicates.sort(
115
- (a, b) => b.similarity - a.similarity || b.tokenCost - a.tokenCost
116
- );
117
- }
118
-
119
- // src/index.ts
120
- function getRefactoringSuggestion(patternType, similarity) {
121
- const baseMessages = {
122
- "api-handler": "Extract common middleware or create a base handler class",
123
- validator: "Consolidate validation logic into shared schema validators (Zod/Yup)",
124
- utility: "Move to a shared utilities file and reuse across modules",
125
- "class-method": "Consider inheritance or composition to share behavior",
126
- component: "Extract shared logic into a custom hook or HOC",
127
- function: "Extract into a shared helper function",
128
- unknown: "Extract common logic into a reusable module"
129
- };
130
- const urgency = similarity > 0.95 ? " (CRITICAL: Nearly identical code)" : similarity > 0.9 ? " (HIGH: Very similar, refactor soon)" : "";
131
- return baseMessages[patternType] + urgency;
132
- }
133
- async function analyzePatterns(options) {
134
- const { minSimilarity = 0.85, minLines = 5, ...scanOptions } = options;
135
- const files = await scanFiles(scanOptions);
136
- const results = [];
137
- const fileContents = await Promise.all(
138
- files.map(async (file) => ({
139
- file,
140
- content: await readFileContent(file)
141
- }))
142
- );
143
- const duplicates = detectDuplicatePatterns(fileContents, {
144
- minSimilarity,
145
- minLines
146
- });
147
- for (const file of files) {
148
- const fileDuplicates = duplicates.filter(
149
- (dup) => dup.file1 === file || dup.file2 === file
150
- );
151
- const issues = fileDuplicates.map((dup) => {
152
- const otherFile = dup.file1 === file ? dup.file2 : dup.file1;
153
- const severity = dup.similarity > 0.95 ? "critical" : dup.similarity > 0.9 ? "major" : "minor";
154
- return {
155
- type: "duplicate-pattern",
156
- severity,
157
- message: `${dup.patternType} pattern ${Math.round(dup.similarity * 100)}% similar to ${otherFile} (${dup.tokenCost} tokens wasted)`,
158
- location: {
159
- file,
160
- line: dup.file1 === file ? dup.line1 : dup.line2
161
- },
162
- suggestion: getRefactoringSuggestion(dup.patternType, dup.similarity)
163
- };
164
- });
165
- const totalTokenCost = fileDuplicates.reduce(
166
- (sum, dup) => sum + dup.tokenCost,
167
- 0
168
- );
169
- results.push({
170
- fileName: file,
171
- issues,
172
- metrics: {
173
- tokenCost: totalTokenCost,
174
- consistencyScore: Math.max(0, 1 - fileDuplicates.length * 0.1)
175
- }
176
- });
177
- }
178
- return results;
179
- }
180
- function generateSummary(results) {
181
- const allIssues = results.flatMap((r) => r.issues);
182
- const totalTokenCost = results.reduce(
183
- (sum, r) => sum + (r.metrics.tokenCost || 0),
184
- 0
185
- );
186
- const patternsByType = {
187
- "api-handler": 0,
188
- validator: 0,
189
- utility: 0,
190
- "class-method": 0,
191
- component: 0,
192
- function: 0,
193
- unknown: 0
194
- };
195
- allIssues.forEach((issue) => {
196
- const match = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
197
- if (match) {
198
- const type = match[1];
199
- patternsByType[type] = (patternsByType[type] || 0) + 1;
200
- }
201
- });
202
- const topDuplicates = allIssues.slice(0, 10).map((issue) => {
203
- const similarityMatch = issue.message.match(/(\d+)% similar/);
204
- const tokenMatch = issue.message.match(/\((\d+) tokens/);
205
- const typeMatch = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
206
- const fileMatch = issue.message.match(/similar to (.+?) \(/);
207
- return {
208
- file1: issue.location.file,
209
- file2: fileMatch?.[1] || "unknown",
210
- similarity: similarityMatch ? parseInt(similarityMatch[1]) / 100 : 0,
211
- patternType: typeMatch?.[1] || "unknown",
212
- tokenCost: tokenMatch ? parseInt(tokenMatch[1]) : 0
213
- };
214
- });
215
- return {
216
- totalPatterns: allIssues.length,
217
- totalTokenCost,
218
- patternsByType,
219
- topDuplicates
220
- };
221
- }
222
-
223
- export {
224
- detectDuplicatePatterns,
225
- analyzePatterns,
226
- generateSummary
227
- };
@@ -1,351 +0,0 @@
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 {
83
- minSimilarity,
84
- minLines,
85
- maxBlocks = 500,
86
- batchSize = 100,
87
- approx = true,
88
- minSharedTokens = 8,
89
- maxCandidatesPerBlock = 100
90
- } = options;
91
- const duplicates = [];
92
- let allBlocks = files.flatMap(
93
- (file) => extractCodeBlocks(file.content, minLines).map((block) => ({
94
- ...block,
95
- file: file.file,
96
- normalized: normalizeCode(block.content),
97
- tokenCost: estimateTokens(block.content)
98
- }))
99
- );
100
- console.log(`Extracted ${allBlocks.length} code blocks for analysis`);
101
- if (allBlocks.length > maxBlocks) {
102
- console.log(`\u26A0\uFE0F Limiting to ${maxBlocks} blocks (sorted by size) to prevent memory issues`);
103
- console.log(` Use --max-blocks to increase limit or --min-lines to filter smaller blocks`);
104
- allBlocks = allBlocks.sort((a, b) => b.linesOfCode - a.linesOfCode).slice(0, maxBlocks);
105
- }
106
- const stopwords = /* @__PURE__ */ new Set([
107
- "return",
108
- "const",
109
- "let",
110
- "var",
111
- "function",
112
- "class",
113
- "new",
114
- "if",
115
- "else",
116
- "for",
117
- "while",
118
- "async",
119
- "await",
120
- "try",
121
- "catch",
122
- "switch",
123
- "case",
124
- "default",
125
- "import",
126
- "export",
127
- "from",
128
- "true",
129
- "false",
130
- "null",
131
- "undefined",
132
- "this"
133
- ]);
134
- const tokenize = (norm) => norm.split(/[\s(){}\[\];,\.]+/).filter((t) => t && t.length >= 3 && !stopwords.has(t.toLowerCase()));
135
- const blockTokens = allBlocks.map((b) => tokenize(b.normalized));
136
- const invertedIndex = /* @__PURE__ */ new Map();
137
- if (approx) {
138
- for (let i = 0; i < blockTokens.length; i++) {
139
- for (const tok of blockTokens[i]) {
140
- let arr = invertedIndex.get(tok);
141
- if (!arr) {
142
- arr = [];
143
- invertedIndex.set(tok, arr);
144
- }
145
- arr.push(i);
146
- }
147
- }
148
- }
149
- const totalComparisons = approx ? void 0 : allBlocks.length * (allBlocks.length - 1) / 2;
150
- if (totalComparisons !== void 0) {
151
- console.log(`Processing ${totalComparisons.toLocaleString()} comparisons in batches...`);
152
- } else {
153
- console.log(`Using approximate candidate selection to reduce comparisons...`);
154
- }
155
- let comparisonsProcessed = 0;
156
- const startTime = Date.now();
157
- for (let i = 0; i < allBlocks.length; i++) {
158
- if (i % batchSize === 0 && i > 0) {
159
- const elapsed = ((Date.now() - startTime) / 1e3).toFixed(1);
160
- if (totalComparisons !== void 0) {
161
- const progress = (comparisonsProcessed / totalComparisons * 100).toFixed(1);
162
- console.log(` ${progress}% complete (${comparisonsProcessed.toLocaleString()}/${totalComparisons.toLocaleString()} comparisons, ${elapsed}s elapsed)`);
163
- } else {
164
- console.log(` Processed ${i.toLocaleString()} blocks (${elapsed}s elapsed)`);
165
- }
166
- await new Promise((resolve) => setImmediate(resolve));
167
- }
168
- const block1 = allBlocks[i];
169
- let candidates = null;
170
- if (approx) {
171
- const counts = /* @__PURE__ */ new Map();
172
- for (const tok of blockTokens[i]) {
173
- const ids = invertedIndex.get(tok);
174
- if (!ids) continue;
175
- for (const j of ids) {
176
- if (j <= i) continue;
177
- if (allBlocks[j].file === block1.file) continue;
178
- counts.set(j, (counts.get(j) || 0) + 1);
179
- }
180
- }
181
- candidates = Array.from(counts.entries()).filter(([, shared]) => shared >= minSharedTokens).sort((a, b) => b[1] - a[1]).slice(0, maxCandidatesPerBlock).map(([j, shared]) => ({ j, shared }));
182
- }
183
- if (approx && candidates) {
184
- for (const { j } of candidates) {
185
- comparisonsProcessed++;
186
- const block2 = allBlocks[j];
187
- const similarity = calculateSimilarity(block1.content, block2.content);
188
- if (similarity >= minSimilarity) {
189
- duplicates.push({
190
- file1: block1.file,
191
- file2: block2.file,
192
- line1: block1.startLine,
193
- line2: block2.startLine,
194
- similarity,
195
- snippet: block1.content.split("\n").slice(0, 5).join("\n") + "\n...",
196
- patternType: block1.patternType,
197
- tokenCost: block1.tokenCost + block2.tokenCost,
198
- linesOfCode: block1.linesOfCode
199
- });
200
- }
201
- }
202
- } else {
203
- for (let j = i + 1; j < allBlocks.length; j++) {
204
- comparisonsProcessed++;
205
- const block2 = allBlocks[j];
206
- if (block1.file === block2.file) continue;
207
- const similarity = calculateSimilarity(block1.content, block2.content);
208
- if (similarity >= minSimilarity) {
209
- duplicates.push({
210
- file1: block1.file,
211
- file2: block2.file,
212
- line1: block1.startLine,
213
- line2: block2.startLine,
214
- similarity,
215
- snippet: block1.content.split("\n").slice(0, 5).join("\n") + "\n...",
216
- patternType: block1.patternType,
217
- tokenCost: block1.tokenCost + block2.tokenCost,
218
- linesOfCode: block1.linesOfCode
219
- });
220
- }
221
- }
222
- }
223
- }
224
- return duplicates.sort(
225
- (a, b) => b.similarity - a.similarity || b.tokenCost - a.tokenCost
226
- );
227
- }
228
-
229
- // src/index.ts
230
- function getRefactoringSuggestion(patternType, similarity) {
231
- const baseMessages = {
232
- "api-handler": "Extract common middleware or create a base handler class",
233
- validator: "Consolidate validation logic into shared schema validators (Zod/Yup)",
234
- utility: "Move to a shared utilities file and reuse across modules",
235
- "class-method": "Consider inheritance or composition to share behavior",
236
- component: "Extract shared logic into a custom hook or HOC",
237
- function: "Extract into a shared helper function",
238
- unknown: "Extract common logic into a reusable module"
239
- };
240
- const urgency = similarity > 0.95 ? " (CRITICAL: Nearly identical code)" : similarity > 0.9 ? " (HIGH: Very similar, refactor soon)" : "";
241
- return baseMessages[patternType] + urgency;
242
- }
243
- async function analyzePatterns(options) {
244
- const {
245
- minSimilarity = 0.85,
246
- minLines = 5,
247
- maxBlocks = 500,
248
- batchSize = 100,
249
- approx = true,
250
- minSharedTokens = 8,
251
- maxCandidatesPerBlock = 100,
252
- ...scanOptions
253
- } = options;
254
- const files = await scanFiles(scanOptions);
255
- const results = [];
256
- const fileContents = await Promise.all(
257
- files.map(async (file) => ({
258
- file,
259
- content: await readFileContent(file)
260
- }))
261
- );
262
- const duplicates = await detectDuplicatePatterns(fileContents, {
263
- minSimilarity,
264
- minLines,
265
- maxBlocks,
266
- batchSize,
267
- approx,
268
- minSharedTokens,
269
- maxCandidatesPerBlock
270
- });
271
- for (const file of files) {
272
- const fileDuplicates = duplicates.filter(
273
- (dup) => dup.file1 === file || dup.file2 === file
274
- );
275
- const issues = fileDuplicates.map((dup) => {
276
- const otherFile = dup.file1 === file ? dup.file2 : dup.file1;
277
- const severity = dup.similarity > 0.95 ? "critical" : dup.similarity > 0.9 ? "major" : "minor";
278
- return {
279
- type: "duplicate-pattern",
280
- severity,
281
- message: `${dup.patternType} pattern ${Math.round(dup.similarity * 100)}% similar to ${otherFile} (${dup.tokenCost} tokens wasted)`,
282
- location: {
283
- file,
284
- line: dup.file1 === file ? dup.line1 : dup.line2
285
- },
286
- suggestion: getRefactoringSuggestion(dup.patternType, dup.similarity)
287
- };
288
- });
289
- const totalTokenCost = fileDuplicates.reduce(
290
- (sum, dup) => sum + dup.tokenCost,
291
- 0
292
- );
293
- results.push({
294
- fileName: file,
295
- issues,
296
- metrics: {
297
- tokenCost: totalTokenCost,
298
- consistencyScore: Math.max(0, 1 - fileDuplicates.length * 0.1)
299
- }
300
- });
301
- }
302
- return results;
303
- }
304
- function generateSummary(results) {
305
- const allIssues = results.flatMap((r) => r.issues);
306
- const totalTokenCost = results.reduce(
307
- (sum, r) => sum + (r.metrics.tokenCost || 0),
308
- 0
309
- );
310
- const patternsByType = {
311
- "api-handler": 0,
312
- validator: 0,
313
- utility: 0,
314
- "class-method": 0,
315
- component: 0,
316
- function: 0,
317
- unknown: 0
318
- };
319
- allIssues.forEach((issue) => {
320
- const match = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
321
- if (match) {
322
- const type = match[1];
323
- patternsByType[type] = (patternsByType[type] || 0) + 1;
324
- }
325
- });
326
- const topDuplicates = allIssues.slice(0, 10).map((issue) => {
327
- const similarityMatch = issue.message.match(/(\d+)% similar/);
328
- const tokenMatch = issue.message.match(/\((\d+) tokens/);
329
- const typeMatch = issue.message.match(/^(\S+(?:-\S+)*) pattern/);
330
- const fileMatch = issue.message.match(/similar to (.+?) \(/);
331
- return {
332
- file1: issue.location.file,
333
- file2: fileMatch?.[1] || "unknown",
334
- similarity: similarityMatch ? parseInt(similarityMatch[1]) / 100 : 0,
335
- patternType: typeMatch?.[1] || "unknown",
336
- tokenCost: tokenMatch ? parseInt(tokenMatch[1]) : 0
337
- };
338
- });
339
- return {
340
- totalPatterns: allIssues.length,
341
- totalTokenCost,
342
- patternsByType,
343
- topDuplicates
344
- };
345
- }
346
-
347
- export {
348
- detectDuplicatePatterns,
349
- analyzePatterns,
350
- generateSummary
351
- };