@aiready/consistency 0.6.5 → 0.6.6

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,1352 @@
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/analyzers/naming-ast.ts
397
+ import { loadConfig } from "@aiready/core";
398
+ import { dirname } from "path";
399
+
400
+ // src/utils/ast-parser.ts
401
+ import { parse } from "@typescript-eslint/typescript-estree";
402
+ import { readFileSync } from "fs";
403
+ function parseFile(filePath, content) {
404
+ try {
405
+ const code = content ?? readFileSync(filePath, "utf-8");
406
+ const isTypeScript = filePath.match(/\.tsx?$/);
407
+ return parse(code, {
408
+ jsx: filePath.match(/\.[jt]sx$/i) !== null,
409
+ loc: true,
410
+ range: true,
411
+ comment: false,
412
+ tokens: false,
413
+ // Relaxed parsing for JavaScript files
414
+ sourceType: "module",
415
+ ecmaVersion: "latest",
416
+ // Only use TypeScript parser features for .ts/.tsx files
417
+ filePath: isTypeScript ? filePath : void 0
418
+ });
419
+ } catch (error) {
420
+ console.warn(`Failed to parse ${filePath}:`, error instanceof Error ? error.message : error);
421
+ return null;
422
+ }
423
+ }
424
+ function traverseAST(node, visitor, parent = null) {
425
+ if (!node) return;
426
+ visitor.enter?.(node, parent);
427
+ for (const key of Object.keys(node)) {
428
+ const value = node[key];
429
+ if (Array.isArray(value)) {
430
+ for (const child of value) {
431
+ if (child && typeof child === "object" && "type" in child) {
432
+ traverseAST(child, visitor, node);
433
+ }
434
+ }
435
+ } else if (value && typeof value === "object" && "type" in value) {
436
+ traverseAST(value, visitor, node);
437
+ }
438
+ }
439
+ visitor.leave?.(node, parent);
440
+ }
441
+ function isLoopStatement(node) {
442
+ return [
443
+ "ForStatement",
444
+ "ForInStatement",
445
+ "ForOfStatement",
446
+ "WhileStatement",
447
+ "DoWhileStatement"
448
+ ].includes(node.type);
449
+ }
450
+ function getFunctionName(node) {
451
+ switch (node.type) {
452
+ case "FunctionDeclaration":
453
+ return node.id?.name ?? null;
454
+ case "FunctionExpression":
455
+ return node.id?.name ?? null;
456
+ case "ArrowFunctionExpression":
457
+ return null;
458
+ // Arrow functions don't have names directly
459
+ case "MethodDefinition":
460
+ if (node.key.type === "Identifier") {
461
+ return node.key.name;
462
+ }
463
+ return null;
464
+ default:
465
+ return null;
466
+ }
467
+ }
468
+ function getLineNumber(node) {
469
+ return node.loc?.start.line ?? 0;
470
+ }
471
+ function isCoverageContext(node, ancestors) {
472
+ const coveragePatterns = /coverage|summary|metrics|pct|percent|statements|branches|functions|lines/i;
473
+ if (node.type === "Identifier" && coveragePatterns.test(node.name)) {
474
+ return true;
475
+ }
476
+ for (const ancestor of ancestors.slice(-3)) {
477
+ if (ancestor.type === "MemberExpression") {
478
+ const memberExpr = ancestor;
479
+ if (memberExpr.object.type === "Identifier" && coveragePatterns.test(memberExpr.object.name)) {
480
+ return true;
481
+ }
482
+ }
483
+ if (ancestor.type === "ObjectPattern" || ancestor.type === "ObjectExpression") {
484
+ const parent = ancestors[ancestors.indexOf(ancestor) - 1];
485
+ if (parent?.type === "VariableDeclarator") {
486
+ const varDecl = parent;
487
+ if (varDecl.id.type === "Identifier" && coveragePatterns.test(varDecl.id.name)) {
488
+ return true;
489
+ }
490
+ }
491
+ }
492
+ }
493
+ return false;
494
+ }
495
+
496
+ // src/utils/scope-tracker.ts
497
+ var ScopeTracker = class {
498
+ constructor(rootNode) {
499
+ this.allScopes = [];
500
+ this.rootScope = {
501
+ type: "global",
502
+ node: rootNode,
503
+ parent: null,
504
+ children: [],
505
+ variables: /* @__PURE__ */ new Map()
506
+ };
507
+ this.currentScope = this.rootScope;
508
+ this.allScopes.push(this.rootScope);
509
+ }
510
+ /**
511
+ * Enter a new scope
512
+ */
513
+ enterScope(type, node) {
514
+ const newScope = {
515
+ type,
516
+ node,
517
+ parent: this.currentScope,
518
+ children: [],
519
+ variables: /* @__PURE__ */ new Map()
520
+ };
521
+ this.currentScope.children.push(newScope);
522
+ this.currentScope = newScope;
523
+ this.allScopes.push(newScope);
524
+ }
525
+ /**
526
+ * Exit current scope and return to parent
527
+ */
528
+ exitScope() {
529
+ if (this.currentScope.parent) {
530
+ this.currentScope = this.currentScope.parent;
531
+ }
532
+ }
533
+ /**
534
+ * Declare a variable in the current scope
535
+ */
536
+ declareVariable(name, node, line, options = {}) {
537
+ const varInfo = {
538
+ name,
539
+ node,
540
+ declarationLine: line,
541
+ references: [],
542
+ type: options.type,
543
+ isParameter: options.isParameter ?? false,
544
+ isDestructured: options.isDestructured ?? false,
545
+ isLoopVariable: options.isLoopVariable ?? false
546
+ };
547
+ this.currentScope.variables.set(name, varInfo);
548
+ }
549
+ /**
550
+ * Add a reference to a variable
551
+ */
552
+ addReference(name, node) {
553
+ const varInfo = this.findVariable(name);
554
+ if (varInfo) {
555
+ varInfo.references.push(node);
556
+ }
557
+ }
558
+ /**
559
+ * Find a variable in current or parent scopes
560
+ */
561
+ findVariable(name) {
562
+ let scope = this.currentScope;
563
+ while (scope) {
564
+ const varInfo = scope.variables.get(name);
565
+ if (varInfo) {
566
+ return varInfo;
567
+ }
568
+ scope = scope.parent;
569
+ }
570
+ return null;
571
+ }
572
+ /**
573
+ * Get all variables in current scope (not including parent scopes)
574
+ */
575
+ getCurrentScopeVariables() {
576
+ return Array.from(this.currentScope.variables.values());
577
+ }
578
+ /**
579
+ * Get all variables across all scopes
580
+ */
581
+ getAllVariables() {
582
+ const allVars = [];
583
+ for (const scope of this.allScopes) {
584
+ allVars.push(...Array.from(scope.variables.values()));
585
+ }
586
+ return allVars;
587
+ }
588
+ /**
589
+ * Calculate actual usage count (references minus declaration)
590
+ */
591
+ getUsageCount(varInfo) {
592
+ return varInfo.references.length;
593
+ }
594
+ /**
595
+ * Check if a variable is short-lived (used within N lines)
596
+ */
597
+ isShortLived(varInfo, maxLines = 5) {
598
+ if (varInfo.references.length === 0) {
599
+ return false;
600
+ }
601
+ const declarationLine = varInfo.declarationLine;
602
+ const maxUsageLine = Math.max(
603
+ ...varInfo.references.map((ref) => ref.loc?.start.line ?? declarationLine)
604
+ );
605
+ return maxUsageLine - declarationLine <= maxLines;
606
+ }
607
+ /**
608
+ * Check if a variable is used in a limited scope (e.g., only in one callback)
609
+ */
610
+ isLocallyScoped(varInfo) {
611
+ if (varInfo.references.length === 0) return false;
612
+ const lines = varInfo.references.map((ref) => ref.loc?.start.line ?? 0);
613
+ const minLine = Math.min(...lines);
614
+ const maxLine = Math.max(...lines);
615
+ return maxLine - minLine <= 3;
616
+ }
617
+ /**
618
+ * Get current scope type
619
+ */
620
+ getCurrentScopeType() {
621
+ return this.currentScope.type;
622
+ }
623
+ /**
624
+ * Check if currently in a loop scope
625
+ */
626
+ isInLoop() {
627
+ let scope = this.currentScope;
628
+ while (scope) {
629
+ if (scope.type === "loop") {
630
+ return true;
631
+ }
632
+ scope = scope.parent;
633
+ }
634
+ return false;
635
+ }
636
+ /**
637
+ * Check if currently in a function scope
638
+ */
639
+ isInFunction() {
640
+ let scope = this.currentScope;
641
+ while (scope) {
642
+ if (scope.type === "function") {
643
+ return true;
644
+ }
645
+ scope = scope.parent;
646
+ }
647
+ return false;
648
+ }
649
+ /**
650
+ * Get the root scope
651
+ */
652
+ getRootScope() {
653
+ return this.rootScope;
654
+ }
655
+ };
656
+
657
+ // src/utils/context-detector.ts
658
+ function detectFileType(filePath, ast) {
659
+ const path = filePath.toLowerCase();
660
+ if (path.match(/\.(test|spec)\.(ts|tsx|js|jsx)$/) || path.includes("__tests__")) {
661
+ return "test";
662
+ }
663
+ if (path.endsWith(".d.ts") || path.includes("types")) {
664
+ return "types";
665
+ }
666
+ if (path.match(/config|\.config\.|rc\.|setup/) || path.includes("configuration")) {
667
+ return "config";
668
+ }
669
+ return "production";
670
+ }
671
+ function detectCodeLayer(ast) {
672
+ let hasAPIIndicators = 0;
673
+ let hasBusinessIndicators = 0;
674
+ let hasDataIndicators = 0;
675
+ let hasUtilityIndicators = 0;
676
+ traverseAST(ast, {
677
+ enter: (node) => {
678
+ if (node.type === "ImportDeclaration") {
679
+ const source = node.source.value;
680
+ if (source.match(/express|fastify|koa|@nestjs|axios|fetch|http/i)) {
681
+ hasAPIIndicators++;
682
+ }
683
+ if (source.match(/database|prisma|typeorm|sequelize|mongoose|pg|mysql/i)) {
684
+ hasDataIndicators++;
685
+ }
686
+ }
687
+ if (node.type === "FunctionDeclaration" && node.id) {
688
+ const name = node.id.name;
689
+ if (name.match(/^(get|post|put|delete|patch|handle|api|route|controller)/i)) {
690
+ hasAPIIndicators++;
691
+ }
692
+ if (name.match(/^(calculate|process|validate|transform|compute|analyze)/i)) {
693
+ hasBusinessIndicators++;
694
+ }
695
+ if (name.match(/^(find|create|update|delete|save|fetch|query|insert)/i)) {
696
+ hasDataIndicators++;
697
+ }
698
+ if (name.match(/^(format|parse|convert|normalize|sanitize|encode|decode)/i)) {
699
+ hasUtilityIndicators++;
700
+ }
701
+ }
702
+ if (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") {
703
+ if (node.type === "ExportNamedDeclaration" && node.declaration) {
704
+ if (node.declaration.type === "FunctionDeclaration" && node.declaration.id) {
705
+ const name = node.declaration.id.name;
706
+ if (name.match(/handler|route|api|controller/i)) {
707
+ hasAPIIndicators += 2;
708
+ }
709
+ }
710
+ }
711
+ }
712
+ }
713
+ });
714
+ const scores = {
715
+ api: hasAPIIndicators,
716
+ business: hasBusinessIndicators,
717
+ data: hasDataIndicators,
718
+ utility: hasUtilityIndicators
719
+ };
720
+ const maxScore = Math.max(...Object.values(scores));
721
+ if (maxScore === 0) {
722
+ return "unknown";
723
+ }
724
+ if (scores.api === maxScore) return "api";
725
+ if (scores.data === maxScore) return "data";
726
+ if (scores.business === maxScore) return "business";
727
+ if (scores.utility === maxScore) return "utility";
728
+ return "unknown";
729
+ }
730
+ function calculateComplexity(node) {
731
+ let complexity = 1;
732
+ traverseAST(node, {
733
+ enter: (childNode) => {
734
+ switch (childNode.type) {
735
+ case "IfStatement":
736
+ case "ConditionalExpression":
737
+ // ternary
738
+ case "SwitchCase":
739
+ case "ForStatement":
740
+ case "ForInStatement":
741
+ case "ForOfStatement":
742
+ case "WhileStatement":
743
+ case "DoWhileStatement":
744
+ case "CatchClause":
745
+ complexity++;
746
+ break;
747
+ case "LogicalExpression":
748
+ if (childNode.operator === "&&" || childNode.operator === "||") {
749
+ complexity++;
750
+ }
751
+ break;
752
+ }
753
+ }
754
+ });
755
+ return complexity;
756
+ }
757
+ function buildCodeContext(filePath, ast) {
758
+ const fileType = detectFileType(filePath, ast);
759
+ const codeLayer = detectCodeLayer(ast);
760
+ let totalComplexity = 0;
761
+ let functionCount = 0;
762
+ traverseAST(ast, {
763
+ enter: (node) => {
764
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
765
+ totalComplexity += calculateComplexity(node);
766
+ functionCount++;
767
+ }
768
+ }
769
+ });
770
+ const avgComplexity = functionCount > 0 ? totalComplexity / functionCount : 1;
771
+ return {
772
+ fileType,
773
+ codeLayer,
774
+ complexity: Math.round(avgComplexity),
775
+ isTestFile: fileType === "test",
776
+ isTypeDefinition: fileType === "types"
777
+ };
778
+ }
779
+ function adjustSeverity(baseSeverity, context, issueType) {
780
+ if (context.isTestFile) {
781
+ if (baseSeverity === "minor") return "info";
782
+ if (baseSeverity === "major") return "minor";
783
+ }
784
+ if (context.isTypeDefinition) {
785
+ if (baseSeverity === "minor") return "info";
786
+ }
787
+ if (context.codeLayer === "api") {
788
+ if (baseSeverity === "info" && issueType === "unclear") return "minor";
789
+ if (baseSeverity === "minor" && issueType === "unclear") return "major";
790
+ }
791
+ if (context.complexity > 10) {
792
+ if (baseSeverity === "info") return "minor";
793
+ }
794
+ if (context.codeLayer === "utility") {
795
+ if (baseSeverity === "minor" && issueType === "abbreviation") return "info";
796
+ }
797
+ return baseSeverity;
798
+ }
799
+ function isAcceptableInContext(name, context, options) {
800
+ if (options.isLoopVariable && ["i", "j", "k", "l", "n", "m"].includes(name)) {
801
+ return true;
802
+ }
803
+ if (context.isTestFile) {
804
+ if (["a", "b", "c", "x", "y", "z"].includes(name) && options.isParameter) {
805
+ return true;
806
+ }
807
+ }
808
+ if (context.codeLayer === "utility" && ["x", "y", "z"].includes(name)) {
809
+ return true;
810
+ }
811
+ if (options.isDestructured) {
812
+ if (["s", "b", "f", "l"].includes(name)) {
813
+ return true;
814
+ }
815
+ }
816
+ if (options.isParameter && (options.complexity ?? context.complexity) < 3) {
817
+ if (name.length >= 2) {
818
+ return true;
819
+ }
820
+ }
821
+ return false;
822
+ }
823
+
824
+ // src/analyzers/naming-ast.ts
825
+ async function analyzeNamingAST(files) {
826
+ const issues = [];
827
+ const rootDir = files.length > 0 ? dirname(files[0]) : process.cwd();
828
+ const config = await loadConfig(rootDir);
829
+ const consistencyConfig = config?.tools?.["consistency"];
830
+ const customAbbreviations = new Set(consistencyConfig?.acceptedAbbreviations || []);
831
+ const customShortWords = new Set(consistencyConfig?.shortWords || []);
832
+ const disabledChecks = new Set(consistencyConfig?.disableChecks || []);
833
+ const allAbbreviations = /* @__PURE__ */ new Set([...ACCEPTABLE_ABBREVIATIONS, ...customAbbreviations]);
834
+ const allShortWords = /* @__PURE__ */ new Set([...COMMON_SHORT_WORDS, ...customShortWords]);
835
+ for (const file of files) {
836
+ try {
837
+ const ast = parseFile(file);
838
+ if (!ast) continue;
839
+ const fileIssues = analyzeFileNamingAST(
840
+ file,
841
+ ast,
842
+ allAbbreviations,
843
+ allShortWords,
844
+ disabledChecks
845
+ );
846
+ issues.push(...fileIssues);
847
+ } catch (error) {
848
+ console.warn(`Skipping ${file} due to parse error:`, error);
849
+ }
850
+ }
851
+ return issues;
852
+ }
853
+ function analyzeFileNamingAST(file, ast, allAbbreviations, allShortWords, disabledChecks) {
854
+ const issues = [];
855
+ const scopeTracker = new ScopeTracker(ast);
856
+ const context = buildCodeContext(file, ast);
857
+ const ancestors = [];
858
+ traverseAST(ast, {
859
+ enter: (node, parent) => {
860
+ ancestors.push(node);
861
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
862
+ scopeTracker.enterScope("function", node);
863
+ if ("params" in node) {
864
+ for (const param of node.params) {
865
+ if (param.type === "Identifier") {
866
+ scopeTracker.declareVariable(param.name, param, getLineNumber(param), {
867
+ isParameter: true
868
+ });
869
+ } else if (param.type === "ObjectPattern" || param.type === "ArrayPattern") {
870
+ extractIdentifiersFromPattern(param, scopeTracker, true);
871
+ }
872
+ }
873
+ }
874
+ } else if (node.type === "BlockStatement") {
875
+ scopeTracker.enterScope("block", node);
876
+ } else if (isLoopStatement(node)) {
877
+ scopeTracker.enterScope("loop", node);
878
+ } else if (node.type === "ClassDeclaration") {
879
+ scopeTracker.enterScope("class", node);
880
+ }
881
+ if (node.type === "VariableDeclarator") {
882
+ if (node.id.type === "Identifier") {
883
+ const isInCoverage = isCoverageContext(node, ancestors);
884
+ scopeTracker.declareVariable(
885
+ node.id.name,
886
+ node.id,
887
+ getLineNumber(node.id),
888
+ {
889
+ type: "typeAnnotation" in node.id ? node.id.typeAnnotation : null,
890
+ isDestructured: false,
891
+ isLoopVariable: scopeTracker.getCurrentScopeType() === "loop"
892
+ }
893
+ );
894
+ } else if (node.id.type === "ObjectPattern" || node.id.type === "ArrayPattern") {
895
+ extractIdentifiersFromPattern(node.id, scopeTracker, false, ancestors);
896
+ }
897
+ }
898
+ if (node.type === "Identifier" && parent) {
899
+ if (parent.type !== "VariableDeclarator" || parent.id !== node) {
900
+ if (parent.type !== "FunctionDeclaration" || parent.id !== node) {
901
+ scopeTracker.addReference(node.name, node);
902
+ }
903
+ }
904
+ }
905
+ },
906
+ leave: (node) => {
907
+ ancestors.pop();
908
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "BlockStatement" || isLoopStatement(node) || node.type === "ClassDeclaration") {
909
+ scopeTracker.exitScope();
910
+ }
911
+ }
912
+ });
913
+ const allVariables = scopeTracker.getAllVariables();
914
+ for (const varInfo of allVariables) {
915
+ const name = varInfo.name;
916
+ const line = varInfo.declarationLine;
917
+ if (disabledChecks.has("single-letter") && name.length === 1) continue;
918
+ if (disabledChecks.has("abbreviation") && name.length <= 3) continue;
919
+ const isInCoverage = ["s", "b", "f", "l"].includes(name) && varInfo.isDestructured;
920
+ if (isInCoverage) continue;
921
+ const functionComplexity = varInfo.node.type === "Identifier" && "parent" in varInfo.node ? calculateComplexity(varInfo.node) : context.complexity;
922
+ if (isAcceptableInContext(name, context, {
923
+ isLoopVariable: varInfo.isLoopVariable || allAbbreviations.has(name),
924
+ isParameter: varInfo.isParameter,
925
+ isDestructured: varInfo.isDestructured,
926
+ complexity: functionComplexity
927
+ })) {
928
+ continue;
929
+ }
930
+ if (name.length === 1 && !allAbbreviations.has(name) && !allShortWords.has(name)) {
931
+ const isShortLived = scopeTracker.isShortLived(varInfo, 5);
932
+ if (!isShortLived) {
933
+ issues.push({
934
+ file,
935
+ line,
936
+ type: "poor-naming",
937
+ identifier: name,
938
+ severity: adjustSeverity("minor", context, "poor-naming"),
939
+ suggestion: `Use descriptive variable name instead of single letter '${name}'`
940
+ });
941
+ }
942
+ continue;
943
+ }
944
+ if (name.length >= 2 && name.length <= 3) {
945
+ if (!allShortWords.has(name.toLowerCase()) && !allAbbreviations.has(name.toLowerCase())) {
946
+ const isShortLived = scopeTracker.isShortLived(varInfo, 5);
947
+ if (!isShortLived) {
948
+ issues.push({
949
+ file,
950
+ line,
951
+ type: "abbreviation",
952
+ identifier: name,
953
+ severity: adjustSeverity("info", context, "abbreviation"),
954
+ suggestion: `Consider using full word instead of abbreviation '${name}'`
955
+ });
956
+ }
957
+ }
958
+ continue;
959
+ }
960
+ if (!disabledChecks.has("convention-mix") && file.match(/\.(ts|tsx|js|jsx)$/)) {
961
+ if (name.includes("_") && !name.startsWith("_") && name.toLowerCase() === name) {
962
+ const camelCase = name.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
963
+ issues.push({
964
+ file,
965
+ line,
966
+ type: "convention-mix",
967
+ identifier: name,
968
+ severity: adjustSeverity("minor", context, "convention-mix"),
969
+ suggestion: `Use camelCase '${camelCase}' instead of snake_case in TypeScript/JavaScript`
970
+ });
971
+ }
972
+ }
973
+ }
974
+ if (!disabledChecks.has("unclear")) {
975
+ traverseAST(ast, {
976
+ enter: (node) => {
977
+ if (node.type === "FunctionDeclaration" || node.type === "MethodDefinition") {
978
+ const name = getFunctionName(node);
979
+ if (!name) return;
980
+ const line = getLineNumber(node);
981
+ if (["main", "init", "setup", "bootstrap"].includes(name)) return;
982
+ 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)/);
983
+ const isFactoryPattern = name.match(/(Factory|Builder|Creator|Generator|Provider|Adapter|Mock)$/);
984
+ const isEventHandler = name.match(/^on[A-Z]/);
985
+ const isDescriptiveLong = name.length > 15;
986
+ const isReactHook = name.match(/^use[A-Z]/);
987
+ const isHelperPattern = name.match(/^(to|from|with|without|for|as|into)\w+/) || name.match(/^\w+(To|From|With|Without|For|As|Into)\w*$/);
988
+ const isUtilityName = ["cn", "proxy", "sitemap", "robots", "gtag"].includes(name);
989
+ const isLanguageKeyword = ["constructor", "toString", "valueOf", "toJSON"].includes(name);
990
+ const isFrameworkPattern = name.match(/^(goto|fill|click|select|submit|wait|expect)\w*/);
991
+ 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)$/);
992
+ const capitalCount = (name.match(/[A-Z]/g) || []).length;
993
+ const isCompoundWord = capitalCount >= 3;
994
+ if (!hasActionVerb && !isFactoryPattern && !isEventHandler && !isDescriptiveLong && !isReactHook && !isHelperPattern && !isUtilityName && !isDescriptivePattern && !isCompoundWord && !isLanguageKeyword && !isFrameworkPattern) {
995
+ issues.push({
996
+ file,
997
+ line,
998
+ type: "unclear",
999
+ identifier: name,
1000
+ severity: adjustSeverity("info", context, "unclear"),
1001
+ suggestion: `Function '${name}' should start with an action verb (get, set, create, etc.)`
1002
+ });
1003
+ }
1004
+ }
1005
+ }
1006
+ });
1007
+ }
1008
+ return issues;
1009
+ }
1010
+ function extractIdentifiersFromPattern(pattern, scopeTracker, isParameter, ancestors) {
1011
+ if (pattern.type === "ObjectPattern") {
1012
+ for (const prop of pattern.properties) {
1013
+ if (prop.type === "Property" && prop.value.type === "Identifier") {
1014
+ scopeTracker.declareVariable(
1015
+ prop.value.name,
1016
+ prop.value,
1017
+ getLineNumber(prop.value),
1018
+ {
1019
+ isParameter,
1020
+ isDestructured: true
1021
+ }
1022
+ );
1023
+ } else if (prop.type === "RestElement" && prop.argument.type === "Identifier") {
1024
+ scopeTracker.declareVariable(
1025
+ prop.argument.name,
1026
+ prop.argument,
1027
+ getLineNumber(prop.argument),
1028
+ {
1029
+ isParameter,
1030
+ isDestructured: true
1031
+ }
1032
+ );
1033
+ }
1034
+ }
1035
+ } else if (pattern.type === "ArrayPattern") {
1036
+ for (const element of pattern.elements) {
1037
+ if (element && element.type === "Identifier") {
1038
+ scopeTracker.declareVariable(
1039
+ element.name,
1040
+ element,
1041
+ getLineNumber(element),
1042
+ {
1043
+ isParameter,
1044
+ isDestructured: true
1045
+ }
1046
+ );
1047
+ }
1048
+ }
1049
+ }
1050
+ }
1051
+
1052
+ // src/analyzers/patterns.ts
1053
+ import { readFileContent } from "@aiready/core";
1054
+ async function analyzePatterns(files) {
1055
+ const issues = [];
1056
+ const errorHandlingIssues = await analyzeErrorHandling(files);
1057
+ issues.push(...errorHandlingIssues);
1058
+ const asyncIssues = await analyzeAsyncPatterns(files);
1059
+ issues.push(...asyncIssues);
1060
+ const importIssues = await analyzeImportStyles(files);
1061
+ issues.push(...importIssues);
1062
+ return issues;
1063
+ }
1064
+ async function analyzeErrorHandling(files) {
1065
+ const patterns = {
1066
+ tryCatch: [],
1067
+ throwsError: [],
1068
+ returnsNull: [],
1069
+ returnsError: []
1070
+ };
1071
+ for (const file of files) {
1072
+ const content = await readFileContent(file);
1073
+ if (content.includes("try {") || content.includes("} catch")) {
1074
+ patterns.tryCatch.push(file);
1075
+ }
1076
+ if (content.match(/throw new \w*Error/)) {
1077
+ patterns.throwsError.push(file);
1078
+ }
1079
+ if (content.match(/return null/)) {
1080
+ patterns.returnsNull.push(file);
1081
+ }
1082
+ if (content.match(/return \{ error:/)) {
1083
+ patterns.returnsError.push(file);
1084
+ }
1085
+ }
1086
+ const issues = [];
1087
+ const strategiesUsed = Object.values(patterns).filter((p) => p.length > 0).length;
1088
+ if (strategiesUsed > 2) {
1089
+ issues.push({
1090
+ files: [.../* @__PURE__ */ new Set([
1091
+ ...patterns.tryCatch,
1092
+ ...patterns.throwsError,
1093
+ ...patterns.returnsNull,
1094
+ ...patterns.returnsError
1095
+ ])],
1096
+ type: "error-handling",
1097
+ description: "Inconsistent error handling strategies across codebase",
1098
+ examples: [
1099
+ patterns.tryCatch.length > 0 ? `Try-catch used in ${patterns.tryCatch.length} files` : "",
1100
+ patterns.throwsError.length > 0 ? `Throws errors in ${patterns.throwsError.length} files` : "",
1101
+ patterns.returnsNull.length > 0 ? `Returns null in ${patterns.returnsNull.length} files` : "",
1102
+ patterns.returnsError.length > 0 ? `Returns error objects in ${patterns.returnsError.length} files` : ""
1103
+ ].filter((e) => e),
1104
+ severity: "major"
1105
+ });
1106
+ }
1107
+ return issues;
1108
+ }
1109
+ async function analyzeAsyncPatterns(files) {
1110
+ const patterns = {
1111
+ asyncAwait: [],
1112
+ promises: [],
1113
+ callbacks: []
1114
+ };
1115
+ for (const file of files) {
1116
+ const content = await readFileContent(file);
1117
+ if (content.match(/async\s+(function|\(|[a-zA-Z])/)) {
1118
+ patterns.asyncAwait.push(file);
1119
+ }
1120
+ if (content.match(/\.then\(/) || content.match(/\.catch\(/)) {
1121
+ patterns.promises.push(file);
1122
+ }
1123
+ if (content.match(/callback\s*\(/) || content.match(/\(\s*err\s*,/)) {
1124
+ patterns.callbacks.push(file);
1125
+ }
1126
+ }
1127
+ const issues = [];
1128
+ if (patterns.callbacks.length > 0 && patterns.asyncAwait.length > 0) {
1129
+ issues.push({
1130
+ files: [...patterns.callbacks, ...patterns.asyncAwait],
1131
+ type: "async-style",
1132
+ description: "Mixed async patterns: callbacks and async/await",
1133
+ examples: [
1134
+ `Callbacks found in: ${patterns.callbacks.slice(0, 3).join(", ")}`,
1135
+ `Async/await used in: ${patterns.asyncAwait.slice(0, 3).join(", ")}`
1136
+ ],
1137
+ severity: "minor"
1138
+ });
1139
+ }
1140
+ if (patterns.promises.length > patterns.asyncAwait.length * 0.3 && patterns.asyncAwait.length > 0) {
1141
+ issues.push({
1142
+ files: patterns.promises,
1143
+ type: "async-style",
1144
+ description: "Consider using async/await instead of promise chains for consistency",
1145
+ examples: patterns.promises.slice(0, 5),
1146
+ severity: "info"
1147
+ });
1148
+ }
1149
+ return issues;
1150
+ }
1151
+ async function analyzeImportStyles(files) {
1152
+ const patterns = {
1153
+ esModules: [],
1154
+ commonJS: [],
1155
+ mixed: []
1156
+ };
1157
+ for (const file of files) {
1158
+ const content = await readFileContent(file);
1159
+ const hasESM = content.match(/^import\s+/m);
1160
+ const hasCJS = content.match(/require\s*\(/);
1161
+ if (hasESM && hasCJS) {
1162
+ patterns.mixed.push(file);
1163
+ } else if (hasESM) {
1164
+ patterns.esModules.push(file);
1165
+ } else if (hasCJS) {
1166
+ patterns.commonJS.push(file);
1167
+ }
1168
+ }
1169
+ const issues = [];
1170
+ if (patterns.mixed.length > 0) {
1171
+ issues.push({
1172
+ files: patterns.mixed,
1173
+ type: "import-style",
1174
+ description: "Mixed ES modules and CommonJS imports in same files",
1175
+ examples: patterns.mixed.slice(0, 5),
1176
+ severity: "major"
1177
+ });
1178
+ }
1179
+ if (patterns.esModules.length > 0 && patterns.commonJS.length > 0) {
1180
+ const ratio = patterns.commonJS.length / (patterns.esModules.length + patterns.commonJS.length);
1181
+ if (ratio > 0.2 && ratio < 0.8) {
1182
+ issues.push({
1183
+ files: [...patterns.esModules, ...patterns.commonJS],
1184
+ type: "import-style",
1185
+ description: "Inconsistent import styles across project",
1186
+ examples: [
1187
+ `ES modules: ${patterns.esModules.length} files`,
1188
+ `CommonJS: ${patterns.commonJS.length} files`
1189
+ ],
1190
+ severity: "minor"
1191
+ });
1192
+ }
1193
+ }
1194
+ return issues;
1195
+ }
1196
+
1197
+ // src/analyzer.ts
1198
+ import { scanFiles } from "@aiready/core";
1199
+ async function analyzeConsistency(options) {
1200
+ const {
1201
+ checkNaming = true,
1202
+ checkPatterns = true,
1203
+ checkArchitecture = false,
1204
+ // Not implemented yet
1205
+ minSeverity = "info",
1206
+ ...scanOptions
1207
+ } = options;
1208
+ const filePaths = await scanFiles(scanOptions);
1209
+ const namingIssues = checkNaming ? await analyzeNamingAST(filePaths) : [];
1210
+ const patternIssues = checkPatterns ? await analyzePatterns(filePaths) : [];
1211
+ const results = [];
1212
+ const fileIssuesMap = /* @__PURE__ */ new Map();
1213
+ for (const issue of namingIssues) {
1214
+ if (!shouldIncludeSeverity(issue.severity, minSeverity)) {
1215
+ continue;
1216
+ }
1217
+ const consistencyIssue = {
1218
+ type: issue.type === "convention-mix" ? "naming-inconsistency" : "naming-quality",
1219
+ category: "naming",
1220
+ severity: issue.severity,
1221
+ message: `${issue.type}: ${issue.identifier}`,
1222
+ location: {
1223
+ file: issue.file,
1224
+ line: issue.line,
1225
+ column: issue.column
1226
+ },
1227
+ suggestion: issue.suggestion
1228
+ };
1229
+ if (!fileIssuesMap.has(issue.file)) {
1230
+ fileIssuesMap.set(issue.file, []);
1231
+ }
1232
+ fileIssuesMap.get(issue.file).push(consistencyIssue);
1233
+ }
1234
+ for (const issue of patternIssues) {
1235
+ if (!shouldIncludeSeverity(issue.severity, minSeverity)) {
1236
+ continue;
1237
+ }
1238
+ const consistencyIssue = {
1239
+ type: "pattern-inconsistency",
1240
+ category: "patterns",
1241
+ severity: issue.severity,
1242
+ message: issue.description,
1243
+ location: {
1244
+ file: issue.files[0] || "multiple files",
1245
+ line: 1
1246
+ },
1247
+ examples: issue.examples,
1248
+ suggestion: `Standardize ${issue.type} patterns across ${issue.files.length} files`
1249
+ };
1250
+ const firstFile = issue.files[0];
1251
+ if (firstFile && !fileIssuesMap.has(firstFile)) {
1252
+ fileIssuesMap.set(firstFile, []);
1253
+ }
1254
+ if (firstFile) {
1255
+ fileIssuesMap.get(firstFile).push(consistencyIssue);
1256
+ }
1257
+ }
1258
+ for (const [fileName, issues] of fileIssuesMap) {
1259
+ results.push({
1260
+ fileName,
1261
+ issues,
1262
+ metrics: {
1263
+ consistencyScore: calculateConsistencyScore(issues)
1264
+ }
1265
+ });
1266
+ }
1267
+ results.sort((fileResultA, fileResultB) => {
1268
+ const severityOrder = { critical: 0, major: 1, minor: 2, info: 3 };
1269
+ const maxSeverityA = Math.min(
1270
+ ...fileResultA.issues.map((i) => severityOrder[i.severity])
1271
+ );
1272
+ const maxSeverityB = Math.min(
1273
+ ...fileResultB.issues.map((i) => severityOrder[i.severity])
1274
+ );
1275
+ if (maxSeverityA !== maxSeverityB) {
1276
+ return maxSeverityA - maxSeverityB;
1277
+ }
1278
+ return fileResultB.issues.length - fileResultA.issues.length;
1279
+ });
1280
+ const recommendations = generateRecommendations(namingIssues, patternIssues);
1281
+ return {
1282
+ summary: {
1283
+ totalIssues: namingIssues.length + patternIssues.length,
1284
+ namingIssues: namingIssues.length,
1285
+ patternIssues: patternIssues.length,
1286
+ architectureIssues: 0,
1287
+ filesAnalyzed: filePaths.length
1288
+ },
1289
+ results,
1290
+ recommendations
1291
+ };
1292
+ }
1293
+ function shouldIncludeSeverity(severity, minSeverity) {
1294
+ const severityLevels = { info: 0, minor: 1, major: 2, critical: 3 };
1295
+ return severityLevels[severity] >= severityLevels[minSeverity];
1296
+ }
1297
+ function calculateConsistencyScore(issues) {
1298
+ const weights = { critical: 10, major: 5, minor: 2, info: 1 };
1299
+ const totalWeight = issues.reduce((sum, issue) => sum + weights[issue.severity], 0);
1300
+ return Math.max(0, 1 - totalWeight / 100);
1301
+ }
1302
+ function generateRecommendations(namingIssues, patternIssues) {
1303
+ const recommendations = [];
1304
+ if (namingIssues.length > 0) {
1305
+ const conventionMixCount = namingIssues.filter((i) => i.type === "convention-mix").length;
1306
+ if (conventionMixCount > 0) {
1307
+ recommendations.push(
1308
+ `Standardize naming conventions: Found ${conventionMixCount} snake_case variables in TypeScript/JavaScript (use camelCase)`
1309
+ );
1310
+ }
1311
+ const poorNamingCount = namingIssues.filter((i) => i.type === "poor-naming").length;
1312
+ if (poorNamingCount > 0) {
1313
+ recommendations.push(
1314
+ `Improve variable naming: Found ${poorNamingCount} single-letter or unclear variable names`
1315
+ );
1316
+ }
1317
+ }
1318
+ if (patternIssues.length > 0) {
1319
+ const errorHandlingIssues = patternIssues.filter((i) => i.type === "error-handling");
1320
+ if (errorHandlingIssues.length > 0) {
1321
+ recommendations.push(
1322
+ "Standardize error handling strategy across the codebase (prefer try-catch with typed errors)"
1323
+ );
1324
+ }
1325
+ const asyncIssues = patternIssues.filter((i) => i.type === "async-style");
1326
+ if (asyncIssues.length > 0) {
1327
+ recommendations.push(
1328
+ "Use async/await consistently instead of mixing with promise chains or callbacks"
1329
+ );
1330
+ }
1331
+ const importIssues = patternIssues.filter((i) => i.type === "import-style");
1332
+ if (importIssues.length > 0) {
1333
+ recommendations.push(
1334
+ "Use ES modules consistently across the project (avoid mixing with CommonJS)"
1335
+ );
1336
+ }
1337
+ }
1338
+ if (recommendations.length === 0) {
1339
+ recommendations.push("No major consistency issues found! Your codebase follows good practices.");
1340
+ }
1341
+ return recommendations;
1342
+ }
1343
+
1344
+ export {
1345
+ COMMON_SHORT_WORDS,
1346
+ ACCEPTABLE_ABBREVIATIONS,
1347
+ snakeCaseToCamelCase,
1348
+ detectNamingConventions,
1349
+ analyzeNamingAST,
1350
+ analyzePatterns,
1351
+ analyzeConsistency
1352
+ };