@aiready/consistency 0.20.19 → 0.20.21

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,831 @@
1
+ // src/analyzers/naming-ast.ts
2
+ import { Severity as Severity2 } from "@aiready/core";
3
+
4
+ // src/utils/ast-parser.ts
5
+ import { parse } from "@typescript-eslint/typescript-estree";
6
+ import { readFileSync } from "fs";
7
+ function parseFile(filePath, content) {
8
+ try {
9
+ const code = content ?? readFileSync(filePath, "utf-8");
10
+ const isTypeScript = filePath.match(/\.tsx?$/);
11
+ return parse(code, {
12
+ jsx: filePath.match(/\.[jt]sx$/i) !== null,
13
+ loc: true,
14
+ range: true,
15
+ comment: false,
16
+ tokens: false,
17
+ // Relaxed parsing for JavaScript files
18
+ sourceType: "module",
19
+ ecmaVersion: "latest",
20
+ // Only use TypeScript parser features for .ts/.tsx files
21
+ filePath: isTypeScript ? filePath : void 0
22
+ });
23
+ } catch (error) {
24
+ void error;
25
+ return null;
26
+ }
27
+ }
28
+ function traverseAST(node, visitor, parent = null) {
29
+ if (!node) return;
30
+ visitor.enter?.(node, parent);
31
+ for (const key of Object.keys(node)) {
32
+ const value = node[key];
33
+ if (Array.isArray(value)) {
34
+ for (const child of value) {
35
+ if (child && typeof child === "object" && "type" in child) {
36
+ traverseAST(child, visitor, node);
37
+ }
38
+ }
39
+ } else if (value && typeof value === "object" && "type" in value) {
40
+ traverseAST(value, visitor, node);
41
+ }
42
+ }
43
+ visitor.leave?.(node, parent);
44
+ }
45
+ function isLoopStatement(node) {
46
+ return [
47
+ "ForStatement",
48
+ "ForInStatement",
49
+ "ForOfStatement",
50
+ "WhileStatement",
51
+ "DoWhileStatement"
52
+ ].includes(node.type);
53
+ }
54
+ function getLineNumber(node) {
55
+ return node.loc?.start.line ?? 0;
56
+ }
57
+
58
+ // src/utils/context-detector.ts
59
+ import { Severity } from "@aiready/core";
60
+ function detectFileType(filePath, ast) {
61
+ void ast;
62
+ const path = filePath.toLowerCase();
63
+ if (path.match(/\.(test|spec)\.(ts|tsx|js|jsx)$/) || path.includes("__tests__")) {
64
+ return "test";
65
+ }
66
+ if (path.endsWith(".d.ts") || path.includes("types")) {
67
+ return "types";
68
+ }
69
+ if (path.match(/config|\.config\.|rc\.|setup/) || path.includes("configuration")) {
70
+ return "config";
71
+ }
72
+ return "production";
73
+ }
74
+ function detectCodeLayer(ast) {
75
+ let hasAPIIndicators = 0;
76
+ let hasBusinessIndicators = 0;
77
+ let hasDataIndicators = 0;
78
+ let hasUtilityIndicators = 0;
79
+ traverseAST(ast, {
80
+ enter: (node) => {
81
+ if (node.type === "ImportDeclaration") {
82
+ const source = node.source.value;
83
+ if (source.match(/express|fastify|koa|@nestjs|axios|fetch|http/i)) {
84
+ hasAPIIndicators++;
85
+ }
86
+ if (source.match(/database|prisma|typeorm|sequelize|mongoose|pg|mysql/i)) {
87
+ hasDataIndicators++;
88
+ }
89
+ }
90
+ if (node.type === "FunctionDeclaration" && node.id) {
91
+ const name = node.id.name;
92
+ if (name.match(
93
+ /^(get|post|put|delete|patch|handle|api|route|controller)/i
94
+ )) {
95
+ hasAPIIndicators++;
96
+ }
97
+ if (name.match(/^(calculate|process|validate|transform|compute|analyze)/i)) {
98
+ hasBusinessIndicators++;
99
+ }
100
+ if (name.match(/^(find|create|update|delete|save|fetch|query|insert)/i)) {
101
+ hasDataIndicators++;
102
+ }
103
+ if (name.match(
104
+ /^(format|parse|convert|normalize|sanitize|encode|decode)/i
105
+ )) {
106
+ hasUtilityIndicators++;
107
+ }
108
+ }
109
+ if (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") {
110
+ if (node.type === "ExportNamedDeclaration" && node.declaration) {
111
+ if (node.declaration.type === "FunctionDeclaration" && node.declaration.id) {
112
+ const name = node.declaration.id.name;
113
+ if (name.match(/handler|route|api|controller/i)) {
114
+ hasAPIIndicators += 2;
115
+ }
116
+ }
117
+ }
118
+ }
119
+ }
120
+ });
121
+ const scores = {
122
+ api: hasAPIIndicators,
123
+ business: hasBusinessIndicators,
124
+ data: hasDataIndicators,
125
+ utility: hasUtilityIndicators
126
+ };
127
+ const maxScore = Math.max(...Object.values(scores));
128
+ if (maxScore === 0) {
129
+ return "unknown";
130
+ }
131
+ if (scores.api === maxScore) return "api";
132
+ if (scores.data === maxScore) return "data";
133
+ if (scores.business === maxScore) return "business";
134
+ if (scores.utility === maxScore) return "utility";
135
+ return "unknown";
136
+ }
137
+ function calculateComplexity(node) {
138
+ let complexity = 1;
139
+ traverseAST(node, {
140
+ enter: (childNode) => {
141
+ switch (childNode.type) {
142
+ case "IfStatement":
143
+ case "ConditionalExpression":
144
+ // ternary
145
+ case "SwitchCase":
146
+ case "ForStatement":
147
+ case "ForInStatement":
148
+ case "ForOfStatement":
149
+ case "WhileStatement":
150
+ case "DoWhileStatement":
151
+ case "CatchClause":
152
+ complexity++;
153
+ break;
154
+ case "LogicalExpression":
155
+ if (childNode.operator === "&&" || childNode.operator === "||") {
156
+ complexity++;
157
+ }
158
+ break;
159
+ }
160
+ }
161
+ });
162
+ return complexity;
163
+ }
164
+ function buildCodeContext(filePath, ast) {
165
+ const fileType = detectFileType(filePath, ast);
166
+ const codeLayer = detectCodeLayer(ast);
167
+ let totalComplexity = 0;
168
+ let functionCount = 0;
169
+ traverseAST(ast, {
170
+ enter: (node) => {
171
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
172
+ totalComplexity += calculateComplexity(node);
173
+ functionCount++;
174
+ }
175
+ }
176
+ });
177
+ const avgComplexity = functionCount > 0 ? totalComplexity / functionCount : 1;
178
+ return {
179
+ fileType,
180
+ codeLayer,
181
+ complexity: Math.round(avgComplexity),
182
+ isTestFile: fileType === "test",
183
+ isTypeDefinition: fileType === "types"
184
+ };
185
+ }
186
+ function adjustSeverity(baseSeverity, context, issueType) {
187
+ const getEnum = (s) => {
188
+ if (s === Severity.Critical || s === "critical") return Severity.Critical;
189
+ if (s === Severity.Major || s === "major") return Severity.Major;
190
+ if (s === Severity.Minor || s === "minor") return Severity.Minor;
191
+ return Severity.Info;
192
+ };
193
+ let currentSev = getEnum(baseSeverity);
194
+ if (context.isTestFile) {
195
+ if (currentSev === Severity.Minor) currentSev = Severity.Info;
196
+ if (currentSev === Severity.Major) currentSev = Severity.Minor;
197
+ }
198
+ if (context.isTypeDefinition) {
199
+ if (currentSev === Severity.Minor) currentSev = Severity.Info;
200
+ }
201
+ if (context.codeLayer === "api") {
202
+ if (currentSev === Severity.Info && issueType === "unclear")
203
+ currentSev = Severity.Minor;
204
+ if (currentSev === Severity.Minor && issueType === "unclear")
205
+ currentSev = Severity.Major;
206
+ }
207
+ if (context.complexity > 10) {
208
+ if (currentSev === Severity.Info) currentSev = Severity.Minor;
209
+ }
210
+ if (context.codeLayer === "utility") {
211
+ if (currentSev === Severity.Minor && issueType === "abbreviation")
212
+ currentSev = Severity.Info;
213
+ }
214
+ return currentSev;
215
+ }
216
+ function isAcceptableInContext(name, context, options) {
217
+ if (options.isLoopVariable && ["i", "j", "k", "l", "n", "m"].includes(name)) {
218
+ return true;
219
+ }
220
+ if (context.isTestFile) {
221
+ if (["a", "b", "c", "x", "y", "z"].includes(name) && options.isParameter) {
222
+ return true;
223
+ }
224
+ }
225
+ if (context.codeLayer === "utility" && ["x", "y", "z"].includes(name)) {
226
+ return true;
227
+ }
228
+ if (options.isDestructured) {
229
+ if (["s", "b", "f", "l"].includes(name)) {
230
+ return true;
231
+ }
232
+ }
233
+ if (options.isParameter && (options.complexity ?? context.complexity) < 3) {
234
+ if (name.length >= 2) {
235
+ return true;
236
+ }
237
+ }
238
+ return false;
239
+ }
240
+
241
+ // src/analyzers/naming-ast.ts
242
+ async function analyzeNamingAST(filePaths) {
243
+ const allIssues = [];
244
+ for (const filePath of filePaths) {
245
+ try {
246
+ const ast = parseFile(filePath);
247
+ if (!ast) continue;
248
+ const context = buildCodeContext(filePath, ast);
249
+ const issues = analyzeIdentifiers(ast, filePath, context);
250
+ allIssues.push(...issues);
251
+ } catch (err) {
252
+ void err;
253
+ }
254
+ }
255
+ return allIssues;
256
+ }
257
+ function analyzeIdentifiers(ast, filePath, context) {
258
+ const issues = [];
259
+ const scopeTracker = new ScopeTracker();
260
+ traverseAST(ast, {
261
+ enter: (node) => {
262
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier") {
263
+ const isParameter = false;
264
+ const isLoopVariable = isLoopStatement(node.parent?.parent);
265
+ scopeTracker.declareVariable(
266
+ node.id.name,
267
+ node.id,
268
+ getLineNumber(node.id),
269
+ { isParameter, isLoopVariable }
270
+ );
271
+ }
272
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
273
+ const isArrowParameter = node.type === "ArrowFunctionExpression";
274
+ node.params.forEach((param) => {
275
+ if (param.type === "Identifier") {
276
+ scopeTracker.declareVariable(
277
+ param.name,
278
+ param,
279
+ getLineNumber(param),
280
+ { isParameter: true, isArrowParameter }
281
+ );
282
+ } else if (param.type === "ObjectPattern") {
283
+ extractDestructuredIdentifiers(param, scopeTracker, {
284
+ isParameter: true,
285
+ isArrowParameter
286
+ });
287
+ }
288
+ });
289
+ }
290
+ if ((node.type === "ClassDeclaration" || node.type === "TSInterfaceDeclaration" || node.type === "TSTypeAliasDeclaration") && node.id) {
291
+ checkNamingConvention(
292
+ node.id.name,
293
+ "PascalCase",
294
+ node.id,
295
+ filePath,
296
+ issues,
297
+ context
298
+ );
299
+ }
300
+ }
301
+ });
302
+ for (const varInfo of scopeTracker.getVariables()) {
303
+ checkVariableNaming(varInfo, filePath, issues, context);
304
+ }
305
+ return issues;
306
+ }
307
+ function checkNamingConvention(name, convention, node, file, issues, context) {
308
+ let isValid = true;
309
+ if (convention === "PascalCase") {
310
+ isValid = /^[A-Z][a-zA-Z0-9]*$/.test(name);
311
+ } else if (convention === "camelCase") {
312
+ isValid = /^[a-z][a-zA-Z0-9]*$/.test(name);
313
+ } else if (convention === "UPPER_CASE") {
314
+ isValid = /^[A-Z][A-Z0-9_]*$/.test(name);
315
+ }
316
+ if (!isValid) {
317
+ const severity = adjustSeverity(Severity2.Info, context, "convention-mix");
318
+ issues.push({
319
+ file,
320
+ line: getLineNumber(node),
321
+ type: "convention-mix",
322
+ identifier: name,
323
+ severity,
324
+ suggestion: `Follow ${convention} for this identifier`
325
+ });
326
+ }
327
+ }
328
+ function checkVariableNaming(varInfo, file, issues, context) {
329
+ const { name, line, options } = varInfo;
330
+ if (isAcceptableInContext(name, context, options)) {
331
+ return;
332
+ }
333
+ if (name.length === 1 && !options.isLoopVariable && !options.isArrowParameter) {
334
+ const severity = adjustSeverity(Severity2.Minor, context, "poor-naming");
335
+ issues.push({
336
+ file,
337
+ line,
338
+ type: "poor-naming",
339
+ identifier: name,
340
+ severity,
341
+ suggestion: "Use a more descriptive name than a single letter"
342
+ });
343
+ }
344
+ const vagueNames = [
345
+ "data",
346
+ "info",
347
+ "item",
348
+ "obj",
349
+ "val",
350
+ "tmp",
351
+ "temp",
352
+ "thing",
353
+ "stuff"
354
+ ];
355
+ if (vagueNames.includes(name.toLowerCase())) {
356
+ const severity = adjustSeverity(Severity2.Minor, context, "poor-naming");
357
+ issues.push({
358
+ file,
359
+ line,
360
+ type: "poor-naming",
361
+ identifier: name,
362
+ severity,
363
+ suggestion: `Avoid vague names like '${name}'. What does this data represent?`
364
+ });
365
+ }
366
+ if (name.length > 1 && name.length <= 3 && !options.isLoopVariable && !isCommonAbbreviation(name)) {
367
+ const severity = adjustSeverity(Severity2.Info, context, "abbreviation");
368
+ issues.push({
369
+ file,
370
+ line,
371
+ type: "abbreviation",
372
+ identifier: name,
373
+ severity,
374
+ suggestion: "Avoid non-standard abbreviations"
375
+ });
376
+ }
377
+ }
378
+ function isCommonAbbreviation(name) {
379
+ const common = [
380
+ "id",
381
+ "db",
382
+ "fs",
383
+ "os",
384
+ "ip",
385
+ "ui",
386
+ "ux",
387
+ "api",
388
+ "env",
389
+ "url",
390
+ "req",
391
+ "res",
392
+ "err",
393
+ "ctx",
394
+ "cb",
395
+ "idx",
396
+ "src",
397
+ "dir",
398
+ "app",
399
+ "dev",
400
+ "qa",
401
+ "dto",
402
+ "dao",
403
+ "ref",
404
+ "ast",
405
+ "dom",
406
+ "log",
407
+ "msg",
408
+ "pkg",
409
+ "req",
410
+ "err",
411
+ "res",
412
+ "css",
413
+ "html",
414
+ "xml",
415
+ "jsx",
416
+ "tsx",
417
+ "ts",
418
+ "js"
419
+ ];
420
+ return common.includes(name.toLowerCase());
421
+ }
422
+ var ScopeTracker = class {
423
+ constructor() {
424
+ this.variables = [];
425
+ }
426
+ declareVariable(name, node, line, options = {}) {
427
+ this.variables.push({ name, node, line, options });
428
+ }
429
+ getVariables() {
430
+ return this.variables;
431
+ }
432
+ };
433
+ function extractDestructuredIdentifiers(node, scopeTracker, options = {}) {
434
+ const { isParameter = false, isArrowParameter = false } = options;
435
+ if (node.type === "ObjectPattern") {
436
+ node.properties.forEach((prop) => {
437
+ if (prop.type === "Property" && prop.value.type === "Identifier") {
438
+ scopeTracker.declareVariable(
439
+ prop.value.name,
440
+ prop.value,
441
+ getLineNumber(prop.value),
442
+ {
443
+ isParameter,
444
+ isDestructured: true,
445
+ isArrowParameter
446
+ }
447
+ );
448
+ }
449
+ });
450
+ } else if (node.type === "ArrayPattern") {
451
+ for (const element of node.elements) {
452
+ if (element?.type === "Identifier") {
453
+ scopeTracker.declareVariable(
454
+ element.name,
455
+ element,
456
+ getLineNumber(element),
457
+ {
458
+ isParameter,
459
+ isDestructured: true,
460
+ isArrowParameter
461
+ }
462
+ );
463
+ }
464
+ }
465
+ }
466
+ }
467
+
468
+ // src/analyzers/patterns.ts
469
+ import { readFileSync as readFileSync2 } from "fs";
470
+ import { Severity as Severity3 } from "@aiready/core";
471
+ async function analyzePatterns(filePaths) {
472
+ const issues = [];
473
+ const contents = /* @__PURE__ */ new Map();
474
+ const tryCatchPattern = /try\s*\{/g;
475
+ const styleStats = {
476
+ tryCatch: 0,
477
+ thenCatch: 0,
478
+ asyncAwait: 0,
479
+ commonJs: 0,
480
+ esm: 0
481
+ };
482
+ for (const filePath of filePaths) {
483
+ try {
484
+ const content = readFileSync2(filePath, "utf-8");
485
+ contents.set(filePath, content);
486
+ if (content.match(tryCatchPattern)) styleStats.tryCatch++;
487
+ if (content.match(/\.catch\s*\(/)) styleStats.thenCatch++;
488
+ if (content.match(/\bawait\b/)) styleStats.asyncAwait++;
489
+ if (content.match(/\brequire\s*\(/)) styleStats.commonJs++;
490
+ if (content.match(/\bimport\b.*\bfrom\b/)) styleStats.esm++;
491
+ } catch (err) {
492
+ void err;
493
+ }
494
+ }
495
+ if (styleStats.tryCatch > 0 && styleStats.thenCatch > 0) {
496
+ const dominant = styleStats.tryCatch >= styleStats.thenCatch ? "try-catch" : ".catch()";
497
+ const minority = dominant === "try-catch" ? ".catch()" : "try-catch";
498
+ issues.push({
499
+ files: filePaths.filter((f) => {
500
+ const c = contents.get(f) || "";
501
+ return minority === "try-catch" ? c.match(tryCatchPattern) : c.match(/\.catch\s*\(/);
502
+ }),
503
+ type: "pattern-inconsistency",
504
+ description: `Mixed error handling styles: codebase primarily uses ${dominant}, but found ${minority} in some files.`,
505
+ examples: [dominant, minority],
506
+ severity: Severity3.Minor
507
+ });
508
+ }
509
+ if (styleStats.commonJs > 0 && styleStats.esm > 0) {
510
+ const minority = styleStats.esm >= styleStats.commonJs ? "CommonJS (require)" : "ESM (import)";
511
+ issues.push({
512
+ files: filePaths.filter((f) => {
513
+ const c = contents.get(f) || "";
514
+ return minority === "CommonJS (require)" ? c.match(/\brequire\s*\(/) : c.match(/\bimport\b/);
515
+ }),
516
+ type: "pattern-inconsistency",
517
+ description: `Mixed module systems: found both ESM and CommonJS.`,
518
+ examples: ['import X from "y"', 'const X = require("y")'],
519
+ severity: Severity3.Major
520
+ });
521
+ }
522
+ return issues;
523
+ }
524
+
525
+ // src/analyzer.ts
526
+ import {
527
+ scanFiles,
528
+ Severity as Severity5,
529
+ IssueType,
530
+ getSeverityLevel
531
+ } from "@aiready/core";
532
+
533
+ // src/analyzers/naming-generalized.ts
534
+ import { getParser, Severity as Severity4 } from "@aiready/core";
535
+ import { readFileSync as readFileSync3 } from "fs";
536
+ var COMMON_ABBREVIATIONS = /* @__PURE__ */ new Set([
537
+ "id",
538
+ "db",
539
+ "fs",
540
+ "os",
541
+ "ip",
542
+ "ui",
543
+ "ux",
544
+ "api",
545
+ "env",
546
+ "url",
547
+ "req",
548
+ "res",
549
+ "err",
550
+ "ctx",
551
+ "cb",
552
+ "idx",
553
+ "src",
554
+ "dir",
555
+ "app",
556
+ "dev",
557
+ "qa",
558
+ "dto",
559
+ "dao",
560
+ "ref",
561
+ "ast",
562
+ "dom",
563
+ "log",
564
+ "msg",
565
+ "pkg",
566
+ "css",
567
+ "html",
568
+ "xml",
569
+ "jsx",
570
+ "tsx",
571
+ "ts",
572
+ "js"
573
+ ]);
574
+ async function analyzeNamingGeneralized(files) {
575
+ const issues = [];
576
+ for (const file of files) {
577
+ const parser = await getParser(file);
578
+ if (!parser) continue;
579
+ try {
580
+ const code = readFileSync3(file, "utf-8");
581
+ if (!code.trim()) continue;
582
+ await parser.initialize();
583
+ const result = parser.parse(code, file);
584
+ const conventions = parser.getNamingConventions();
585
+ const exceptions = new Set(conventions.exceptions || []);
586
+ for (const exp of result.exports) {
587
+ if (!exp.name || exp.name === "default") continue;
588
+ if (exceptions.has(exp.name)) continue;
589
+ if (COMMON_ABBREVIATIONS.has(exp.name.toLowerCase())) continue;
590
+ let pattern;
591
+ if (exp.type === "class") {
592
+ pattern = conventions.classPattern;
593
+ } else if (exp.type === "interface" && conventions.interfacePattern) {
594
+ pattern = conventions.interfacePattern;
595
+ } else if (exp.type === "type" && conventions.typePattern) {
596
+ pattern = conventions.typePattern;
597
+ } else if (exp.type === "function") {
598
+ if (/^[A-Z][a-zA-Z0-9]*$/.test(exp.name) || /^[A-Z][A-Z0-9_]*$/.test(exp.name)) {
599
+ continue;
600
+ }
601
+ pattern = conventions.functionPattern;
602
+ } else if (exp.type === "const") {
603
+ if ([
604
+ "handler",
605
+ "GET",
606
+ "POST",
607
+ "PUT",
608
+ "DELETE",
609
+ "PATCH",
610
+ "OPTIONS",
611
+ "HEAD"
612
+ ].includes(exp.name))
613
+ continue;
614
+ pattern = exp.isPrimitive ? conventions.constantPattern : conventions.variablePattern;
615
+ } else {
616
+ pattern = conventions.variablePattern;
617
+ }
618
+ if (pattern && !pattern.test(exp.name)) {
619
+ issues.push({
620
+ type: "naming-inconsistency",
621
+ identifier: exp.name,
622
+ file,
623
+ line: exp.loc?.start.line || 1,
624
+ column: exp.loc?.start.column || 0,
625
+ // Recalibrate naming issues to Minor to differentiate from structural/architectural issues
626
+ severity: Severity4.Minor,
627
+ category: "naming",
628
+ suggestion: `Follow ${parser.language} ${exp.type} naming convention: ${pattern.toString()}`
629
+ });
630
+ }
631
+ }
632
+ for (const imp of result.imports) {
633
+ for (const spec of imp.specifiers) {
634
+ if (!spec || spec === "*" || spec === "default") continue;
635
+ if (exceptions.has(spec)) continue;
636
+ if (COMMON_ABBREVIATIONS.has(spec.toLowerCase())) continue;
637
+ if (!conventions.variablePattern.test(spec) && !conventions.classPattern.test(spec) && (!conventions.constantPattern || !conventions.constantPattern.test(spec)) && (!conventions.typePattern || !conventions.typePattern.test(spec)) && (!conventions.interfacePattern || !conventions.interfacePattern.test(spec)) && !/^[A-Z][A-Z0-9_]*$/.test(spec)) {
638
+ issues.push({
639
+ type: "naming-inconsistency",
640
+ identifier: spec,
641
+ file,
642
+ line: imp.loc?.start.line || 1,
643
+ column: imp.loc?.start.column || 0,
644
+ severity: Severity4.Info,
645
+ // Reduced from Minor to Info for imports
646
+ category: "naming",
647
+ suggestion: `Imported identifier '${spec}' may not follow standard conventions for this language.`
648
+ });
649
+ }
650
+ }
651
+ }
652
+ } catch (error) {
653
+ const errorMessage = error instanceof Error ? error.message : String(error);
654
+ console.debug(
655
+ `Consistency: Skipping unparseable file ${file}: ${errorMessage.split("\\n")[0]}`
656
+ );
657
+ }
658
+ }
659
+ return issues;
660
+ }
661
+
662
+ // src/analyzer.ts
663
+ async function analyzeConsistency(options) {
664
+ const {
665
+ checkNaming = true,
666
+ checkPatterns = true,
667
+ checkArchitecture = false,
668
+ // Not implemented yet
669
+ minSeverity = Severity5.Info,
670
+ ...scanOptions
671
+ } = options;
672
+ void checkArchitecture;
673
+ const filePaths = await scanFiles(scanOptions);
674
+ let namingIssues = [];
675
+ if (checkNaming) {
676
+ namingIssues = await analyzeNamingGeneralized(filePaths);
677
+ const tsJsFiles = filePaths.filter((f) => /\.(ts|tsx|js|jsx)$/i.test(f));
678
+ if (tsJsFiles.length > 0) {
679
+ const deepTsIssues = await analyzeNamingAST(tsJsFiles);
680
+ namingIssues = [...namingIssues, ...deepTsIssues];
681
+ }
682
+ }
683
+ const patternIssues = checkPatterns ? await analyzePatterns(filePaths) : [];
684
+ const results = [];
685
+ const fileIssuesMap = /* @__PURE__ */ new Map();
686
+ for (const issue of namingIssues) {
687
+ if (!shouldIncludeSeverity(issue.severity, minSeverity)) continue;
688
+ const fileName = issue.fileName || issue.file || issue.filePath || "unknown";
689
+ if (!fileIssuesMap.has(fileName)) fileIssuesMap.set(fileName, []);
690
+ fileIssuesMap.get(fileName).push(issue);
691
+ }
692
+ for (const issue of patternIssues) {
693
+ if (!shouldIncludeSeverity(issue.severity, minSeverity)) continue;
694
+ const fileName = issue.fileName || issue.file || issue.filePath || (Array.isArray(issue.files) ? issue.files[0] : "unknown");
695
+ if (!fileIssuesMap.has(fileName)) fileIssuesMap.set(fileName, []);
696
+ fileIssuesMap.get(fileName).push(issue);
697
+ }
698
+ for (const [fileName, issues] of fileIssuesMap.entries()) {
699
+ results.push({
700
+ fileName,
701
+ issues: issues.map((i) => transformToIssue(i)),
702
+ metrics: {
703
+ consistencyScore: calculateConsistencyScore(issues)
704
+ }
705
+ });
706
+ }
707
+ const recommendations = [];
708
+ if (namingIssues.length > 0) {
709
+ recommendations.push("Standardize naming conventions across the codebase");
710
+ }
711
+ if (patternIssues.length > 0) {
712
+ recommendations.push("Consolidate repetitive implementation patterns");
713
+ }
714
+ if (results.some((r) => (r.metrics?.consistencyScore ?? 1) < 0.8)) {
715
+ recommendations.push(
716
+ "Improve cross-module consistency to reduce AI confusion"
717
+ );
718
+ }
719
+ return {
720
+ results,
721
+ summary: {
722
+ filesAnalyzed: filePaths.length,
723
+ totalIssues: results.reduce((acc, r) => acc + r.issues.length, 0),
724
+ namingIssues: namingIssues.length,
725
+ patternIssues: patternIssues.length,
726
+ architectureIssues: 0
727
+ },
728
+ recommendations,
729
+ metadata: {
730
+ toolName: "naming-consistency",
731
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
732
+ }
733
+ };
734
+ }
735
+ function shouldIncludeSeverity(severity, minSeverity) {
736
+ return getSeverityLevel(severity) >= getSeverityLevel(minSeverity);
737
+ }
738
+ function getIssueType(type) {
739
+ if (!type) return IssueType.NamingInconsistency;
740
+ const typeMap = {
741
+ "naming-inconsistency": IssueType.NamingInconsistency,
742
+ "naming-quality": IssueType.NamingQuality,
743
+ "pattern-inconsistency": IssueType.PatternInconsistency,
744
+ "architecture-inconsistency": IssueType.ArchitectureInconsistency,
745
+ "error-handling": IssueType.PatternInconsistency,
746
+ "async-style": IssueType.PatternInconsistency,
747
+ "import-style": IssueType.PatternInconsistency,
748
+ "api-design": IssueType.PatternInconsistency
749
+ };
750
+ return typeMap[type] || IssueType.NamingInconsistency;
751
+ }
752
+ function transformToIssue(i) {
753
+ if (i.message && i.location) {
754
+ return {
755
+ type: getIssueType(i.type),
756
+ severity: i.severity,
757
+ message: i.message,
758
+ location: i.location,
759
+ suggestion: i.suggestion
760
+ };
761
+ }
762
+ if (i.identifier || i.type) {
763
+ const line = i.line || 1;
764
+ const column = i.column || 1;
765
+ return {
766
+ type: getIssueType(i.type),
767
+ severity: i.severity,
768
+ message: i.suggestion ? `Naming issue: ${i.suggestion}` : `Naming issue for '${i.identifier || "unknown"}'`,
769
+ location: {
770
+ file: i.file || i.fileName || "",
771
+ line,
772
+ column,
773
+ endLine: line,
774
+ endColumn: column + (i.identifier?.length || 10)
775
+ },
776
+ suggestion: i.suggestion
777
+ };
778
+ }
779
+ if (i.description || i.files) {
780
+ const fileName = Array.isArray(i.files) ? i.files[0] : i.file || "";
781
+ return {
782
+ type: getIssueType(i.type),
783
+ severity: i.severity,
784
+ message: i.description || "Pattern inconsistency found",
785
+ location: {
786
+ file: fileName,
787
+ line: 1,
788
+ column: 1,
789
+ endLine: 1,
790
+ endColumn: 10
791
+ },
792
+ suggestion: i.examples?.[0]
793
+ };
794
+ }
795
+ return {
796
+ type: getIssueType(i.type),
797
+ severity: i.severity,
798
+ message: i.message || "Unknown issue",
799
+ location: i.location || { file: "", line: 1, column: 1 },
800
+ suggestion: i.suggestion
801
+ };
802
+ }
803
+ function calculateConsistencyScore(issues) {
804
+ let totalWeight = 0;
805
+ for (const issue of issues) {
806
+ const val = getSeverityLevel(issue.severity);
807
+ switch (val) {
808
+ case 4:
809
+ totalWeight += 10;
810
+ break;
811
+ case 3:
812
+ totalWeight += 5;
813
+ break;
814
+ case 2:
815
+ totalWeight += 2;
816
+ break;
817
+ case 1:
818
+ totalWeight += 1;
819
+ break;
820
+ default:
821
+ totalWeight += 1;
822
+ }
823
+ }
824
+ return Math.max(0, 1 - totalWeight / 100);
825
+ }
826
+
827
+ export {
828
+ analyzeNamingAST,
829
+ analyzePatterns,
830
+ analyzeConsistency
831
+ };