react-code-smell-detector 1.0.0 → 1.1.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.
Files changed (59) hide show
  1. package/dist/analyzer.d.ts.map +1 -1
  2. package/dist/analyzer.js +43 -1
  3. package/dist/cli.js +0 -0
  4. package/dist/detectors/deadCode.d.ts +14 -0
  5. package/dist/detectors/deadCode.d.ts.map +1 -0
  6. package/dist/detectors/deadCode.js +141 -0
  7. package/dist/detectors/dependencyArray.d.ts +7 -0
  8. package/dist/detectors/dependencyArray.d.ts.map +1 -0
  9. package/dist/detectors/dependencyArray.js +164 -0
  10. package/dist/detectors/hooksRules.d.ts +7 -0
  11. package/dist/detectors/hooksRules.d.ts.map +1 -0
  12. package/dist/detectors/hooksRules.js +81 -0
  13. package/dist/detectors/index.d.ts +11 -0
  14. package/dist/detectors/index.d.ts.map +1 -1
  15. package/dist/detectors/index.js +12 -0
  16. package/dist/detectors/javascript.d.ts +11 -0
  17. package/dist/detectors/javascript.d.ts.map +1 -0
  18. package/dist/detectors/javascript.js +148 -0
  19. package/dist/detectors/magicValues.d.ts +7 -0
  20. package/dist/detectors/magicValues.d.ts.map +1 -0
  21. package/dist/detectors/magicValues.js +99 -0
  22. package/dist/detectors/missingKey.d.ts +7 -0
  23. package/dist/detectors/missingKey.d.ts.map +1 -0
  24. package/dist/detectors/missingKey.js +93 -0
  25. package/dist/detectors/nestedTernary.d.ts +7 -0
  26. package/dist/detectors/nestedTernary.d.ts.map +1 -0
  27. package/dist/detectors/nestedTernary.js +58 -0
  28. package/dist/detectors/nextjs.d.ts +11 -0
  29. package/dist/detectors/nextjs.d.ts.map +1 -0
  30. package/dist/detectors/nextjs.js +103 -0
  31. package/dist/detectors/nodejs.d.ts +11 -0
  32. package/dist/detectors/nodejs.d.ts.map +1 -0
  33. package/dist/detectors/nodejs.js +169 -0
  34. package/dist/detectors/reactNative.d.ts +10 -0
  35. package/dist/detectors/reactNative.d.ts.map +1 -0
  36. package/dist/detectors/reactNative.js +135 -0
  37. package/dist/detectors/typescript.d.ts +11 -0
  38. package/dist/detectors/typescript.d.ts.map +1 -0
  39. package/dist/detectors/typescript.js +135 -0
  40. package/dist/reporter.js +30 -0
  41. package/dist/types/index.d.ts +14 -1
  42. package/dist/types/index.d.ts.map +1 -1
  43. package/dist/types/index.js +14 -0
  44. package/package.json +1 -1
  45. package/src/analyzer.ts +53 -0
  46. package/src/detectors/deadCode.ts +163 -0
  47. package/src/detectors/dependencyArray.ts +176 -0
  48. package/src/detectors/hooksRules.ts +101 -0
  49. package/src/detectors/index.ts +12 -0
  50. package/src/detectors/javascript.ts +169 -0
  51. package/src/detectors/magicValues.ts +114 -0
  52. package/src/detectors/missingKey.ts +105 -0
  53. package/src/detectors/nestedTernary.ts +75 -0
  54. package/src/detectors/nextjs.ts +124 -0
  55. package/src/detectors/nodejs.ts +199 -0
  56. package/src/detectors/reactNative.ts +154 -0
  57. package/src/detectors/typescript.ts +151 -0
  58. package/src/reporter.ts +30 -0
  59. package/src/types/index.ts +59 -1
@@ -0,0 +1,154 @@
1
+ import * as t from '@babel/types';
2
+ import { NodePath } from '@babel/traverse';
3
+ import { ParsedComponent, getCodeSnippet } from '../parser/index.js';
4
+ import { CodeSmell, DetectorConfig, DEFAULT_CONFIG } from '../types/index.js';
5
+
6
+ /**
7
+ * Detects React Native-specific code smells:
8
+ * - Inline styles instead of StyleSheet
9
+ * - Missing accessibility props
10
+ * - Performance anti-patterns
11
+ */
12
+ export function detectReactNativeIssues(
13
+ component: ParsedComponent,
14
+ filePath: string,
15
+ sourceCode: string,
16
+ config: DetectorConfig = DEFAULT_CONFIG,
17
+ imports: string[] = []
18
+ ): CodeSmell[] {
19
+ if (!config.checkReactNative) return [];
20
+
21
+ // Only run on React Native projects
22
+ const isRNProject = imports.some(imp =>
23
+ imp.includes('react-native') || imp.includes('@react-native')
24
+ );
25
+
26
+ if (!isRNProject) return [];
27
+
28
+ const smells: CodeSmell[] = [];
29
+ const inlineStyleLines = new Set<number>();
30
+
31
+ // Check for inline styles instead of StyleSheet
32
+ component.path.traverse({
33
+ JSXAttribute(path) {
34
+ if (!t.isJSXIdentifier(path.node.name)) return;
35
+ if (path.node.name.name !== 'style') return;
36
+
37
+ const value = path.node.value;
38
+ if (!t.isJSXExpressionContainer(value)) return;
39
+
40
+ // Check if it's an inline object (not a StyleSheet reference)
41
+ if (t.isObjectExpression(value.expression)) {
42
+ const loc = path.node.loc;
43
+ const line = loc?.start.line || 0;
44
+
45
+ if (!inlineStyleLines.has(line)) {
46
+ inlineStyleLines.add(line);
47
+ smells.push({
48
+ type: 'rn-inline-style',
49
+ severity: 'warning',
50
+ message: `Inline style object in "${component.name}" - prefer StyleSheet.create()`,
51
+ file: filePath,
52
+ line,
53
+ column: loc?.start.column || 0,
54
+ suggestion: 'Use StyleSheet.create() for better performance: const styles = StyleSheet.create({ ... })',
55
+ codeSnippet: getCodeSnippet(sourceCode, line),
56
+ });
57
+ }
58
+ }
59
+ },
60
+ });
61
+
62
+ // Check for missing accessibility props on interactive elements
63
+ const interactiveComponents = ['TouchableOpacity', 'TouchableHighlight', 'Pressable', 'Button', 'TouchableWithoutFeedback'];
64
+
65
+ component.path.traverse({
66
+ JSXOpeningElement(path) {
67
+ if (!t.isJSXIdentifier(path.node.name)) return;
68
+
69
+ const componentName = path.node.name.name;
70
+ if (!interactiveComponents.includes(componentName)) return;
71
+
72
+ // Check for accessibility props
73
+ const hasAccessibilityLabel = path.node.attributes.some(attr => {
74
+ if (t.isJSXAttribute(attr) && t.isJSXIdentifier(attr.name)) {
75
+ return ['accessibilityLabel', 'accessible', 'accessibilityRole', 'accessibilityHint'].includes(attr.name.name);
76
+ }
77
+ return false;
78
+ });
79
+
80
+ if (!hasAccessibilityLabel) {
81
+ const loc = path.node.loc;
82
+ smells.push({
83
+ type: 'rn-missing-accessibility',
84
+ severity: 'info',
85
+ message: `${componentName} missing accessibility props in "${component.name}"`,
86
+ file: filePath,
87
+ line: loc?.start.line || 0,
88
+ column: loc?.start.column || 0,
89
+ suggestion: 'Add accessibilityLabel and accessibilityRole for screen readers',
90
+ codeSnippet: getCodeSnippet(sourceCode, loc?.start.line || 0),
91
+ });
92
+ }
93
+ },
94
+ });
95
+
96
+ // Check for performance anti-patterns
97
+ component.path.traverse({
98
+ // Detect creating anonymous functions in render (for onPress, etc.)
99
+ JSXAttribute(path) {
100
+ if (!t.isJSXIdentifier(path.node.name)) return;
101
+
102
+ const propName = path.node.name.name;
103
+ if (!['onPress', 'onPressIn', 'onPressOut', 'onLongPress'].includes(propName)) return;
104
+
105
+ const value = path.node.value;
106
+ if (!t.isJSXExpressionContainer(value)) return;
107
+
108
+ // Check for arrow functions or function expressions
109
+ if (t.isArrowFunctionExpression(value.expression) || t.isFunctionExpression(value.expression)) {
110
+ const loc = path.node.loc;
111
+ smells.push({
112
+ type: 'rn-performance-issue',
113
+ severity: 'info',
114
+ message: `Inline function for ${propName} in "${component.name}" creates new reference each render`,
115
+ file: filePath,
116
+ line: loc?.start.line || 0,
117
+ column: loc?.start.column || 0,
118
+ suggestion: 'Extract to useCallback or class method to prevent unnecessary re-renders',
119
+ codeSnippet: getCodeSnippet(sourceCode, loc?.start.line || 0),
120
+ });
121
+ }
122
+ },
123
+
124
+ // Detect array spreads in render that could be memoized
125
+ SpreadElement(path) {
126
+ const loc = path.node.loc;
127
+ // Only flag if inside JSX or return statement
128
+ let inJSX = false;
129
+ let current: NodePath | null = path.parentPath;
130
+ while (current) {
131
+ if (t.isJSXElement(current.node) || t.isJSXFragment(current.node)) {
132
+ inJSX = true;
133
+ break;
134
+ }
135
+ current = current.parentPath;
136
+ }
137
+
138
+ if (inJSX && t.isArrayExpression(path.parent)) {
139
+ smells.push({
140
+ type: 'rn-performance-issue',
141
+ severity: 'info',
142
+ message: `Array spread in render may cause performance issues in "${component.name}"`,
143
+ file: filePath,
144
+ line: loc?.start.line || 0,
145
+ column: loc?.start.column || 0,
146
+ suggestion: 'Consider memoizing with useMemo if this array is passed as a prop',
147
+ codeSnippet: getCodeSnippet(sourceCode, loc?.start.line || 0),
148
+ });
149
+ }
150
+ },
151
+ });
152
+
153
+ return smells;
154
+ }
@@ -0,0 +1,151 @@
1
+ import * as t from '@babel/types';
2
+ import { ParsedComponent, getCodeSnippet } from '../parser/index.js';
3
+ import { CodeSmell, DetectorConfig, DEFAULT_CONFIG } from '../types/index.js';
4
+
5
+ /**
6
+ * Detects TypeScript-specific code smells:
7
+ * - Overuse of 'any' type
8
+ * - Missing return type on functions
9
+ * - Non-null assertion operator (!)
10
+ * - Type assertions (as) that could be avoided
11
+ */
12
+ export function detectTypescriptIssues(
13
+ component: ParsedComponent,
14
+ filePath: string,
15
+ sourceCode: string,
16
+ config: DetectorConfig = DEFAULT_CONFIG
17
+ ): CodeSmell[] {
18
+ if (!config.checkTypescript) return [];
19
+
20
+ // Only run on TypeScript files
21
+ if (!filePath.endsWith('.ts') && !filePath.endsWith('.tsx')) return [];
22
+
23
+ const smells: CodeSmell[] = [];
24
+
25
+ // Detect 'any' type usage
26
+ component.path.traverse({
27
+ TSAnyKeyword(path) {
28
+ const loc = path.node.loc;
29
+ smells.push({
30
+ type: 'ts-any-usage',
31
+ severity: 'warning',
32
+ message: `Using "any" type in "${component.name}"`,
33
+ file: filePath,
34
+ line: loc?.start.line || 0,
35
+ column: loc?.start.column || 0,
36
+ suggestion: 'Use a specific type, "unknown", or create an interface',
37
+ codeSnippet: getCodeSnippet(sourceCode, loc?.start.line || 0),
38
+ });
39
+ },
40
+ });
41
+
42
+ // Detect functions without return type (only in complex functions)
43
+ component.path.traverse({
44
+ FunctionDeclaration(path) {
45
+ // Skip if function has explicit return type
46
+ if (path.node.returnType) return;
47
+
48
+ // Check if function body has return statements
49
+ let hasReturn = false;
50
+ path.traverse({
51
+ ReturnStatement(returnPath) {
52
+ if (returnPath.node.argument) {
53
+ hasReturn = true;
54
+ }
55
+ },
56
+ });
57
+
58
+ if (hasReturn) {
59
+ const loc = path.node.loc;
60
+ smells.push({
61
+ type: 'ts-missing-return-type',
62
+ severity: 'info',
63
+ message: `Function "${path.node.id?.name || 'anonymous'}" missing return type`,
64
+ file: filePath,
65
+ line: loc?.start.line || 0,
66
+ column: loc?.start.column || 0,
67
+ suggestion: 'Add explicit return type: function name(): ReturnType { ... }',
68
+ codeSnippet: getCodeSnippet(sourceCode, loc?.start.line || 0),
69
+ });
70
+ }
71
+ },
72
+
73
+ ArrowFunctionExpression(path) {
74
+ // Only check arrow functions assigned to variables with 5+ lines
75
+ if (!path.node.returnType) {
76
+ const body = path.node.body;
77
+
78
+ // Skip simple arrow functions (single expression)
79
+ if (!t.isBlockStatement(body)) return;
80
+
81
+ // Check complexity - only flag if function is substantial
82
+ const startLine = path.node.loc?.start.line || 0;
83
+ const endLine = path.node.loc?.end.line || 0;
84
+
85
+ if (endLine - startLine >= 5) {
86
+ // Check if parent is variable declarator (assigned to variable)
87
+ const parent = path.parent;
88
+
89
+ if (t.isVariableDeclarator(parent) && t.isIdentifier(parent.id)) {
90
+ const loc = path.node.loc;
91
+ smells.push({
92
+ type: 'ts-missing-return-type',
93
+ severity: 'info',
94
+ message: `Arrow function "${parent.id.name}" missing return type`,
95
+ file: filePath,
96
+ line: loc?.start.line || 0,
97
+ column: loc?.start.column || 0,
98
+ suggestion: 'Add return type: const name = (): ReturnType => { ... }',
99
+ codeSnippet: getCodeSnippet(sourceCode, loc?.start.line || 0),
100
+ });
101
+ }
102
+ }
103
+ }
104
+ },
105
+ });
106
+
107
+ // Detect non-null assertion operator (!)
108
+ component.path.traverse({
109
+ TSNonNullExpression(path) {
110
+ const loc = path.node.loc;
111
+ smells.push({
112
+ type: 'ts-non-null-assertion',
113
+ severity: 'warning',
114
+ message: `Non-null assertion (!) bypasses type safety in "${component.name}"`,
115
+ file: filePath,
116
+ line: loc?.start.line || 0,
117
+ column: loc?.start.column || 0,
118
+ suggestion: 'Use optional chaining (?.) or proper null checks instead',
119
+ codeSnippet: getCodeSnippet(sourceCode, loc?.start.line || 0),
120
+ });
121
+ },
122
+ });
123
+
124
+ // Detect type assertions (as keyword) - these can hide type errors
125
+ component.path.traverse({
126
+ TSAsExpression(path) {
127
+ // Skip assertions to 'const' (used for const assertions)
128
+ if (t.isTSTypeReference(path.node.typeAnnotation)) {
129
+ const typeName = path.node.typeAnnotation.typeName;
130
+ if (t.isIdentifier(typeName) && typeName.name === 'const') return;
131
+ }
132
+
133
+ // Skip double assertions (as unknown as Type) - already flagged by TypeScript
134
+ if (t.isTSAsExpression(path.node.expression)) return;
135
+
136
+ const loc = path.node.loc;
137
+ smells.push({
138
+ type: 'ts-type-assertion',
139
+ severity: 'info',
140
+ message: `Type assertion (as) bypasses type checking in "${component.name}"`,
141
+ file: filePath,
142
+ line: loc?.start.line || 0,
143
+ column: loc?.start.column || 0,
144
+ suggestion: 'Consider using type guards or proper typing instead of assertions',
145
+ codeSnippet: getCodeSnippet(sourceCode, loc?.start.line || 0),
146
+ });
147
+ },
148
+ });
149
+
150
+ return smells;
151
+ }
package/src/reporter.ts CHANGED
@@ -243,6 +243,36 @@ function formatSmellType(type: string): string {
243
243
  'state-in-loop': '🔄 State in Loop',
244
244
  'inline-function-prop': '📎 Inline Function Prop',
245
245
  'deep-nesting': '📊 Deep Nesting',
246
+ 'missing-key': '🔑 Missing Key',
247
+ 'hooks-rules-violation': '⚠️ Hooks Rules Violation',
248
+ 'dependency-array-issue': '📋 Dependency Array Issue',
249
+ 'nested-ternary': '❓ Nested Ternary',
250
+ 'dead-code': '💀 Dead Code',
251
+ 'magic-value': '🔢 Magic Value',
252
+ // Next.js
253
+ 'nextjs-client-server-boundary': '▲ Next.js Client/Server Boundary',
254
+ 'nextjs-missing-metadata': '▲ Next.js Missing Metadata',
255
+ 'nextjs-image-unoptimized': '▲ Next.js Unoptimized Image',
256
+ 'nextjs-router-misuse': '▲ Next.js Router Misuse',
257
+ // React Native
258
+ 'rn-inline-style': '📱 RN Inline Style',
259
+ 'rn-missing-accessibility': '📱 RN Missing Accessibility',
260
+ 'rn-performance-issue': '📱 RN Performance Issue',
261
+ // Node.js
262
+ 'nodejs-callback-hell': '🟢 Node.js Callback Hell',
263
+ 'nodejs-unhandled-promise': '🟢 Node.js Unhandled Promise',
264
+ 'nodejs-sync-io': '🟢 Node.js Sync I/O',
265
+ 'nodejs-missing-error-handling': '🟢 Node.js Missing Error Handling',
266
+ // JavaScript
267
+ 'js-var-usage': '📜 JS var Usage',
268
+ 'js-loose-equality': '📜 JS Loose Equality',
269
+ 'js-implicit-coercion': '📜 JS Implicit Coercion',
270
+ 'js-global-pollution': '📜 JS Global Pollution',
271
+ // TypeScript
272
+ 'ts-any-usage': '🔷 TS any Usage',
273
+ 'ts-missing-return-type': '🔷 TS Missing Return Type',
274
+ 'ts-non-null-assertion': '🔷 TS Non-null Assertion',
275
+ 'ts-type-assertion': '🔷 TS Type Assertion',
246
276
  };
247
277
  return labels[type] || type;
248
278
  }
@@ -8,7 +8,37 @@ export type SmellType =
8
8
  | 'missing-dependency'
9
9
  | 'state-in-loop'
10
10
  | 'inline-function-prop'
11
- | 'deep-nesting';
11
+ | 'deep-nesting'
12
+ | 'missing-key'
13
+ | 'hooks-rules-violation'
14
+ | 'dependency-array-issue'
15
+ | 'nested-ternary'
16
+ | 'dead-code'
17
+ | 'magic-value'
18
+ // Next.js specific
19
+ | 'nextjs-client-server-boundary'
20
+ | 'nextjs-missing-metadata'
21
+ | 'nextjs-image-unoptimized'
22
+ | 'nextjs-router-misuse'
23
+ // React Native specific
24
+ | 'rn-inline-style'
25
+ | 'rn-missing-accessibility'
26
+ | 'rn-performance-issue'
27
+ // Node.js specific
28
+ | 'nodejs-callback-hell'
29
+ | 'nodejs-unhandled-promise'
30
+ | 'nodejs-sync-io'
31
+ | 'nodejs-missing-error-handling'
32
+ // JavaScript specific
33
+ | 'js-var-usage'
34
+ | 'js-loose-equality'
35
+ | 'js-implicit-coercion'
36
+ | 'js-global-pollution'
37
+ // TypeScript specific
38
+ | 'ts-any-usage'
39
+ | 'ts-missing-return-type'
40
+ | 'ts-non-null-assertion'
41
+ | 'ts-type-assertion';
12
42
 
13
43
  export interface CodeSmell {
14
44
  type: SmellType;
@@ -75,6 +105,20 @@ export interface DetectorConfig {
75
105
  maxComponentLines: number;
76
106
  maxPropsCount: number;
77
107
  checkMemoization: boolean;
108
+ checkMissingKeys: boolean;
109
+ checkHooksRules: boolean;
110
+ checkDependencyArrays: boolean;
111
+ maxTernaryDepth: number;
112
+ checkDeadCode: boolean;
113
+ checkMagicValues: boolean;
114
+ magicNumberThreshold: number;
115
+ // Framework detection
116
+ checkNextjs: boolean;
117
+ checkReactNative: boolean;
118
+ checkNodejs: boolean;
119
+ checkJavascript: boolean;
120
+ checkTypescript: boolean;
121
+ maxCallbackDepth: number;
78
122
  }
79
123
 
80
124
  export const DEFAULT_CONFIG: DetectorConfig = {
@@ -83,4 +127,18 @@ export const DEFAULT_CONFIG: DetectorConfig = {
83
127
  maxComponentLines: 300,
84
128
  maxPropsCount: 7,
85
129
  checkMemoization: true,
130
+ checkMissingKeys: true,
131
+ checkHooksRules: true,
132
+ checkDependencyArrays: true,
133
+ maxTernaryDepth: 2,
134
+ checkDeadCode: true,
135
+ checkMagicValues: true,
136
+ magicNumberThreshold: 10,
137
+ // Framework detection - auto-enabled based on project
138
+ checkNextjs: true,
139
+ checkReactNative: true,
140
+ checkNodejs: true,
141
+ checkJavascript: true,
142
+ checkTypescript: true,
143
+ maxCallbackDepth: 3,
86
144
  };