@aiready/pattern-detect 0.17.13 → 0.17.15

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,323 @@
1
+ // src/context-rules.ts
2
+ import {
3
+ IssueType,
4
+ getSeverityLabel,
5
+ filterBySeverity,
6
+ Severity as Severity5
7
+ } from "@aiready/core";
8
+
9
+ // src/rules/categories/test-rules.ts
10
+ import { Severity } from "@aiready/core";
11
+ var TEST_RULES = [
12
+ // Test Fixtures - Intentional duplication for test isolation
13
+ {
14
+ name: "test-fixtures",
15
+ detect: (file, code) => {
16
+ const isTestFile = file.includes(".test.") || file.includes(".spec.") || file.includes("__tests__") || file.includes("/test/") || file.includes("/tests/");
17
+ const hasTestFixtures = code.includes("beforeAll") || code.includes("afterAll") || code.includes("beforeEach") || code.includes("afterEach") || code.includes("setUp") || code.includes("tearDown");
18
+ return isTestFile && hasTestFixtures;
19
+ },
20
+ severity: Severity.Info,
21
+ reason: "Test fixture duplication is intentional for test isolation",
22
+ suggestion: "Consider if shared test setup would improve maintainability without coupling tests"
23
+ },
24
+ // E2E/Integration Test Page Objects - Test independence
25
+ {
26
+ name: "e2e-page-objects",
27
+ detect: (file, code) => {
28
+ 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/");
29
+ const hasPageObjectPatterns = code.includes("page.") || code.includes("await page") || code.includes("locator") || code.includes("getBy") || code.includes("selector") || code.includes("click(") || code.includes("fill(");
30
+ return isE2ETest && hasPageObjectPatterns;
31
+ },
32
+ severity: Severity.Info,
33
+ reason: "E2E test duplication ensures test independence and reduces coupling",
34
+ suggestion: "Consider page object pattern only if duplication causes maintenance issues"
35
+ },
36
+ // Mock Data - Test data intentionally duplicated
37
+ {
38
+ name: "mock-data",
39
+ detect: (file, code) => {
40
+ const isMockFile = file.includes("/mocks/") || file.includes("/__mocks__/") || file.includes("/fixtures/") || file.includes(".mock.") || file.includes(".fixture.");
41
+ const hasMockData = code.includes("mock") || code.includes("Mock") || code.includes("fixture") || code.includes("stub") || code.includes("export const");
42
+ return isMockFile && hasMockData;
43
+ },
44
+ severity: Severity.Info,
45
+ reason: "Mock data duplication is expected for comprehensive test coverage",
46
+ suggestion: "Consider shared factories only for complex mock generation"
47
+ }
48
+ ];
49
+
50
+ // src/rules/categories/web-rules.ts
51
+ import { Severity as Severity2 } from "@aiready/core";
52
+ var WEB_RULES = [
53
+ // Email/Document Templates - Often intentionally similar for consistency
54
+ {
55
+ name: "templates",
56
+ detect: (file, code) => {
57
+ const isTemplate = file.includes("/templates/") || file.includes("-template") || file.includes("/email-templates/") || file.includes("/emails/");
58
+ const hasTemplateContent = (code.includes("return") || code.includes("export")) && (code.includes("html") || code.includes("subject") || code.includes("body"));
59
+ return isTemplate && hasTemplateContent;
60
+ },
61
+ severity: Severity2.Info,
62
+ reason: "Template duplication may be intentional for maintainability and branding consistency",
63
+ suggestion: "Extract shared structure only if templates become hard to maintain"
64
+ },
65
+ // Common UI Event Handlers - Very specific patterns only
66
+ {
67
+ name: "common-ui-handlers",
68
+ detect: (file, code) => {
69
+ const isUIFile = file.includes("/components/") || file.includes(".tsx") || file.includes(".jsx") || file.includes("/hooks/");
70
+ const hasCommonHandler = code.includes("handleClickOutside") && code.includes("dropdownRef.current") && code.includes("!dropdownRef.current.contains") || code.includes("handleEscape") && code.includes("event.key") && code.includes("=== 'Escape'") || code.includes("handleClickInside") && code.includes("event.stopPropagation");
71
+ return isUIFile && hasCommonHandler;
72
+ },
73
+ severity: Severity2.Info,
74
+ reason: "Common UI event handlers are boilerplate patterns that repeat across components",
75
+ suggestion: "Consider extracting to shared hooks (useClickOutside, useEscapeKey) only if causing maintenance issues"
76
+ },
77
+ // Next.js Route Handler Patterns - Boilerplate API route patterns
78
+ {
79
+ name: "nextjs-route-handlers",
80
+ detect: (file, code) => {
81
+ const isRouteFile = file.includes("/api/") && (file.endsWith("/route.ts") || file.endsWith("/route.js"));
82
+ const hasRoutePattern = code.includes("export async function POST") || code.includes("export async function GET") || code.includes("export async function PUT") || code.includes("export async function DELETE") || code.includes("NextResponse.json") || code.includes("NextRequest");
83
+ return isRouteFile && hasRoutePattern;
84
+ },
85
+ severity: Severity2.Info,
86
+ reason: "Next.js route handlers follow standard patterns and are intentionally similar across endpoints",
87
+ suggestion: "Route handler duplication is acceptable for API endpoint boilerplate"
88
+ }
89
+ ];
90
+
91
+ // src/rules/categories/infra-rules.ts
92
+ import { Severity as Severity3 } from "@aiready/core";
93
+ var INFRA_RULES = [
94
+ // Configuration Files - Often necessarily similar by design
95
+ {
96
+ name: "config-files",
97
+ detect: (file) => {
98
+ 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");
99
+ },
100
+ severity: Severity3.Info,
101
+ reason: "Configuration files often have similar structure by design",
102
+ suggestion: "Consider shared config base only if configurations become hard to maintain"
103
+ },
104
+ // Migration Scripts - One-off scripts that are similar by nature
105
+ {
106
+ name: "migration-scripts",
107
+ detect: (file) => {
108
+ return file.includes("/migrations/") || file.includes("/migrate/") || file.includes(".migration.");
109
+ },
110
+ severity: Severity3.Info,
111
+ reason: "Migration scripts are typically one-off and intentionally similar",
112
+ suggestion: "Duplication is acceptable for migration scripts"
113
+ },
114
+ // Tool Implementations - Structural Boilerplate
115
+ {
116
+ name: "tool-implementations",
117
+ detect: (file, code) => {
118
+ const isToolFile = file.includes("/tools/") || file.endsWith(".tool.ts") || code.includes("toolDefinitions");
119
+ const hasToolStructure = code.includes("execute") && (code.includes("try") || code.includes("catch"));
120
+ return isToolFile && hasToolStructure;
121
+ },
122
+ severity: Severity3.Info,
123
+ reason: "Tool implementations share structural boilerplate but have distinct business logic",
124
+ suggestion: "Tool duplication is acceptable for boilerplate interface wrappers"
125
+ },
126
+ // CLI Command Definitions - Commander.js boilerplate patterns
127
+ {
128
+ name: "cli-command-definitions",
129
+ detect: (file, code) => {
130
+ const basename = file.split("/").pop() || "";
131
+ const isCliFile = file.includes("/commands/") || file.includes("/cli/") || file.endsWith(".command.ts") || basename === "cli.ts" || basename === "cli.js" || basename === "cli.tsx" || basename === "cli-action.ts";
132
+ const hasCommandPattern = (code.includes(".command(") || code.includes("defineCommand")) && (code.includes(".description(") || code.includes(".option(")) && (code.includes(".action(") || code.includes("async"));
133
+ return isCliFile && hasCommandPattern;
134
+ },
135
+ severity: Severity3.Info,
136
+ reason: "CLI command definitions follow standard Commander.js patterns and are intentionally similar",
137
+ suggestion: "Command boilerplate duplication is acceptable for CLI interfaces"
138
+ }
139
+ ];
140
+
141
+ // src/rules/categories/logic-rules.ts
142
+ import { Severity as Severity4 } from "@aiready/core";
143
+ var LOGIC_RULES = [
144
+ // Re-export / Barrel files - Intentional API surface consolidation
145
+ {
146
+ name: "re-export-files",
147
+ detect: (file, code) => {
148
+ const isIndexFile = file.endsWith("/index.ts") || file.endsWith("/index.js") || file.endsWith("/index.tsx") || file.endsWith("/index.jsx");
149
+ const lines = code.split("\n").filter((l) => l.trim());
150
+ if (lines.length === 0) return false;
151
+ const reExportLines = lines.filter(
152
+ (l) => /^export\s+(\{[^}]+\}|\*)\s+from\s+/.test(l.trim()) || /^export\s+\*\s+as\s+\w+\s+from\s+/.test(l.trim())
153
+ ).length;
154
+ return isIndexFile && reExportLines > 0 && reExportLines / lines.length > 0.5;
155
+ },
156
+ severity: Severity4.Info,
157
+ reason: "Barrel/index files intentionally re-export for API surface consolidation",
158
+ suggestion: "Re-exports in barrel files are expected and not true duplication"
159
+ },
160
+ // Type Definitions - Duplication for type safety and module independence
161
+ {
162
+ name: "type-definitions",
163
+ detect: (file, code) => {
164
+ const isTypeFile = file.endsWith(".d.ts") || file.includes("/types/");
165
+ const hasOnlyTypeDefinitions = (code.includes("interface ") || code.includes("type ") || code.includes("enum ")) && !code.includes("function ") && !code.includes("class ") && !code.includes("const ") && !code.includes("let ") && !code.includes("export default");
166
+ const isInterfaceOnlySnippet = code.trim().startsWith("interface ") && code.includes("{") && code.includes("}") && !code.includes("function ") && !code.includes("const ") && !code.includes("return ");
167
+ return isTypeFile && hasOnlyTypeDefinitions || isInterfaceOnlySnippet;
168
+ },
169
+ severity: Severity4.Info,
170
+ reason: "Type/interface definitions are intentionally duplicated for module independence",
171
+ suggestion: "Extract to shared types package only if causing maintenance burden"
172
+ },
173
+ // Utility Functions - Small helpers in dedicated utility files
174
+ {
175
+ name: "utility-functions",
176
+ detect: (file, code) => {
177
+ const isUtilFile = file.endsWith(".util.ts") || file.endsWith(".helper.ts") || file.endsWith(".utils.ts");
178
+ const hasUtilPattern = code.includes("function format") || code.includes("function parse") || code.includes("function sanitize") || code.includes("function normalize") || code.includes("function convert");
179
+ return isUtilFile && hasUtilPattern;
180
+ },
181
+ severity: Severity4.Info,
182
+ reason: "Utility functions in dedicated utility files may be intentionally similar",
183
+ suggestion: "Consider extracting to shared utilities only if causing significant duplication"
184
+ },
185
+ // React/Vue Hooks - Standard patterns
186
+ {
187
+ name: "shared-hooks",
188
+ detect: (file, code) => {
189
+ const isHookFile = file.includes("/hooks/") || file.endsWith(".hook.ts") || file.endsWith(".hook.tsx");
190
+ const hasHookPattern = code.includes("function use") || code.includes("export function use") || code.includes("const use") || code.includes("export const use");
191
+ return isHookFile && hasHookPattern;
192
+ },
193
+ severity: Severity4.Info,
194
+ reason: "Hooks follow standard patterns and are often intentionally similar across components",
195
+ suggestion: "Consider extracting common hook logic only if hooks become complex"
196
+ },
197
+ // Score/Rating Helper Functions - Common threshold patterns
198
+ {
199
+ name: "score-helpers",
200
+ detect: (file, code) => {
201
+ const isHelperFile = file.includes("/utils/") || file.includes("/helpers/") || file.endsWith(".util.ts");
202
+ const hasScorePattern = (code.includes("if (score >=") || code.includes("if (score >")) && code.includes("return") && code.includes("'") && code.split("if (score").length >= 3;
203
+ return isHelperFile && hasScorePattern;
204
+ },
205
+ severity: Severity4.Info,
206
+ reason: "Score/rating helper functions use common threshold patterns that are intentionally similar",
207
+ suggestion: "Score formatting duplication is acceptable for consistent UI display"
208
+ },
209
+ // D3/Canvas Event Handlers - Standard visualization patterns
210
+ {
211
+ name: "visualization-handlers",
212
+ detect: (file, code) => {
213
+ const isVizFile = file.includes("/visualizer/") || file.includes("/charts/") || file.includes("GraphCanvas") || file.includes("ForceDirected");
214
+ const hasVizPattern = (code.includes("dragstarted") || code.includes("dragged") || code.includes("dragended")) && (code.includes("simulation") || code.includes("d3.") || code.includes("alphaTarget"));
215
+ return isVizFile && hasVizPattern;
216
+ },
217
+ severity: Severity4.Info,
218
+ reason: "D3/visualization event handlers follow standard patterns and are intentionally similar",
219
+ suggestion: "Visualization boilerplate duplication is acceptable for interactive charts"
220
+ },
221
+ // Icon/Switch Statement Helpers - Common enum-to-value patterns
222
+ {
223
+ name: "switch-helpers",
224
+ detect: (file, code) => {
225
+ const hasSwitchPattern = code.includes("switch (") && code.includes("case '") && code.includes("return") && code.split("case ").length >= 4;
226
+ const hasIconPattern = code.includes("getIcon") || code.includes("getColor") || code.includes("getLabel") || code.includes("getRating");
227
+ return hasSwitchPattern && hasIconPattern;
228
+ },
229
+ severity: Severity4.Info,
230
+ reason: "Switch statement helpers for enum-to-value mapping are inherently similar",
231
+ suggestion: "Switch duplication is acceptable for mapping enums to display values"
232
+ },
233
+ // Common API/Utility Functions - Legitimate duplication across modules
234
+ {
235
+ name: "common-api-functions",
236
+ detect: (file, code) => {
237
+ const isApiFile = file.includes("/api/") || file.includes("/lib/") || file.includes("/utils/") || file.endsWith(".ts");
238
+ const hasCommonApiPattern = code.includes("getStripe") && code.includes("process.env.STRIPE_SECRET_KEY") || code.includes("getUserByEmail") && code.includes("queryItems") || code.includes("updateUser") && code.includes("buildUpdateExpression") || code.includes("listUserRepositories") && code.includes("queryItems") || code.includes("listTeamRepositories") && code.includes("queryItems") || code.includes("getRemediation") && code.includes("queryItems") || code.includes("formatBreakdownKey") && code.includes(".replace(/([A-Z])/g") || code.includes("queryItems") && code.includes("KeyConditionExpression") || code.includes("putItem") && code.includes("createdAt") || code.includes("updateItem") && code.includes("buildUpdateExpression");
239
+ return isApiFile && hasCommonApiPattern;
240
+ },
241
+ severity: Severity4.Info,
242
+ reason: "Common API/utility functions are legitimately duplicated across modules for clarity and independence",
243
+ suggestion: "Consider extracting to shared utilities only if causing significant duplication"
244
+ },
245
+ // Validation Functions - Inherently similar patterns
246
+ {
247
+ name: "validation-functions",
248
+ detect: (file, code) => {
249
+ const hasValidationPattern = code.includes("isValid") || code.includes("validate") || code.includes("checkValid") || code.includes("isEmail") || code.includes("isPhone") || code.includes("isUrl") || code.includes("isNumeric") || code.includes("isAlpha") || code.includes("isAlphanumeric") || code.includes("isEmpty") || code.includes("isNotEmpty") || code.includes("isRequired") || code.includes("isOptional");
250
+ return hasValidationPattern;
251
+ },
252
+ severity: Severity4.Info,
253
+ reason: "Validation functions are inherently similar and often intentionally duplicated for domain clarity",
254
+ suggestion: "Consider extracting to shared validators only if validation logic becomes complex"
255
+ }
256
+ ];
257
+
258
+ // src/context-rules.ts
259
+ var CONTEXT_RULES = [
260
+ ...TEST_RULES,
261
+ ...WEB_RULES,
262
+ ...INFRA_RULES,
263
+ ...LOGIC_RULES
264
+ ];
265
+ function calculateSeverity(file1, file2, code, similarity, linesOfCode) {
266
+ for (const rule of CONTEXT_RULES) {
267
+ if (rule.detect(file1, code) || rule.detect(file2, code)) {
268
+ return {
269
+ severity: rule.severity,
270
+ reason: rule.reason,
271
+ suggestion: rule.suggestion,
272
+ matchedRule: rule.name
273
+ };
274
+ }
275
+ }
276
+ if (similarity >= 0.95 && linesOfCode >= 30) {
277
+ return {
278
+ severity: Severity5.Critical,
279
+ reason: "Large nearly-identical code blocks waste tokens and create maintenance burden",
280
+ suggestion: "Extract to shared utility module immediately"
281
+ };
282
+ } else if (similarity >= 0.95 && linesOfCode >= 15) {
283
+ return {
284
+ severity: Severity5.Major,
285
+ reason: "Nearly identical code should be consolidated",
286
+ suggestion: "Move to shared utility file"
287
+ };
288
+ } else if (similarity >= 0.85) {
289
+ return {
290
+ severity: Severity5.Major,
291
+ reason: "High similarity indicates significant duplication",
292
+ suggestion: "Extract common logic to shared function"
293
+ };
294
+ } else if (similarity >= 0.7) {
295
+ return {
296
+ severity: Severity5.Minor,
297
+ reason: "Moderate similarity detected",
298
+ suggestion: "Consider extracting shared patterns if code evolves together"
299
+ };
300
+ } else {
301
+ return {
302
+ severity: Severity5.Minor,
303
+ reason: "Minor similarity detected",
304
+ suggestion: "Monitor but refactoring may not be worthwhile"
305
+ };
306
+ }
307
+ }
308
+ function getSeverityThreshold(severity) {
309
+ const thresholds = {
310
+ [Severity5.Critical]: 0.95,
311
+ [Severity5.Major]: 0.85,
312
+ [Severity5.Minor]: 0.5,
313
+ [Severity5.Info]: 0
314
+ };
315
+ return thresholds[severity] || 0;
316
+ }
317
+
318
+ export {
319
+ getSeverityLabel,
320
+ filterBySeverity,
321
+ calculateSeverity,
322
+ getSeverityThreshold
323
+ };