@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,909 @@
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/scoring.ts
526
+ import { calculateProductivityImpact, ToolName } from "@aiready/core";
527
+ function calculateConsistencyScore(issues, totalFilesAnalyzed, costConfig) {
528
+ void costConfig;
529
+ const criticalIssues = issues.filter((i) => i.severity === "critical").length;
530
+ const majorIssues = issues.filter((i) => i.severity === "major").length;
531
+ const minorIssues = issues.filter((i) => i.severity === "minor").length;
532
+ const totalIssues = issues.length;
533
+ const issuesPerFile = totalFilesAnalyzed > 0 ? totalIssues / totalFilesAnalyzed : 0;
534
+ const densityPenalty = Math.min(50, issuesPerFile * 15);
535
+ const weightedCount = criticalIssues * 10 + majorIssues * 3 + minorIssues * 0.5;
536
+ const avgWeightedIssuesPerFile = totalFilesAnalyzed > 0 ? weightedCount / totalFilesAnalyzed : 0;
537
+ const severityPenalty = Math.min(50, avgWeightedIssuesPerFile * 2);
538
+ const rawScore = 100 - densityPenalty - severityPenalty;
539
+ const score = Math.max(0, Math.min(100, Math.round(rawScore)));
540
+ const factors = [
541
+ {
542
+ name: "Issue Density",
543
+ impact: -Math.round(densityPenalty),
544
+ description: `${issuesPerFile.toFixed(2)} issues per file ${issuesPerFile < 1 ? "(excellent)" : issuesPerFile < 3 ? "(acceptable)" : "(high)"}`
545
+ }
546
+ ];
547
+ if (criticalIssues > 0) {
548
+ const criticalImpact = Math.min(30, criticalIssues * 10);
549
+ factors.push({
550
+ name: "Critical Issues",
551
+ impact: -criticalImpact,
552
+ description: `${criticalIssues} critical consistency issue${criticalIssues > 1 ? "s" : ""} (high AI confusion risk)`
553
+ });
554
+ }
555
+ if (majorIssues > 0) {
556
+ const majorImpact = Math.min(20, Math.round(majorIssues * 3));
557
+ factors.push({
558
+ name: "Major Issues",
559
+ impact: -majorImpact,
560
+ description: `${majorIssues} major issue${majorIssues > 1 ? "s" : ""} (moderate AI confusion risk)`
561
+ });
562
+ }
563
+ if (minorIssues > 0 && minorIssues >= totalFilesAnalyzed) {
564
+ const minorImpact = -Math.round(minorIssues * 0.5);
565
+ factors.push({
566
+ name: "Minor Issues",
567
+ impact: minorImpact,
568
+ description: `${minorIssues} minor issue${minorIssues > 1 ? "s" : ""} (slight AI confusion risk)`
569
+ });
570
+ }
571
+ const recommendations = [];
572
+ if (criticalIssues > 0) {
573
+ const estimatedImpact = Math.min(30, criticalIssues * 10);
574
+ recommendations.push({
575
+ action: "Fix critical naming/pattern inconsistencies (highest AI confusion risk)",
576
+ estimatedImpact,
577
+ priority: "high"
578
+ });
579
+ }
580
+ if (majorIssues > 5) {
581
+ const estimatedImpact = Math.min(15, Math.round(majorIssues / 2));
582
+ recommendations.push({
583
+ action: "Standardize naming conventions across codebase",
584
+ estimatedImpact,
585
+ priority: "medium"
586
+ });
587
+ }
588
+ if (issuesPerFile > 3) {
589
+ recommendations.push({
590
+ action: "Establish and enforce coding style guide to reduce inconsistencies",
591
+ estimatedImpact: 12,
592
+ priority: "medium"
593
+ });
594
+ }
595
+ if (totalIssues > 20 && minorIssues / totalIssues > 0.7) {
596
+ recommendations.push({
597
+ action: "Enable linter/formatter to automatically fix minor style issues",
598
+ estimatedImpact: 8,
599
+ priority: "low"
600
+ });
601
+ }
602
+ const productivityImpact = calculateProductivityImpact(issues);
603
+ return {
604
+ toolName: ToolName.NamingConsistency,
605
+ score,
606
+ rawMetrics: {
607
+ totalIssues,
608
+ criticalIssues,
609
+ majorIssues,
610
+ minorIssues,
611
+ issuesPerFile: Math.round(issuesPerFile * 100) / 100,
612
+ avgWeightedIssuesPerFile: Math.round(avgWeightedIssuesPerFile * 100) / 100,
613
+ // Business value metrics
614
+ estimatedDeveloperHours: productivityImpact.totalHours
615
+ },
616
+ factors,
617
+ recommendations
618
+ };
619
+ }
620
+
621
+ // src/analyzer.ts
622
+ import {
623
+ scanFiles,
624
+ Severity as Severity5,
625
+ IssueType,
626
+ getSeverityLevel
627
+ } from "@aiready/core";
628
+
629
+ // src/analyzers/naming-generalized.ts
630
+ import { getParser, Severity as Severity4 } from "@aiready/core";
631
+ import { readFileSync as readFileSync3 } from "fs";
632
+ var COMMON_ABBREVIATIONS = /* @__PURE__ */ new Set([
633
+ "id",
634
+ "db",
635
+ "fs",
636
+ "os",
637
+ "ip",
638
+ "ui",
639
+ "ux",
640
+ "api",
641
+ "env",
642
+ "url",
643
+ "req",
644
+ "res",
645
+ "err",
646
+ "ctx",
647
+ "cb",
648
+ "idx",
649
+ "src",
650
+ "dir",
651
+ "app",
652
+ "dev",
653
+ "qa",
654
+ "dto",
655
+ "dao",
656
+ "ref",
657
+ "ast",
658
+ "dom",
659
+ "log",
660
+ "msg",
661
+ "pkg",
662
+ "css",
663
+ "html",
664
+ "xml",
665
+ "jsx",
666
+ "tsx",
667
+ "ts",
668
+ "js"
669
+ ]);
670
+ async function analyzeNamingGeneralized(files) {
671
+ const issues = [];
672
+ for (const file of files) {
673
+ const parser = await getParser(file);
674
+ if (!parser) continue;
675
+ try {
676
+ const code = readFileSync3(file, "utf-8");
677
+ if (!code.trim()) continue;
678
+ await parser.initialize();
679
+ const result = parser.parse(code, file);
680
+ const conventions = parser.getNamingConventions();
681
+ const exceptions = new Set(conventions.exceptions || []);
682
+ for (const exp of result.exports) {
683
+ if (!exp.name || exp.name === "default") continue;
684
+ if (exceptions.has(exp.name)) continue;
685
+ if (COMMON_ABBREVIATIONS.has(exp.name.toLowerCase())) continue;
686
+ let pattern;
687
+ if (exp.type === "class") {
688
+ pattern = conventions.classPattern;
689
+ } else if (exp.type === "interface" && conventions.interfacePattern) {
690
+ pattern = conventions.interfacePattern;
691
+ } else if (exp.type === "type" && conventions.typePattern) {
692
+ pattern = conventions.typePattern;
693
+ } else if (exp.type === "function") {
694
+ if (/^[A-Z][a-zA-Z0-9]*$/.test(exp.name) || /^[A-Z][A-Z0-9_]*$/.test(exp.name)) {
695
+ continue;
696
+ }
697
+ pattern = conventions.functionPattern;
698
+ } else if (exp.type === "const") {
699
+ if ([
700
+ "handler",
701
+ "GET",
702
+ "POST",
703
+ "PUT",
704
+ "DELETE",
705
+ "PATCH",
706
+ "OPTIONS",
707
+ "HEAD"
708
+ ].includes(exp.name))
709
+ continue;
710
+ pattern = exp.isPrimitive ? conventions.constantPattern : conventions.variablePattern;
711
+ } else {
712
+ pattern = conventions.variablePattern;
713
+ }
714
+ if (pattern && !pattern.test(exp.name)) {
715
+ issues.push({
716
+ type: "naming-inconsistency",
717
+ identifier: exp.name,
718
+ file,
719
+ line: exp.loc?.start.line || 1,
720
+ column: exp.loc?.start.column || 0,
721
+ // Recalibrate naming issues to Minor to differentiate from structural/architectural issues
722
+ severity: Severity4.Minor,
723
+ category: "naming",
724
+ suggestion: `Follow ${parser.language} ${exp.type} naming convention: ${pattern.toString()}`
725
+ });
726
+ }
727
+ }
728
+ for (const imp of result.imports) {
729
+ for (const spec of imp.specifiers) {
730
+ if (!spec || spec === "*" || spec === "default") continue;
731
+ if (exceptions.has(spec)) continue;
732
+ if (COMMON_ABBREVIATIONS.has(spec.toLowerCase())) continue;
733
+ 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)) {
734
+ issues.push({
735
+ type: "naming-inconsistency",
736
+ identifier: spec,
737
+ file,
738
+ line: imp.loc?.start.line || 1,
739
+ column: imp.loc?.start.column || 0,
740
+ severity: Severity4.Info,
741
+ // Reduced from Minor to Info for imports
742
+ category: "naming",
743
+ suggestion: `Imported identifier '${spec}' may not follow standard conventions for this language.`
744
+ });
745
+ }
746
+ }
747
+ }
748
+ } catch (error) {
749
+ const errorMessage = error instanceof Error ? error.message : String(error);
750
+ console.debug(
751
+ `Consistency: Skipping unparseable file ${file}: ${errorMessage.split("\\n")[0]}`
752
+ );
753
+ }
754
+ }
755
+ return issues;
756
+ }
757
+
758
+ // src/analyzer.ts
759
+ async function analyzeConsistency(options) {
760
+ const {
761
+ checkNaming = true,
762
+ checkPatterns = true,
763
+ checkArchitecture = false,
764
+ // Not implemented yet
765
+ minSeverity = Severity5.Info,
766
+ ...scanOptions
767
+ } = options;
768
+ void checkArchitecture;
769
+ const filePaths = await scanFiles(scanOptions);
770
+ let namingIssues = [];
771
+ if (checkNaming) {
772
+ namingIssues = await analyzeNamingGeneralized(filePaths);
773
+ const tsJsFiles = filePaths.filter((f) => /\.(ts|tsx|js|jsx)$/i.test(f));
774
+ if (tsJsFiles.length > 0) {
775
+ const deepTsIssues = await analyzeNamingAST(tsJsFiles);
776
+ namingIssues = [...namingIssues, ...deepTsIssues];
777
+ }
778
+ }
779
+ const patternIssues = checkPatterns ? await analyzePatterns(filePaths) : [];
780
+ const results = [];
781
+ const fileIssuesMap = /* @__PURE__ */ new Map();
782
+ for (const issue of namingIssues) {
783
+ if (!shouldIncludeSeverity(issue.severity, minSeverity)) continue;
784
+ const fileName = issue.fileName || issue.file || issue.filePath || "unknown";
785
+ if (!fileIssuesMap.has(fileName)) fileIssuesMap.set(fileName, []);
786
+ fileIssuesMap.get(fileName).push(issue);
787
+ }
788
+ for (const issue of patternIssues) {
789
+ if (!shouldIncludeSeverity(issue.severity, minSeverity)) continue;
790
+ const fileName = issue.fileName || issue.file || issue.filePath || (Array.isArray(issue.files) ? issue.files[0] : "unknown");
791
+ if (!fileIssuesMap.has(fileName)) fileIssuesMap.set(fileName, []);
792
+ fileIssuesMap.get(fileName).push(issue);
793
+ }
794
+ for (const [fileName, issues] of fileIssuesMap.entries()) {
795
+ const scoreResult = calculateConsistencyScore(
796
+ issues,
797
+ filePaths.length
798
+ );
799
+ results.push({
800
+ fileName,
801
+ issues: issues.map((i) => transformToIssue(i)),
802
+ metrics: {
803
+ consistencyScore: scoreResult.score / 100
804
+ }
805
+ });
806
+ }
807
+ const recommendations = [];
808
+ if (namingIssues.length > 0) {
809
+ recommendations.push("Standardize naming conventions across the codebase");
810
+ }
811
+ if (patternIssues.length > 0) {
812
+ recommendations.push("Consolidate repetitive implementation patterns");
813
+ }
814
+ if (results.some((r) => (r.metrics?.consistencyScore ?? 1) < 0.8)) {
815
+ recommendations.push(
816
+ "Improve cross-module consistency to reduce AI confusion"
817
+ );
818
+ }
819
+ return {
820
+ results,
821
+ summary: {
822
+ filesAnalyzed: filePaths.length,
823
+ totalIssues: results.reduce((acc, r) => acc + r.issues.length, 0),
824
+ namingIssues: namingIssues.length,
825
+ patternIssues: patternIssues.length,
826
+ architectureIssues: 0
827
+ },
828
+ recommendations,
829
+ metadata: {
830
+ toolName: "naming-consistency",
831
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
832
+ }
833
+ };
834
+ }
835
+ function shouldIncludeSeverity(severity, minSeverity) {
836
+ return getSeverityLevel(severity) >= getSeverityLevel(minSeverity);
837
+ }
838
+ function getIssueType(type) {
839
+ if (!type) return IssueType.NamingInconsistency;
840
+ const typeMap = {
841
+ "naming-inconsistency": IssueType.NamingInconsistency,
842
+ "naming-quality": IssueType.NamingQuality,
843
+ "pattern-inconsistency": IssueType.PatternInconsistency,
844
+ "architecture-inconsistency": IssueType.ArchitectureInconsistency,
845
+ "error-handling": IssueType.PatternInconsistency,
846
+ "async-style": IssueType.PatternInconsistency,
847
+ "import-style": IssueType.PatternInconsistency,
848
+ "api-design": IssueType.PatternInconsistency
849
+ };
850
+ return typeMap[type] || IssueType.NamingInconsistency;
851
+ }
852
+ function transformToIssue(i) {
853
+ if (i.message && i.location) {
854
+ return {
855
+ type: getIssueType(i.type),
856
+ severity: i.severity,
857
+ message: i.message,
858
+ location: i.location,
859
+ suggestion: i.suggestion
860
+ };
861
+ }
862
+ if (i.identifier || i.type) {
863
+ const line = i.line || 1;
864
+ const column = i.column || 1;
865
+ return {
866
+ type: getIssueType(i.type),
867
+ severity: i.severity,
868
+ message: i.suggestion ? `Naming issue: ${i.suggestion}` : `Naming issue for '${i.identifier || "unknown"}'`,
869
+ location: {
870
+ file: i.file || i.fileName || "",
871
+ line,
872
+ column,
873
+ endLine: line,
874
+ endColumn: column + (i.identifier?.length || 10)
875
+ },
876
+ suggestion: i.suggestion
877
+ };
878
+ }
879
+ if (i.description || i.files) {
880
+ const fileName = Array.isArray(i.files) ? i.files[0] : i.file || "";
881
+ return {
882
+ type: getIssueType(i.type),
883
+ severity: i.severity,
884
+ message: i.description || "Pattern inconsistency found",
885
+ location: {
886
+ file: fileName,
887
+ line: 1,
888
+ column: 1,
889
+ endLine: 1,
890
+ endColumn: 10
891
+ },
892
+ suggestion: i.examples?.[0]
893
+ };
894
+ }
895
+ return {
896
+ type: getIssueType(i.type),
897
+ severity: i.severity,
898
+ message: i.message || "Unknown issue",
899
+ location: i.location || { file: "", line: 1, column: 1 },
900
+ suggestion: i.suggestion
901
+ };
902
+ }
903
+
904
+ export {
905
+ analyzeNamingAST,
906
+ analyzePatterns,
907
+ calculateConsistencyScore,
908
+ analyzeConsistency
909
+ };