@aiready/consistency 0.6.17 → 0.7.1

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,1497 @@
1
+ // src/analyzers/naming-constants.ts
2
+ var COMMON_SHORT_WORDS = /* @__PURE__ */ new Set([
3
+ // Full English words (1-3 letters)
4
+ "day",
5
+ "key",
6
+ "net",
7
+ "to",
8
+ "go",
9
+ "for",
10
+ "not",
11
+ "new",
12
+ "old",
13
+ "top",
14
+ "end",
15
+ "run",
16
+ "try",
17
+ "use",
18
+ "get",
19
+ "set",
20
+ "add",
21
+ "put",
22
+ "map",
23
+ "log",
24
+ "row",
25
+ "col",
26
+ "tab",
27
+ "box",
28
+ "div",
29
+ "nav",
30
+ "tag",
31
+ "any",
32
+ "all",
33
+ "one",
34
+ "two",
35
+ "out",
36
+ "off",
37
+ "on",
38
+ "yes",
39
+ "no",
40
+ "now",
41
+ "max",
42
+ "min",
43
+ "sum",
44
+ "avg",
45
+ "ref",
46
+ "src",
47
+ "dst",
48
+ "raw",
49
+ "def",
50
+ "sub",
51
+ "pub",
52
+ "pre",
53
+ "mid",
54
+ "alt",
55
+ "opt",
56
+ "tmp",
57
+ "ext",
58
+ "sep",
59
+ // Prepositions and conjunctions
60
+ "and",
61
+ "from",
62
+ "how",
63
+ "pad",
64
+ "bar",
65
+ "non",
66
+ // Additional full words commonly flagged
67
+ "tax",
68
+ "cat",
69
+ "dog",
70
+ "car",
71
+ "bus",
72
+ "web",
73
+ "app",
74
+ "war",
75
+ "law",
76
+ "pay",
77
+ "buy",
78
+ "win",
79
+ "cut",
80
+ "hit",
81
+ "hot",
82
+ "pop",
83
+ "job",
84
+ "age",
85
+ "act",
86
+ "let",
87
+ "lot",
88
+ "bad",
89
+ "big",
90
+ "far",
91
+ "few",
92
+ "own",
93
+ "per",
94
+ "red",
95
+ "low",
96
+ "see",
97
+ "six",
98
+ "ten",
99
+ "way",
100
+ "who",
101
+ "why",
102
+ "yet",
103
+ "via",
104
+ "due",
105
+ "fee",
106
+ "fun",
107
+ "gas",
108
+ "gay",
109
+ "god",
110
+ "gun",
111
+ "guy",
112
+ "ice",
113
+ "ill",
114
+ "kid",
115
+ "mad",
116
+ "man",
117
+ "mix",
118
+ "mom",
119
+ "mrs",
120
+ "nor",
121
+ "odd",
122
+ "oil",
123
+ "pan",
124
+ "pet",
125
+ "pit",
126
+ "pot",
127
+ "pow",
128
+ "pro",
129
+ "raw",
130
+ "rep",
131
+ "rid",
132
+ "sad",
133
+ "sea",
134
+ "sit",
135
+ "sky",
136
+ "son",
137
+ "tea",
138
+ "tie",
139
+ "tip",
140
+ "van",
141
+ "war",
142
+ "win",
143
+ "won"
144
+ ]);
145
+ var ACCEPTABLE_ABBREVIATIONS = /* @__PURE__ */ new Set([
146
+ // Standard identifiers
147
+ "id",
148
+ "uid",
149
+ "gid",
150
+ "pid",
151
+ // Loop counters and iterators
152
+ "i",
153
+ "j",
154
+ "k",
155
+ "n",
156
+ "m",
157
+ // Web/Network
158
+ "url",
159
+ "uri",
160
+ "api",
161
+ "cdn",
162
+ "dns",
163
+ "ip",
164
+ "tcp",
165
+ "udp",
166
+ "http",
167
+ "ssl",
168
+ "tls",
169
+ "utm",
170
+ "seo",
171
+ "rss",
172
+ "xhr",
173
+ "ajax",
174
+ "cors",
175
+ "ws",
176
+ "wss",
177
+ // Data formats
178
+ "json",
179
+ "xml",
180
+ "yaml",
181
+ "csv",
182
+ "html",
183
+ "css",
184
+ "svg",
185
+ "pdf",
186
+ // File types & extensions
187
+ "img",
188
+ "txt",
189
+ "doc",
190
+ "docx",
191
+ "xlsx",
192
+ "ppt",
193
+ "md",
194
+ "rst",
195
+ "jpg",
196
+ "png",
197
+ "gif",
198
+ // Databases
199
+ "db",
200
+ "sql",
201
+ "orm",
202
+ "dao",
203
+ "dto",
204
+ "ddb",
205
+ "rds",
206
+ "nosql",
207
+ // File system
208
+ "fs",
209
+ "dir",
210
+ "tmp",
211
+ "src",
212
+ "dst",
213
+ "bin",
214
+ "lib",
215
+ "pkg",
216
+ // Operating system
217
+ "os",
218
+ "env",
219
+ "arg",
220
+ "cli",
221
+ "cmd",
222
+ "exe",
223
+ "cwd",
224
+ "pwd",
225
+ // UI/UX
226
+ "ui",
227
+ "ux",
228
+ "gui",
229
+ "dom",
230
+ "ref",
231
+ // Request/Response
232
+ "req",
233
+ "res",
234
+ "ctx",
235
+ "err",
236
+ "msg",
237
+ "auth",
238
+ // Mathematics/Computing
239
+ "max",
240
+ "min",
241
+ "avg",
242
+ "sum",
243
+ "abs",
244
+ "cos",
245
+ "sin",
246
+ "tan",
247
+ "log",
248
+ "exp",
249
+ "pow",
250
+ "sqrt",
251
+ "std",
252
+ "var",
253
+ "int",
254
+ "num",
255
+ "idx",
256
+ // Time
257
+ "now",
258
+ "utc",
259
+ "tz",
260
+ "ms",
261
+ "sec",
262
+ "hr",
263
+ "min",
264
+ "yr",
265
+ "mo",
266
+ // Common patterns
267
+ "app",
268
+ "cfg",
269
+ "config",
270
+ "init",
271
+ "len",
272
+ "val",
273
+ "str",
274
+ "obj",
275
+ "arr",
276
+ "gen",
277
+ "def",
278
+ "raw",
279
+ "new",
280
+ "old",
281
+ "pre",
282
+ "post",
283
+ "sub",
284
+ "pub",
285
+ // Programming/Framework specific
286
+ "ts",
287
+ "js",
288
+ "jsx",
289
+ "tsx",
290
+ "py",
291
+ "rb",
292
+ "vue",
293
+ "re",
294
+ "fn",
295
+ "fns",
296
+ "mod",
297
+ "opts",
298
+ "dev",
299
+ // Cloud/Infrastructure
300
+ "s3",
301
+ "ec2",
302
+ "sqs",
303
+ "sns",
304
+ "vpc",
305
+ "ami",
306
+ "iam",
307
+ "acl",
308
+ "elb",
309
+ "alb",
310
+ "nlb",
311
+ "aws",
312
+ "ses",
313
+ "gst",
314
+ "cdk",
315
+ "btn",
316
+ "buf",
317
+ "agg",
318
+ "ocr",
319
+ "ai",
320
+ "cf",
321
+ "cfn",
322
+ "ga",
323
+ // Metrics/Performance
324
+ "fcp",
325
+ "lcp",
326
+ "cls",
327
+ "ttfb",
328
+ "tti",
329
+ "fid",
330
+ "fps",
331
+ "qps",
332
+ "rps",
333
+ "tps",
334
+ "wpm",
335
+ // Testing & i18n
336
+ "po",
337
+ "e2e",
338
+ "a11y",
339
+ "i18n",
340
+ "l10n",
341
+ "spy",
342
+ // Domain-specific abbreviations (context-aware)
343
+ "sk",
344
+ "fy",
345
+ "faq",
346
+ "og",
347
+ "seo",
348
+ "cta",
349
+ "roi",
350
+ "kpi",
351
+ "ttl",
352
+ "pct",
353
+ // Technical abbreviations
354
+ "mac",
355
+ "hex",
356
+ "esm",
357
+ "git",
358
+ "rec",
359
+ "loc",
360
+ "dup",
361
+ // Boolean helpers (these are intentional short names)
362
+ "is",
363
+ "has",
364
+ "can",
365
+ "did",
366
+ "was",
367
+ "are",
368
+ // Date/Time context (when in date contexts)
369
+ "d",
370
+ "t",
371
+ "dt",
372
+ // Coverage metrics (industry standard: statements/branches/functions/lines)
373
+ "s",
374
+ "b",
375
+ "f",
376
+ "l",
377
+ // Common media/content abbreviations
378
+ "vid",
379
+ "pic",
380
+ "img",
381
+ "doc",
382
+ "msg"
383
+ ]);
384
+ function snakeCaseToCamelCase(str) {
385
+ return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
386
+ }
387
+ function detectNamingConventions(files, allIssues) {
388
+ const camelCaseCount = allIssues.filter((i) => i.type === "convention-mix").length;
389
+ const totalChecks = files.length * 10;
390
+ if (camelCaseCount / totalChecks > 0.3) {
391
+ return { dominantConvention: "mixed", conventionScore: 0.5 };
392
+ }
393
+ return { dominantConvention: "camelCase", conventionScore: 0.9 };
394
+ }
395
+
396
+ // src/utils/ast-parser.ts
397
+ import { parse } from "@typescript-eslint/typescript-estree";
398
+ import { readFileSync } from "fs";
399
+ function parseFile(filePath, content) {
400
+ try {
401
+ const code = content ?? readFileSync(filePath, "utf-8");
402
+ const isTypeScript = filePath.match(/\.tsx?$/);
403
+ return parse(code, {
404
+ jsx: filePath.match(/\.[jt]sx$/i) !== null,
405
+ loc: true,
406
+ range: true,
407
+ comment: false,
408
+ tokens: false,
409
+ // Relaxed parsing for JavaScript files
410
+ sourceType: "module",
411
+ ecmaVersion: "latest",
412
+ // Only use TypeScript parser features for .ts/.tsx files
413
+ filePath: isTypeScript ? filePath : void 0
414
+ });
415
+ } catch (error) {
416
+ return null;
417
+ }
418
+ }
419
+ function traverseAST(node, visitor, parent = null) {
420
+ if (!node) return;
421
+ visitor.enter?.(node, parent);
422
+ for (const key of Object.keys(node)) {
423
+ const value = node[key];
424
+ if (Array.isArray(value)) {
425
+ for (const child of value) {
426
+ if (child && typeof child === "object" && "type" in child) {
427
+ traverseAST(child, visitor, node);
428
+ }
429
+ }
430
+ } else if (value && typeof value === "object" && "type" in value) {
431
+ traverseAST(value, visitor, node);
432
+ }
433
+ }
434
+ visitor.leave?.(node, parent);
435
+ }
436
+ function isLoopStatement(node) {
437
+ return [
438
+ "ForStatement",
439
+ "ForInStatement",
440
+ "ForOfStatement",
441
+ "WhileStatement",
442
+ "DoWhileStatement"
443
+ ].includes(node.type);
444
+ }
445
+ function getFunctionName(node) {
446
+ switch (node.type) {
447
+ case "FunctionDeclaration":
448
+ return node.id?.name ?? null;
449
+ case "FunctionExpression":
450
+ return node.id?.name ?? null;
451
+ case "ArrowFunctionExpression":
452
+ return null;
453
+ // Arrow functions don't have names directly
454
+ case "MethodDefinition":
455
+ if (node.key.type === "Identifier") {
456
+ return node.key.name;
457
+ }
458
+ return null;
459
+ default:
460
+ return null;
461
+ }
462
+ }
463
+ function getLineNumber(node) {
464
+ return node.loc?.start.line ?? 0;
465
+ }
466
+ function isCoverageContext(node, ancestors) {
467
+ const coveragePatterns = /coverage|summary|metrics|pct|percent|statements|branches|functions|lines/i;
468
+ if (node.type === "Identifier" && coveragePatterns.test(node.name)) {
469
+ return true;
470
+ }
471
+ for (const ancestor of ancestors.slice(-3)) {
472
+ if (ancestor.type === "MemberExpression") {
473
+ const memberExpr = ancestor;
474
+ if (memberExpr.object.type === "Identifier" && coveragePatterns.test(memberExpr.object.name)) {
475
+ return true;
476
+ }
477
+ }
478
+ if (ancestor.type === "ObjectPattern" || ancestor.type === "ObjectExpression") {
479
+ const parent = ancestors[ancestors.indexOf(ancestor) - 1];
480
+ if (parent?.type === "VariableDeclarator") {
481
+ const varDecl = parent;
482
+ if (varDecl.id.type === "Identifier" && coveragePatterns.test(varDecl.id.name)) {
483
+ return true;
484
+ }
485
+ }
486
+ }
487
+ }
488
+ return false;
489
+ }
490
+
491
+ // src/utils/scope-tracker.ts
492
+ var ScopeTracker = class {
493
+ constructor(rootNode) {
494
+ this.allScopes = [];
495
+ this.rootScope = {
496
+ type: "global",
497
+ node: rootNode,
498
+ parent: null,
499
+ children: [],
500
+ variables: /* @__PURE__ */ new Map()
501
+ };
502
+ this.currentScope = this.rootScope;
503
+ this.allScopes.push(this.rootScope);
504
+ }
505
+ /**
506
+ * Enter a new scope
507
+ */
508
+ enterScope(type, node) {
509
+ const newScope = {
510
+ type,
511
+ node,
512
+ parent: this.currentScope,
513
+ children: [],
514
+ variables: /* @__PURE__ */ new Map()
515
+ };
516
+ this.currentScope.children.push(newScope);
517
+ this.currentScope = newScope;
518
+ this.allScopes.push(newScope);
519
+ }
520
+ /**
521
+ * Exit current scope and return to parent
522
+ */
523
+ exitScope() {
524
+ if (this.currentScope.parent) {
525
+ this.currentScope = this.currentScope.parent;
526
+ }
527
+ }
528
+ /**
529
+ * Declare a variable in the current scope
530
+ */
531
+ declareVariable(name, node, line, options = {}) {
532
+ const varInfo = {
533
+ name,
534
+ node,
535
+ declarationLine: line,
536
+ references: [],
537
+ type: options.type,
538
+ isParameter: options.isParameter ?? false,
539
+ isDestructured: options.isDestructured ?? false,
540
+ isLoopVariable: options.isLoopVariable ?? false
541
+ };
542
+ this.currentScope.variables.set(name, varInfo);
543
+ }
544
+ /**
545
+ * Add a reference to a variable
546
+ */
547
+ addReference(name, node) {
548
+ const varInfo = this.findVariable(name);
549
+ if (varInfo) {
550
+ varInfo.references.push(node);
551
+ }
552
+ }
553
+ /**
554
+ * Find a variable in current or parent scopes
555
+ */
556
+ findVariable(name) {
557
+ let scope = this.currentScope;
558
+ while (scope) {
559
+ const varInfo = scope.variables.get(name);
560
+ if (varInfo) {
561
+ return varInfo;
562
+ }
563
+ scope = scope.parent;
564
+ }
565
+ return null;
566
+ }
567
+ /**
568
+ * Get all variables in current scope (not including parent scopes)
569
+ */
570
+ getCurrentScopeVariables() {
571
+ return Array.from(this.currentScope.variables.values());
572
+ }
573
+ /**
574
+ * Get all variables across all scopes
575
+ */
576
+ getAllVariables() {
577
+ const allVars = [];
578
+ for (const scope of this.allScopes) {
579
+ allVars.push(...Array.from(scope.variables.values()));
580
+ }
581
+ return allVars;
582
+ }
583
+ /**
584
+ * Calculate actual usage count (references minus declaration)
585
+ */
586
+ getUsageCount(varInfo) {
587
+ return varInfo.references.length;
588
+ }
589
+ /**
590
+ * Check if a variable is short-lived (used within N lines)
591
+ */
592
+ isShortLived(varInfo, maxLines = 5) {
593
+ if (varInfo.references.length === 0) {
594
+ return false;
595
+ }
596
+ const declarationLine = varInfo.declarationLine;
597
+ const maxUsageLine = Math.max(
598
+ ...varInfo.references.map((ref) => ref.loc?.start.line ?? declarationLine)
599
+ );
600
+ return maxUsageLine - declarationLine <= maxLines;
601
+ }
602
+ /**
603
+ * Check if a variable is used in a limited scope (e.g., only in one callback)
604
+ */
605
+ isLocallyScoped(varInfo) {
606
+ if (varInfo.references.length === 0) return false;
607
+ const lines = varInfo.references.map((ref) => ref.loc?.start.line ?? 0);
608
+ const minLine = Math.min(...lines);
609
+ const maxLine = Math.max(...lines);
610
+ return maxLine - minLine <= 3;
611
+ }
612
+ /**
613
+ * Get current scope type
614
+ */
615
+ getCurrentScopeType() {
616
+ return this.currentScope.type;
617
+ }
618
+ /**
619
+ * Check if currently in a loop scope
620
+ */
621
+ isInLoop() {
622
+ let scope = this.currentScope;
623
+ while (scope) {
624
+ if (scope.type === "loop") {
625
+ return true;
626
+ }
627
+ scope = scope.parent;
628
+ }
629
+ return false;
630
+ }
631
+ /**
632
+ * Check if currently in a function scope
633
+ */
634
+ isInFunction() {
635
+ let scope = this.currentScope;
636
+ while (scope) {
637
+ if (scope.type === "function") {
638
+ return true;
639
+ }
640
+ scope = scope.parent;
641
+ }
642
+ return false;
643
+ }
644
+ /**
645
+ * Get the root scope
646
+ */
647
+ getRootScope() {
648
+ return this.rootScope;
649
+ }
650
+ };
651
+
652
+ // src/utils/context-detector.ts
653
+ function detectFileType(filePath, ast) {
654
+ const path = filePath.toLowerCase();
655
+ if (path.match(/\.(test|spec)\.(ts|tsx|js|jsx)$/) || path.includes("__tests__")) {
656
+ return "test";
657
+ }
658
+ if (path.endsWith(".d.ts") || path.includes("types")) {
659
+ return "types";
660
+ }
661
+ if (path.match(/config|\.config\.|rc\.|setup/) || path.includes("configuration")) {
662
+ return "config";
663
+ }
664
+ return "production";
665
+ }
666
+ function detectCodeLayer(ast) {
667
+ let hasAPIIndicators = 0;
668
+ let hasBusinessIndicators = 0;
669
+ let hasDataIndicators = 0;
670
+ let hasUtilityIndicators = 0;
671
+ traverseAST(ast, {
672
+ enter: (node) => {
673
+ if (node.type === "ImportDeclaration") {
674
+ const source = node.source.value;
675
+ if (source.match(/express|fastify|koa|@nestjs|axios|fetch|http/i)) {
676
+ hasAPIIndicators++;
677
+ }
678
+ if (source.match(/database|prisma|typeorm|sequelize|mongoose|pg|mysql/i)) {
679
+ hasDataIndicators++;
680
+ }
681
+ }
682
+ if (node.type === "FunctionDeclaration" && node.id) {
683
+ const name = node.id.name;
684
+ if (name.match(/^(get|post|put|delete|patch|handle|api|route|controller)/i)) {
685
+ hasAPIIndicators++;
686
+ }
687
+ if (name.match(/^(calculate|process|validate|transform|compute|analyze)/i)) {
688
+ hasBusinessIndicators++;
689
+ }
690
+ if (name.match(/^(find|create|update|delete|save|fetch|query|insert)/i)) {
691
+ hasDataIndicators++;
692
+ }
693
+ if (name.match(/^(format|parse|convert|normalize|sanitize|encode|decode)/i)) {
694
+ hasUtilityIndicators++;
695
+ }
696
+ }
697
+ if (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") {
698
+ if (node.type === "ExportNamedDeclaration" && node.declaration) {
699
+ if (node.declaration.type === "FunctionDeclaration" && node.declaration.id) {
700
+ const name = node.declaration.id.name;
701
+ if (name.match(/handler|route|api|controller/i)) {
702
+ hasAPIIndicators += 2;
703
+ }
704
+ }
705
+ }
706
+ }
707
+ }
708
+ });
709
+ const scores = {
710
+ api: hasAPIIndicators,
711
+ business: hasBusinessIndicators,
712
+ data: hasDataIndicators,
713
+ utility: hasUtilityIndicators
714
+ };
715
+ const maxScore = Math.max(...Object.values(scores));
716
+ if (maxScore === 0) {
717
+ return "unknown";
718
+ }
719
+ if (scores.api === maxScore) return "api";
720
+ if (scores.data === maxScore) return "data";
721
+ if (scores.business === maxScore) return "business";
722
+ if (scores.utility === maxScore) return "utility";
723
+ return "unknown";
724
+ }
725
+ function calculateComplexity(node) {
726
+ let complexity = 1;
727
+ traverseAST(node, {
728
+ enter: (childNode) => {
729
+ switch (childNode.type) {
730
+ case "IfStatement":
731
+ case "ConditionalExpression":
732
+ // ternary
733
+ case "SwitchCase":
734
+ case "ForStatement":
735
+ case "ForInStatement":
736
+ case "ForOfStatement":
737
+ case "WhileStatement":
738
+ case "DoWhileStatement":
739
+ case "CatchClause":
740
+ complexity++;
741
+ break;
742
+ case "LogicalExpression":
743
+ if (childNode.operator === "&&" || childNode.operator === "||") {
744
+ complexity++;
745
+ }
746
+ break;
747
+ }
748
+ }
749
+ });
750
+ return complexity;
751
+ }
752
+ function buildCodeContext(filePath, ast) {
753
+ const fileType = detectFileType(filePath, ast);
754
+ const codeLayer = detectCodeLayer(ast);
755
+ let totalComplexity = 0;
756
+ let functionCount = 0;
757
+ traverseAST(ast, {
758
+ enter: (node) => {
759
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
760
+ totalComplexity += calculateComplexity(node);
761
+ functionCount++;
762
+ }
763
+ }
764
+ });
765
+ const avgComplexity = functionCount > 0 ? totalComplexity / functionCount : 1;
766
+ return {
767
+ fileType,
768
+ codeLayer,
769
+ complexity: Math.round(avgComplexity),
770
+ isTestFile: fileType === "test",
771
+ isTypeDefinition: fileType === "types"
772
+ };
773
+ }
774
+ function adjustSeverity(baseSeverity, context, issueType) {
775
+ if (context.isTestFile) {
776
+ if (baseSeverity === "minor") return "info";
777
+ if (baseSeverity === "major") return "minor";
778
+ }
779
+ if (context.isTypeDefinition) {
780
+ if (baseSeverity === "minor") return "info";
781
+ }
782
+ if (context.codeLayer === "api") {
783
+ if (baseSeverity === "info" && issueType === "unclear") return "minor";
784
+ if (baseSeverity === "minor" && issueType === "unclear") return "major";
785
+ }
786
+ if (context.complexity > 10) {
787
+ if (baseSeverity === "info") return "minor";
788
+ }
789
+ if (context.codeLayer === "utility") {
790
+ if (baseSeverity === "minor" && issueType === "abbreviation") return "info";
791
+ }
792
+ return baseSeverity;
793
+ }
794
+ function isAcceptableInContext(name, context, options) {
795
+ if (options.isLoopVariable && ["i", "j", "k", "l", "n", "m"].includes(name)) {
796
+ return true;
797
+ }
798
+ if (context.isTestFile) {
799
+ if (["a", "b", "c", "x", "y", "z"].includes(name) && options.isParameter) {
800
+ return true;
801
+ }
802
+ }
803
+ if (context.codeLayer === "utility" && ["x", "y", "z"].includes(name)) {
804
+ return true;
805
+ }
806
+ if (options.isDestructured) {
807
+ if (["s", "b", "f", "l"].includes(name)) {
808
+ return true;
809
+ }
810
+ }
811
+ if (options.isParameter && (options.complexity ?? context.complexity) < 3) {
812
+ if (name.length >= 2) {
813
+ return true;
814
+ }
815
+ }
816
+ return false;
817
+ }
818
+
819
+ // src/utils/config-loader.ts
820
+ import { loadConfig } from "@aiready/core";
821
+ import { dirname } from "path";
822
+ async function loadNamingConfig(files) {
823
+ const rootDir = files.length > 0 ? dirname(files[0]) : process.cwd();
824
+ const config = await loadConfig(rootDir);
825
+ const consistencyConfig = config?.tools?.["consistency"];
826
+ const customAbbreviations = new Set(consistencyConfig?.acceptedAbbreviations || []);
827
+ const customShortWords = new Set(consistencyConfig?.shortWords || []);
828
+ const disabledChecks = new Set(consistencyConfig?.disableChecks || []);
829
+ const allAbbreviations = /* @__PURE__ */ new Set([...ACCEPTABLE_ABBREVIATIONS, ...customAbbreviations]);
830
+ const allShortWords = /* @__PURE__ */ new Set([...COMMON_SHORT_WORDS, ...customShortWords]);
831
+ return {
832
+ customAbbreviations,
833
+ customShortWords,
834
+ disabledChecks,
835
+ allAbbreviations,
836
+ allShortWords
837
+ };
838
+ }
839
+
840
+ // src/analyzers/naming-ast.ts
841
+ async function analyzeNamingAST(files) {
842
+ const issues = [];
843
+ const { allAbbreviations, allShortWords, disabledChecks } = await loadNamingConfig(files);
844
+ const supportedFiles = files.filter(
845
+ (file) => /\.(js|jsx|ts|tsx)$/i.test(file)
846
+ );
847
+ for (const file of supportedFiles) {
848
+ try {
849
+ const ast = parseFile(file);
850
+ if (!ast) continue;
851
+ const fileIssues = analyzeFileNamingAST(
852
+ file,
853
+ ast,
854
+ allAbbreviations,
855
+ allShortWords,
856
+ disabledChecks
857
+ );
858
+ issues.push(...fileIssues);
859
+ } catch (error) {
860
+ console.warn(`Skipping ${file} due to parse error:`, error);
861
+ }
862
+ }
863
+ return issues;
864
+ }
865
+ function analyzeFileNamingAST(file, ast, allAbbreviations, allShortWords, disabledChecks) {
866
+ const issues = [];
867
+ const scopeTracker = new ScopeTracker(ast);
868
+ const context = buildCodeContext(file, ast);
869
+ const ancestors = [];
870
+ traverseAST(ast, {
871
+ enter: (node, parent) => {
872
+ ancestors.push(node);
873
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
874
+ scopeTracker.enterScope("function", node);
875
+ if ("params" in node) {
876
+ for (const param of node.params) {
877
+ if (param.type === "Identifier") {
878
+ scopeTracker.declareVariable(param.name, param, getLineNumber(param), {
879
+ isParameter: true
880
+ });
881
+ } else if (param.type === "ObjectPattern" || param.type === "ArrayPattern") {
882
+ extractIdentifiersFromPattern(param, scopeTracker, true);
883
+ }
884
+ }
885
+ }
886
+ } else if (node.type === "BlockStatement") {
887
+ scopeTracker.enterScope("block", node);
888
+ } else if (isLoopStatement(node)) {
889
+ scopeTracker.enterScope("loop", node);
890
+ } else if (node.type === "ClassDeclaration") {
891
+ scopeTracker.enterScope("class", node);
892
+ }
893
+ if (node.type === "VariableDeclarator") {
894
+ if (node.id.type === "Identifier") {
895
+ const isInCoverage = isCoverageContext(node, ancestors);
896
+ scopeTracker.declareVariable(
897
+ node.id.name,
898
+ node.id,
899
+ getLineNumber(node.id),
900
+ {
901
+ type: "typeAnnotation" in node.id ? node.id.typeAnnotation : null,
902
+ isDestructured: false,
903
+ isLoopVariable: scopeTracker.getCurrentScopeType() === "loop"
904
+ }
905
+ );
906
+ } else if (node.id.type === "ObjectPattern" || node.id.type === "ArrayPattern") {
907
+ extractIdentifiersFromPattern(node.id, scopeTracker, false, ancestors);
908
+ }
909
+ }
910
+ if (node.type === "Identifier" && parent) {
911
+ if (parent.type !== "VariableDeclarator" || parent.id !== node) {
912
+ if (parent.type !== "FunctionDeclaration" || parent.id !== node) {
913
+ scopeTracker.addReference(node.name, node);
914
+ }
915
+ }
916
+ }
917
+ },
918
+ leave: (node) => {
919
+ ancestors.pop();
920
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "BlockStatement" || isLoopStatement(node) || node.type === "ClassDeclaration") {
921
+ scopeTracker.exitScope();
922
+ }
923
+ }
924
+ });
925
+ const allVariables = scopeTracker.getAllVariables();
926
+ for (const varInfo of allVariables) {
927
+ const name = varInfo.name;
928
+ const line = varInfo.declarationLine;
929
+ if (disabledChecks.has("single-letter") && name.length === 1) continue;
930
+ if (disabledChecks.has("abbreviation") && name.length <= 3) continue;
931
+ const isInCoverage = ["s", "b", "f", "l"].includes(name) && varInfo.isDestructured;
932
+ if (isInCoverage) continue;
933
+ const functionComplexity = varInfo.node.type === "Identifier" && "parent" in varInfo.node ? calculateComplexity(varInfo.node) : context.complexity;
934
+ if (isAcceptableInContext(name, context, {
935
+ isLoopVariable: varInfo.isLoopVariable || allAbbreviations.has(name),
936
+ isParameter: varInfo.isParameter,
937
+ isDestructured: varInfo.isDestructured,
938
+ complexity: functionComplexity
939
+ })) {
940
+ continue;
941
+ }
942
+ if (name.length === 1 && !allAbbreviations.has(name) && !allShortWords.has(name)) {
943
+ const isShortLived = scopeTracker.isShortLived(varInfo, 5);
944
+ if (!isShortLived) {
945
+ issues.push({
946
+ file,
947
+ line,
948
+ type: "poor-naming",
949
+ identifier: name,
950
+ severity: adjustSeverity("minor", context, "poor-naming"),
951
+ suggestion: `Use descriptive variable name instead of single letter '${name}'`
952
+ });
953
+ }
954
+ continue;
955
+ }
956
+ if (name.length >= 2 && name.length <= 3) {
957
+ if (!allShortWords.has(name.toLowerCase()) && !allAbbreviations.has(name.toLowerCase())) {
958
+ const isShortLived = scopeTracker.isShortLived(varInfo, 5);
959
+ if (!isShortLived) {
960
+ issues.push({
961
+ file,
962
+ line,
963
+ type: "abbreviation",
964
+ identifier: name,
965
+ severity: adjustSeverity("info", context, "abbreviation"),
966
+ suggestion: `Consider using full word instead of abbreviation '${name}'`
967
+ });
968
+ }
969
+ }
970
+ continue;
971
+ }
972
+ if (!disabledChecks.has("convention-mix") && file.match(/\.(ts|tsx|js|jsx)$/)) {
973
+ if (name.includes("_") && !name.startsWith("_") && name.toLowerCase() === name) {
974
+ const camelCase = name.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
975
+ issues.push({
976
+ file,
977
+ line,
978
+ type: "convention-mix",
979
+ identifier: name,
980
+ severity: adjustSeverity("minor", context, "convention-mix"),
981
+ suggestion: `Use camelCase '${camelCase}' instead of snake_case in TypeScript/JavaScript`
982
+ });
983
+ }
984
+ }
985
+ }
986
+ if (!disabledChecks.has("unclear")) {
987
+ traverseAST(ast, {
988
+ enter: (node) => {
989
+ if (node.type === "FunctionDeclaration" || node.type === "MethodDefinition") {
990
+ const name = getFunctionName(node);
991
+ if (!name) return;
992
+ const line = getLineNumber(node);
993
+ if (["main", "init", "setup", "bootstrap"].includes(name)) return;
994
+ const hasActionVerb = name.match(/^(get|set|is|has|can|should|create|update|delete|fetch|load|save|process|handle|validate|check|find|search|filter|map|reduce|make|do|run|start|stop|build|parse|format|render|calculate|compute|generate|transform|convert|normalize|sanitize|encode|decode|compress|extract|merge|split|join|sort|compare|test|verify|ensure|apply|execute|invoke|call|emit|dispatch|trigger|listen|subscribe|unsubscribe|add|remove|clear|reset|toggle|enable|disable|open|close|connect|disconnect|send|receive|read|write|import|export|register|unregister|mount|unmount|track|store|persist|upsert|derive|classify|combine|discover|activate|require|assert|expect|mask|escape|sign|put|list|complete|page|safe|mock|pick|pluralize|text|count|detect|select)/);
995
+ const isFactoryPattern = name.match(/(Factory|Builder|Creator|Generator|Provider|Adapter|Mock)$/);
996
+ const isEventHandler = name.match(/^on[A-Z]/);
997
+ const isDescriptiveLong = name.length > 15;
998
+ const isReactHook = name.match(/^use[A-Z]/);
999
+ const isHelperPattern = name.match(/^(to|from|with|without|for|as|into)\w+/) || name.match(/^\w+(To|From|With|Without|For|As|Into)\w*$/);
1000
+ const isUtilityName = ["cn", "proxy", "sitemap", "robots", "gtag"].includes(name);
1001
+ const isLanguageKeyword = ["constructor", "toString", "valueOf", "toJSON"].includes(name);
1002
+ const isFrameworkPattern = name.match(/^(goto|fill|click|select|submit|wait|expect)\w*/);
1003
+ const isDescriptivePattern = name.match(/^(default|total|count|sum|avg|max|min|initial|current|previous|next)\w+/) || name.match(/\w+(Count|Total|Sum|Average|List|Map|Set|Config|Settings|Options|Props|Data|Info|Details|State|Status|Response|Result)$/);
1004
+ const capitalCount = (name.match(/[A-Z]/g) || []).length;
1005
+ const isCompoundWord = capitalCount >= 3;
1006
+ if (!hasActionVerb && !isFactoryPattern && !isEventHandler && !isDescriptiveLong && !isReactHook && !isHelperPattern && !isUtilityName && !isDescriptivePattern && !isCompoundWord && !isLanguageKeyword && !isFrameworkPattern) {
1007
+ issues.push({
1008
+ file,
1009
+ line,
1010
+ type: "unclear",
1011
+ identifier: name,
1012
+ severity: adjustSeverity("info", context, "unclear"),
1013
+ suggestion: `Function '${name}' should start with an action verb (get, set, create, etc.)`
1014
+ });
1015
+ }
1016
+ }
1017
+ }
1018
+ });
1019
+ }
1020
+ return issues;
1021
+ }
1022
+ function extractIdentifiersFromPattern(pattern, scopeTracker, isParameter, ancestors) {
1023
+ if (pattern.type === "ObjectPattern") {
1024
+ for (const prop of pattern.properties) {
1025
+ if (prop.type === "Property" && prop.value.type === "Identifier") {
1026
+ scopeTracker.declareVariable(
1027
+ prop.value.name,
1028
+ prop.value,
1029
+ getLineNumber(prop.value),
1030
+ {
1031
+ isParameter,
1032
+ isDestructured: true
1033
+ }
1034
+ );
1035
+ } else if (prop.type === "RestElement" && prop.argument.type === "Identifier") {
1036
+ scopeTracker.declareVariable(
1037
+ prop.argument.name,
1038
+ prop.argument,
1039
+ getLineNumber(prop.argument),
1040
+ {
1041
+ isParameter,
1042
+ isDestructured: true
1043
+ }
1044
+ );
1045
+ }
1046
+ }
1047
+ } else if (pattern.type === "ArrayPattern") {
1048
+ for (const element of pattern.elements) {
1049
+ if (element && element.type === "Identifier") {
1050
+ scopeTracker.declareVariable(
1051
+ element.name,
1052
+ element,
1053
+ getLineNumber(element),
1054
+ {
1055
+ isParameter,
1056
+ isDestructured: true
1057
+ }
1058
+ );
1059
+ }
1060
+ }
1061
+ }
1062
+ }
1063
+
1064
+ // src/analyzers/patterns.ts
1065
+ import { readFileContent } from "@aiready/core";
1066
+ async function analyzePatterns(files) {
1067
+ const issues = [];
1068
+ const errorHandlingIssues = await analyzeErrorHandling(files);
1069
+ issues.push(...errorHandlingIssues);
1070
+ const asyncIssues = await analyzeAsyncPatterns(files);
1071
+ issues.push(...asyncIssues);
1072
+ const importIssues = await analyzeImportStyles(files);
1073
+ issues.push(...importIssues);
1074
+ return issues;
1075
+ }
1076
+ async function analyzeErrorHandling(files) {
1077
+ const patterns = {
1078
+ tryCatch: [],
1079
+ throwsError: [],
1080
+ returnsNull: [],
1081
+ returnsError: []
1082
+ };
1083
+ for (const file of files) {
1084
+ const content = await readFileContent(file);
1085
+ if (content.includes("try {") || content.includes("} catch")) {
1086
+ patterns.tryCatch.push(file);
1087
+ }
1088
+ if (content.match(/throw new \w*Error/)) {
1089
+ patterns.throwsError.push(file);
1090
+ }
1091
+ if (content.match(/return null/)) {
1092
+ patterns.returnsNull.push(file);
1093
+ }
1094
+ if (content.match(/return \{ error:/)) {
1095
+ patterns.returnsError.push(file);
1096
+ }
1097
+ }
1098
+ const issues = [];
1099
+ const strategiesUsed = Object.values(patterns).filter((p) => p.length > 0).length;
1100
+ if (strategiesUsed > 2) {
1101
+ issues.push({
1102
+ files: [.../* @__PURE__ */ new Set([
1103
+ ...patterns.tryCatch,
1104
+ ...patterns.throwsError,
1105
+ ...patterns.returnsNull,
1106
+ ...patterns.returnsError
1107
+ ])],
1108
+ type: "error-handling",
1109
+ description: "Inconsistent error handling strategies across codebase",
1110
+ examples: [
1111
+ patterns.tryCatch.length > 0 ? `Try-catch used in ${patterns.tryCatch.length} files` : "",
1112
+ patterns.throwsError.length > 0 ? `Throws errors in ${patterns.throwsError.length} files` : "",
1113
+ patterns.returnsNull.length > 0 ? `Returns null in ${patterns.returnsNull.length} files` : "",
1114
+ patterns.returnsError.length > 0 ? `Returns error objects in ${patterns.returnsError.length} files` : ""
1115
+ ].filter((e) => e),
1116
+ severity: "major"
1117
+ });
1118
+ }
1119
+ return issues;
1120
+ }
1121
+ async function analyzeAsyncPatterns(files) {
1122
+ const patterns = {
1123
+ asyncAwait: [],
1124
+ promises: [],
1125
+ callbacks: []
1126
+ };
1127
+ for (const file of files) {
1128
+ const content = await readFileContent(file);
1129
+ if (content.match(/async\s+(function|\(|[a-zA-Z])/)) {
1130
+ patterns.asyncAwait.push(file);
1131
+ }
1132
+ if (content.match(/\.then\(/) || content.match(/\.catch\(/)) {
1133
+ patterns.promises.push(file);
1134
+ }
1135
+ if (content.match(/callback\s*\(/) || content.match(/\(\s*err\s*,/)) {
1136
+ patterns.callbacks.push(file);
1137
+ }
1138
+ }
1139
+ const issues = [];
1140
+ if (patterns.callbacks.length > 0 && patterns.asyncAwait.length > 0) {
1141
+ issues.push({
1142
+ files: [...patterns.callbacks, ...patterns.asyncAwait],
1143
+ type: "async-style",
1144
+ description: "Mixed async patterns: callbacks and async/await",
1145
+ examples: [
1146
+ `Callbacks found in: ${patterns.callbacks.slice(0, 3).join(", ")}`,
1147
+ `Async/await used in: ${patterns.asyncAwait.slice(0, 3).join(", ")}`
1148
+ ],
1149
+ severity: "minor"
1150
+ });
1151
+ }
1152
+ if (patterns.promises.length > patterns.asyncAwait.length * 0.3 && patterns.asyncAwait.length > 0) {
1153
+ issues.push({
1154
+ files: patterns.promises,
1155
+ type: "async-style",
1156
+ description: "Consider using async/await instead of promise chains for consistency",
1157
+ examples: patterns.promises.slice(0, 5),
1158
+ severity: "info"
1159
+ });
1160
+ }
1161
+ return issues;
1162
+ }
1163
+ async function analyzeImportStyles(files) {
1164
+ const patterns = {
1165
+ esModules: [],
1166
+ commonJS: [],
1167
+ mixed: []
1168
+ };
1169
+ for (const file of files) {
1170
+ const content = await readFileContent(file);
1171
+ const hasESM = content.match(/^import\s+/m);
1172
+ const hasCJS = hasActualRequireCalls(content);
1173
+ if (hasESM && hasCJS) {
1174
+ patterns.mixed.push(file);
1175
+ } else if (hasESM) {
1176
+ patterns.esModules.push(file);
1177
+ } else if (hasCJS) {
1178
+ patterns.commonJS.push(file);
1179
+ }
1180
+ }
1181
+ const issues = [];
1182
+ if (patterns.mixed.length > 0) {
1183
+ issues.push({
1184
+ files: patterns.mixed,
1185
+ type: "import-style",
1186
+ description: "Mixed ES modules and CommonJS imports in same files",
1187
+ examples: patterns.mixed.slice(0, 5),
1188
+ severity: "major"
1189
+ });
1190
+ }
1191
+ if (patterns.esModules.length > 0 && patterns.commonJS.length > 0) {
1192
+ const ratio = patterns.commonJS.length / (patterns.esModules.length + patterns.commonJS.length);
1193
+ if (ratio > 0.2 && ratio < 0.8) {
1194
+ issues.push({
1195
+ files: [...patterns.esModules, ...patterns.commonJS],
1196
+ type: "import-style",
1197
+ description: "Inconsistent import styles across project",
1198
+ examples: [
1199
+ `ES modules: ${patterns.esModules.length} files`,
1200
+ `CommonJS: ${patterns.commonJS.length} files`
1201
+ ],
1202
+ severity: "minor"
1203
+ });
1204
+ }
1205
+ }
1206
+ return issues;
1207
+ }
1208
+ function hasActualRequireCalls(content) {
1209
+ let cleaned = content.replace(/\/\/.*$/gm, "");
1210
+ cleaned = cleaned.replace(/\/\*[\s\S]*?\*\//g, "");
1211
+ cleaned = cleaned.replace(/"[^"\n]*"/g, '""');
1212
+ cleaned = cleaned.replace(/'[^'\n]*'/g, "''");
1213
+ cleaned = cleaned.replace(/`[^`]*`/g, "``");
1214
+ cleaned = cleaned.replace(/\/[^/\n]*require[^/\n]*\/[gimsuvy]*/g, "");
1215
+ return /require\s*\(/.test(cleaned);
1216
+ }
1217
+
1218
+ // src/analyzer.ts
1219
+ import { scanFiles } from "@aiready/core";
1220
+
1221
+ // src/analyzers/naming-python.ts
1222
+ import { getParser } from "@aiready/core";
1223
+ async function analyzePythonNaming(files) {
1224
+ const issues = [];
1225
+ const parser = getParser("dummy.py");
1226
+ if (!parser) {
1227
+ console.warn("Python parser not available");
1228
+ return issues;
1229
+ }
1230
+ const pythonFiles = files.filter((f) => f.toLowerCase().endsWith(".py"));
1231
+ for (const file of pythonFiles) {
1232
+ try {
1233
+ const fs = await import("fs");
1234
+ const code = await fs.promises.readFile(file, "utf-8");
1235
+ const result = parser.parse(code, file);
1236
+ for (const exp of result.exports) {
1237
+ const nameIssue = checkPythonNaming(exp.name, exp.type, file, exp.loc?.start.line || 0);
1238
+ if (nameIssue) {
1239
+ issues.push(nameIssue);
1240
+ }
1241
+ }
1242
+ for (const imp of result.imports) {
1243
+ for (const spec of imp.specifiers) {
1244
+ if (spec !== "*" && spec !== "default") {
1245
+ const nameIssue = checkPythonNaming(spec, "variable", file, imp.loc?.start.line || 0);
1246
+ if (nameIssue) {
1247
+ issues.push(nameIssue);
1248
+ }
1249
+ }
1250
+ }
1251
+ }
1252
+ } catch (error) {
1253
+ console.warn(`Skipping ${file} due to error:`, error);
1254
+ }
1255
+ }
1256
+ return issues;
1257
+ }
1258
+ function checkPythonNaming(identifier, type, file, line) {
1259
+ const parser = getParser("dummy.py");
1260
+ const conventions = parser?.getNamingConventions();
1261
+ if (!conventions) return null;
1262
+ if (conventions.exceptions?.includes(identifier)) {
1263
+ return null;
1264
+ }
1265
+ if (type === "class") {
1266
+ if (!conventions.classPattern.test(identifier)) {
1267
+ return {
1268
+ type: "poor-naming",
1269
+ identifier,
1270
+ file,
1271
+ line,
1272
+ column: 0,
1273
+ severity: "major",
1274
+ category: "naming",
1275
+ suggestion: `Class names should use PascalCase (e.g., ${toPascalCase(identifier)})`
1276
+ };
1277
+ }
1278
+ } else if (type === "function") {
1279
+ if (!conventions.functionPattern.test(identifier)) {
1280
+ if (/^[a-z][a-zA-Z0-9]*$/.test(identifier) && /[A-Z]/.test(identifier)) {
1281
+ return {
1282
+ type: "convention-mix",
1283
+ identifier,
1284
+ file,
1285
+ line,
1286
+ column: 0,
1287
+ severity: "major",
1288
+ category: "naming",
1289
+ suggestion: `Function names should use snake_case, not camelCase (e.g., ${toSnakeCase(identifier)})`
1290
+ };
1291
+ }
1292
+ }
1293
+ } else if (type === "const" || type === "variable") {
1294
+ if (identifier === identifier.toUpperCase() && identifier.length > 1) {
1295
+ if (!conventions.constantPattern.test(identifier)) {
1296
+ return {
1297
+ type: "poor-naming",
1298
+ identifier,
1299
+ file,
1300
+ line,
1301
+ column: 0,
1302
+ severity: "minor",
1303
+ category: "naming",
1304
+ suggestion: "Constants should use UPPER_CASE_WITH_UNDERSCORES"
1305
+ };
1306
+ }
1307
+ } else {
1308
+ if (!conventions.variablePattern.test(identifier)) {
1309
+ if (/^[a-z][a-zA-Z0-9]*$/.test(identifier) && /[A-Z]/.test(identifier)) {
1310
+ return {
1311
+ type: "convention-mix",
1312
+ identifier,
1313
+ file,
1314
+ line,
1315
+ column: 0,
1316
+ severity: "major",
1317
+ category: "naming",
1318
+ suggestion: `Variable names should use snake_case, not camelCase (e.g., ${toSnakeCase(identifier)})`
1319
+ };
1320
+ }
1321
+ }
1322
+ }
1323
+ }
1324
+ return null;
1325
+ }
1326
+ function toSnakeCase(str) {
1327
+ return str.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
1328
+ }
1329
+ function toPascalCase(str) {
1330
+ return str.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
1331
+ }
1332
+
1333
+ // src/analyzer.ts
1334
+ async function analyzeConsistency(options) {
1335
+ const {
1336
+ checkNaming = true,
1337
+ checkPatterns = true,
1338
+ checkArchitecture = false,
1339
+ // Not implemented yet
1340
+ minSeverity = "info",
1341
+ ...scanOptions
1342
+ } = options;
1343
+ const filePaths = await scanFiles(scanOptions);
1344
+ const tsJsFiles = filePaths.filter((f) => /\.(ts|tsx|js|jsx)$/i.test(f));
1345
+ const pythonFiles = filePaths.filter((f) => /\.py$/i.test(f));
1346
+ let namingIssues = [];
1347
+ if (checkNaming) {
1348
+ const tsJsNamingIssues = tsJsFiles.length > 0 ? await analyzeNamingAST(tsJsFiles) : [];
1349
+ const pythonNamingIssues = pythonFiles.length > 0 ? await analyzePythonNaming(pythonFiles) : [];
1350
+ namingIssues = [...tsJsNamingIssues, ...pythonNamingIssues];
1351
+ }
1352
+ const patternIssues = checkPatterns ? await analyzePatterns(filePaths) : [];
1353
+ const results = [];
1354
+ const fileIssuesMap = /* @__PURE__ */ new Map();
1355
+ for (const issue of namingIssues) {
1356
+ if (!shouldIncludeSeverity(issue.severity, minSeverity)) {
1357
+ continue;
1358
+ }
1359
+ const consistencyIssue = {
1360
+ type: issue.type === "convention-mix" ? "naming-inconsistency" : "naming-quality",
1361
+ category: "naming",
1362
+ severity: issue.severity,
1363
+ message: `${issue.type}: ${issue.identifier}`,
1364
+ location: {
1365
+ file: issue.file,
1366
+ line: issue.line,
1367
+ column: issue.column
1368
+ },
1369
+ suggestion: issue.suggestion
1370
+ };
1371
+ if (!fileIssuesMap.has(issue.file)) {
1372
+ fileIssuesMap.set(issue.file, []);
1373
+ }
1374
+ fileIssuesMap.get(issue.file).push(consistencyIssue);
1375
+ }
1376
+ for (const issue of patternIssues) {
1377
+ if (!shouldIncludeSeverity(issue.severity, minSeverity)) {
1378
+ continue;
1379
+ }
1380
+ const consistencyIssue = {
1381
+ type: "pattern-inconsistency",
1382
+ category: "patterns",
1383
+ severity: issue.severity,
1384
+ message: issue.description,
1385
+ location: {
1386
+ file: issue.files[0] || "multiple files",
1387
+ line: 1
1388
+ },
1389
+ examples: issue.examples,
1390
+ suggestion: `Standardize ${issue.type} patterns across ${issue.files.length} files`
1391
+ };
1392
+ const firstFile = issue.files[0];
1393
+ if (firstFile && !fileIssuesMap.has(firstFile)) {
1394
+ fileIssuesMap.set(firstFile, []);
1395
+ }
1396
+ if (firstFile) {
1397
+ fileIssuesMap.get(firstFile).push(consistencyIssue);
1398
+ }
1399
+ }
1400
+ for (const [fileName, issues] of fileIssuesMap) {
1401
+ results.push({
1402
+ fileName,
1403
+ issues,
1404
+ metrics: {
1405
+ consistencyScore: calculateConsistencyScore(issues)
1406
+ }
1407
+ });
1408
+ }
1409
+ results.sort((fileResultA, fileResultB) => {
1410
+ const severityOrder = { critical: 0, major: 1, minor: 2, info: 3 };
1411
+ const maxSeverityA = Math.min(
1412
+ ...fileResultA.issues.map((i) => severityOrder[i.severity])
1413
+ );
1414
+ const maxSeverityB = Math.min(
1415
+ ...fileResultB.issues.map((i) => severityOrder[i.severity])
1416
+ );
1417
+ if (maxSeverityA !== maxSeverityB) {
1418
+ return maxSeverityA - maxSeverityB;
1419
+ }
1420
+ return fileResultB.issues.length - fileResultA.issues.length;
1421
+ });
1422
+ const recommendations = generateRecommendations(namingIssues, patternIssues);
1423
+ const namingCountFiltered = namingIssues.filter((i) => shouldIncludeSeverity(i.severity, minSeverity)).length;
1424
+ const patternCountFiltered = patternIssues.filter((i) => shouldIncludeSeverity(i.severity, minSeverity)).length;
1425
+ return {
1426
+ summary: {
1427
+ totalIssues: namingCountFiltered + patternCountFiltered,
1428
+ namingIssues: namingCountFiltered,
1429
+ patternIssues: patternCountFiltered,
1430
+ architectureIssues: 0,
1431
+ filesAnalyzed: filePaths.length
1432
+ },
1433
+ results,
1434
+ recommendations
1435
+ };
1436
+ }
1437
+ function shouldIncludeSeverity(severity, minSeverity) {
1438
+ const severityLevels = { info: 0, minor: 1, major: 2, critical: 3 };
1439
+ return severityLevels[severity] >= severityLevels[minSeverity];
1440
+ }
1441
+ function calculateConsistencyScore(issues) {
1442
+ const weights = { critical: 10, major: 5, minor: 2, info: 1 };
1443
+ const totalWeight = issues.reduce((sum, issue) => sum + weights[issue.severity], 0);
1444
+ return Math.max(0, 1 - totalWeight / 100);
1445
+ }
1446
+ function generateRecommendations(namingIssues, patternIssues) {
1447
+ const recommendations = [];
1448
+ if (namingIssues.length > 0) {
1449
+ const conventionMixCount = namingIssues.filter((i) => i.type === "convention-mix").length;
1450
+ if (conventionMixCount > 0) {
1451
+ recommendations.push(
1452
+ `Standardize naming conventions: Found ${conventionMixCount} snake_case variables in TypeScript/JavaScript (use camelCase)`
1453
+ );
1454
+ }
1455
+ const poorNamingCount = namingIssues.filter((i) => i.type === "poor-naming").length;
1456
+ if (poorNamingCount > 0) {
1457
+ recommendations.push(
1458
+ `Improve variable naming: Found ${poorNamingCount} single-letter or unclear variable names`
1459
+ );
1460
+ }
1461
+ }
1462
+ if (patternIssues.length > 0) {
1463
+ const errorHandlingIssues = patternIssues.filter((i) => i.type === "error-handling");
1464
+ if (errorHandlingIssues.length > 0) {
1465
+ recommendations.push(
1466
+ "Standardize error handling strategy across the codebase (prefer try-catch with typed errors)"
1467
+ );
1468
+ }
1469
+ const asyncIssues = patternIssues.filter((i) => i.type === "async-style");
1470
+ if (asyncIssues.length > 0) {
1471
+ recommendations.push(
1472
+ "Use async/await consistently instead of mixing with promise chains or callbacks"
1473
+ );
1474
+ }
1475
+ const importIssues = patternIssues.filter((i) => i.type === "import-style");
1476
+ if (importIssues.length > 0) {
1477
+ recommendations.push(
1478
+ "Use ES modules consistently across the project (avoid mixing with CommonJS)"
1479
+ );
1480
+ }
1481
+ }
1482
+ if (recommendations.length === 0) {
1483
+ recommendations.push("No major consistency issues found! Your codebase follows good practices.");
1484
+ }
1485
+ return recommendations;
1486
+ }
1487
+
1488
+ export {
1489
+ COMMON_SHORT_WORDS,
1490
+ ACCEPTABLE_ABBREVIATIONS,
1491
+ snakeCaseToCamelCase,
1492
+ detectNamingConventions,
1493
+ loadNamingConfig,
1494
+ analyzeNamingAST,
1495
+ analyzePatterns,
1496
+ analyzeConsistency
1497
+ };