@angular-modernizer/plugin-solid 1.2.0 → 2.1.0

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.
@@ -1,209 +1,38 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ServiceDipViolationRule = void 0;
4
- const ts_morph_1 = require("ts-morph");
5
4
  /**
6
- * Service DIP Violation Rule (`solid:service-dip-violation`) - detects
7
- * concrete `@Injectable` constructor injection.
5
+ * Former check for concrete `@Injectable` constructor injection
6
+ * (`solid:service-dip-violation`). Reports nothing: injecting a concrete
7
+ * `@Injectable` class is Angular's normal DI, not a defect. The one harmful
8
+ * shape, an injection against the layer direction, is always an import
9
+ * upwards, which `architecture:layer-boundary-violation` reports for the
10
+ * configured `layers` / `layersSource` (and suppresses with its
11
+ * `suppressionComments` markers).
8
12
  *
9
- * Reports a constructor parameter of an `@Injectable` class whose type
10
- * resolves (via the type checker, across files) to another `@Injectable`
11
- * class, instead of an abstraction (interface). Provides a suggested
12
- * interface name (`I` + injected class name) and a suggested fix. With
13
- * {@link ServiceDipViolationConfig.crossLayerOnly}, only injections between
14
- * different path-based layers are reported. Declaration files are skipped.
13
+ * The id stays registered so configurations naming it keep loading; ConfigLoader
14
+ * warns that `rules['solid:service-dip-violation']` has no effect. The
15
+ * `service-dip-violation-transform` ({@link ServiceDipViolationTransformRule})
16
+ * detects its targets itself and keeps working.
15
17
  *
16
- * Sibling of {@link DIPViolationRule}, which detects `new MyService()`.
17
- * {@link ServiceDipViolationTransformRule} applies the fix.
18
- *
19
- * @example
20
- * ```typescript
21
- * // Violation detected:
22
- * class UserService {
23
- * constructor(private orderService: OrderService) {}
24
- * }
25
- *
26
- * // Suggested fix:
27
- * class UserService {
28
- * constructor(private orderService: IOrderService) {}
29
- * }
30
- * ```
18
+ * @deprecated Reports nothing; removed in 3.0. Layer direction is checked by
19
+ * `architecture:layer-boundary-violation`.
31
20
  */
32
21
  class ServiceDipViolationRule {
33
22
  id = 'solid:service-dip-violation';
34
- name = 'Service DIP Violation';
35
- description = 'Detects @Injectable classes injecting other @Injectable classes by concrete type instead of interface';
23
+ name = 'Service DIP Violation (deprecated)';
24
+ description = 'Deprecated, reports nothing: injections against the layer direction are reported by architecture:layer-boundary-violation';
36
25
  severity = 'warning';
37
26
  category = 'solid-violation';
38
- tags = ['solid', 'dip', 'interfaces', 'dependency-injection'];
39
- config;
40
- constructor(config = {}) {
41
- this.config = config;
42
- }
43
- async analyze(context) {
44
- const sourceFile = context.sourceFile;
45
- // Skip declaration files
46
- if (sourceFile.getFilePath().endsWith('.d.ts')) {
47
- return [];
48
- }
49
- const violations = [];
50
- const injectingFilePath = sourceFile.getFilePath();
51
- for (const classDecl of sourceFile.getClasses()) {
52
- if (!this.hasInjectableDecorator(classDecl)) {
53
- continue;
54
- }
55
- const ctor = classDecl.getConstructors()[0];
56
- if (!ctor) {
57
- continue;
58
- }
59
- for (const param of ctor.getParameters()) {
60
- const violation = this.checkParameter(classDecl, param, injectingFilePath, context);
61
- if (violation) {
62
- violations.push(violation);
63
- }
64
- }
65
- }
66
- return violations;
67
- }
68
- // ---------------------------------------------------------------------------
69
- // Core detection
70
- // ---------------------------------------------------------------------------
71
- checkParameter(injectingClass, param, injectingFilePath, _context) {
72
- const injectedDecl = this.resolveServiceDeclaration(param);
73
- if (!injectedDecl) {
74
- return null;
75
- }
76
- if (!this.hasInjectableDecorator(injectedDecl)) {
77
- return null;
78
- }
79
- const injectedClass = injectedDecl.getName() ?? 'Unknown';
80
- const injectingClassName = injectingClass.getName() ?? 'Unknown';
81
- const paramName = param.getName();
82
- const suggestedInterfaceName = `I${injectedClass}`;
83
- // Layer information
84
- const injectedSourceFile = injectedDecl.getSourceFile();
85
- const injectedFilePath = injectedSourceFile.getFilePath();
86
- const injectingLayer = this.extractLayer(injectingFilePath);
87
- const injectedLayer = this.extractLayer(injectedFilePath);
88
- const isCrossLayer = injectingLayer !== undefined &&
89
- injectedLayer !== undefined &&
90
- injectingLayer !== injectedLayer;
91
- // Apply crossLayerOnly filter
92
- if (this.config.crossLayerOnly && !isCrossLayer) {
93
- return null;
94
- }
95
- const metadata = {
96
- violationType: 'concrete-injection',
97
- injectedClass,
98
- injectingClass: injectingClassName,
99
- parameterName: paramName,
100
- suggestedInterfaceName,
101
- confidence: 0.95,
102
- isBidirectional: false,
103
- isCrossLayer,
104
- ...(injectingLayer !== undefined ? { injectingLayer } : {}),
105
- ...(injectedLayer !== undefined ? { injectedLayer } : {}),
106
- };
107
- return {
108
- ruleId: this.id,
109
- message: `${injectingClassName} injects concrete class ${injectedClass} via constructor. ` +
110
- `Depend on an interface (${suggestedInterfaceName}) instead.`,
111
- filePath: injectingFilePath,
112
- line: param.getStartLineNumber(),
113
- column: param.getStart() - param.getStartLinePos(),
114
- suggestedFix: `Extract interface ${suggestedInterfaceName} from ${injectedClass}, ` +
115
- `add injection token, and replace the parameter type with ${suggestedInterfaceName}.`,
116
- metadata: metadata,
117
- };
118
- }
119
- // ---------------------------------------------------------------------------
120
- // Helpers
121
- // ---------------------------------------------------------------------------
27
+ tags = ['solid', 'dip', 'deprecated'];
122
28
  /**
123
- * Resolves the class declaration that a constructor parameter's type refers to.
124
- * Uses ts-morph's type checker — works across files within the same Project.
29
+ * @param _config - Ignored; kept so existing callers compile.
125
30
  */
126
- resolveServiceDeclaration(param) {
127
- try {
128
- const declarations = param.getType().getSymbol()?.getDeclarations();
129
- if (!declarations || declarations.length === 0) {
130
- return null;
131
- }
132
- for (const decl of declarations) {
133
- if (ts_morph_1.Node.isClassDeclaration(decl)) {
134
- return decl;
135
- }
136
- }
137
- return null;
138
- }
139
- catch {
140
- return null;
141
- }
31
+ constructor(_config = {}) {
32
+ // Options have no effect since the rule reports nothing.
142
33
  }
143
- /**
144
- * Checks whether a class has an `@Injectable` decorator.
145
- * Pattern copied from angular-service-without-injectable.rule.ts.
146
- */
147
- hasInjectableDecorator(classDecl) {
148
- return classDecl
149
- .getDecorators()
150
- .some((decorator) => decorator.getName() === 'Injectable');
151
- }
152
- /**
153
- * Extracts the architectural layer from a file path by scanning path segments.
154
- * Path-based fallback adapted from import-direction-violation.rule.ts.
155
- *
156
- * Returns undefined when no known layer segment is found.
157
- */
158
- extractLayer(filePath) {
159
- const parts = filePath.split('/');
160
- // Exact segment match (highest confidence)
161
- const exactLayers = [
162
- 'shared',
163
- 'features',
164
- 'core',
165
- 'lib',
166
- 'libs',
167
- 'app',
168
- 'config',
169
- 'environments',
170
- 'domain',
171
- ];
172
- for (let i = parts.length - 1; i >= 0; i--) {
173
- const part = parts[i]?.toLowerCase();
174
- if (!part) {
175
- continue;
176
- }
177
- if (exactLayers.includes(part)) {
178
- return part === 'libs' ? 'lib' : part;
179
- }
180
- }
181
- // Substring match (lower confidence — still useful)
182
- for (let i = parts.length - 1; i >= 0; i--) {
183
- const part = parts[i]?.toLowerCase();
184
- if (!part) {
185
- continue;
186
- }
187
- if (part.includes('shared')) {
188
- return 'shared';
189
- }
190
- if (part.includes('features')) {
191
- return 'features';
192
- }
193
- if (part.includes('core')) {
194
- return 'core';
195
- }
196
- if (part.includes('libs') || part.includes('lib')) {
197
- return 'lib';
198
- }
199
- if (part.includes('app')) {
200
- return 'app';
201
- }
202
- if (part.includes('config') || part.includes('environments')) {
203
- return 'config';
204
- }
205
- }
206
- return undefined;
34
+ analyze(_context) {
35
+ return Promise.resolve([]);
207
36
  }
208
37
  }
209
38
  exports.ServiceDipViolationRule = ServiceDipViolationRule;
@@ -1,94 +1,59 @@
1
1
  import type { AnalysisRule, AnalysisContext, AnalysisResult } from '@angular-modernizer/plugin-system';
2
+ /** Options of {@link SingleResponsibilityRule}. */
3
+ export interface SingleResponsibilityRuleOptions {
4
+ /**
5
+ * Project component decorators (`parser.componentDecorators`), in
6
+ * addition to `Component`. Classes with one of them are skipped.
7
+ * @default []
8
+ */
9
+ componentDecorators?: readonly string[];
10
+ }
2
11
  /**
3
- * SRP Violation Rule (`solid:srp-single-responsibility-violation`) - detects
4
- * Single Responsibility Principle violations in classes.
12
+ * SRP Violation Rule (`solid:srp-single-responsibility-violation`) - reports
13
+ * classes that are too large.
5
14
  *
6
- * Detection patterns (`violationType` in the metadata):
7
- * - `too-many-methods`: classes with more than 15 callable members. Get/set
8
- * accessors (a pair counts once) and arrow-function / function-expression
9
- * properties count as methods.
10
- * - `mixed-responsibilities`: member names that fall into 3 or more
11
- * responsibility categories. Base classes (abstract, or extended by 3 or
12
- * more classes in the project) with at least 8 public/protected callable
13
- * members are flagged at 2 categories, since every subclass inherits all
14
- * concerns; metadata then carries `isBaseClass`, `isAbstract` and
15
- * `subclassCount`.
16
- * - `single-method-multi-concern`: a method of 20 or more lines whose body
17
- * touches 4 or more categories.
15
+ * One finding per class (`violationType: 'too-many-methods'`, severity
16
+ * warning, at the class) when the class has more than 15 instance methods.
17
+ * Counted: method declarations that are not static, an overloaded method
18
+ * once; not counted: Angular lifecycle hooks (`ngOnInit`, `ngOnDestroy`,
19
+ * `ngOnChanges`, `ngDoCheck`, `ngAfterViewInit`, `ngAfterViewChecked`,
20
+ * `ngAfterContentInit`, `ngAfterContentChecked`), get/set accessors and
21
+ * properties, also function-valued ones and signal fields such as `input()`,
22
+ * `output()`, `model()`, `computed()` and `effect()`.
18
23
  *
19
- * Responsibility categories are matched by keywords: UI, Business, HTTP,
20
- * Data, Event and Lifecycle.
24
+ * Skipped: components (`Component` plus `parser.componentDecorators`; their
25
+ * size is reported by `architecture:component-complexity`) and static-only
26
+ * classes. The rule makes no claim about responsibilities: member names and
27
+ * method bodies are not read.
21
28
  *
22
29
  * @example
23
30
  * ```typescript
24
- * // Violation: class mixes HTTP, business, and UI concerns
25
- * class UserComponent {
26
- * fetchUsers() {} // HTTP concern
27
- * calculateTotal() {} // Business concern
28
- * renderChart() {} // UI concern
31
+ * // Reported: 16 instance methods
32
+ * @Injectable({ providedIn: 'root' })
33
+ * export class UserService {
34
+ * load(): void {}
35
+ * // ... 15 more methods
29
36
  * }
30
37
  * ```
31
38
  */
32
39
  export declare class SingleResponsibilityRule implements AnalysisRule {
33
40
  readonly id = "solid:srp-single-responsibility-violation";
34
41
  readonly name = "Single Responsibility Principle Violation";
35
- readonly description = "Detects classes with too many methods or mixed responsibilities";
42
+ readonly description = "Detects classes with more than 15 instance methods (lifecycle hooks, accessors and function properties not counted)";
36
43
  readonly severity = "warning";
37
44
  readonly category = "solid-violation";
38
45
  readonly tags: string[];
39
- /**
40
- * Default threshold for maximum number of methods in a class.
41
- */
46
+ /** Instance methods a class may have before it is reported. */
42
47
  private readonly maxMethodsThreshold;
48
+ private readonly componentDecorators;
43
49
  /**
44
- * Minimum number of different responsibility categories to flag as mixed.
45
- */
46
- private readonly minMixedResponsibilities;
47
- /**
48
- * Minimum number of mixed categories for base classes (abstract or
49
- * subclassed >= `minSubclassesForBase` times) with a large surface.
50
- */
51
- private readonly minMixedResponsibilitiesForBase;
52
- /**
53
- * Number of subclasses in the project that make a class a base class.
50
+ * @param options - `componentDecorators`: decorator names that mark a
51
+ * component in addition to `Component` (the plugin passes
52
+ * `parser.componentDecorators`).
54
53
  */
55
- private readonly minSubclassesForBase;
56
- /**
57
- * Public/protected callable members a base class needs to be evaluated.
58
- */
59
- private readonly baseClassSurfaceThreshold;
60
- /**
61
- * Responsibility categories for method classification.
62
- */
63
- private readonly responsibilityCategories;
54
+ constructor(options?: SingleResponsibilityRuleOptions);
64
55
  analyze(context: AnalysisContext): Promise<AnalysisResult[]>;
65
- /**
66
- * Check if a class violates SRP.
67
- */
68
56
  private checkClass;
69
- /**
70
- * Detect a single method that mixes ≥4 distinct concern categories AND is ≥20 lines.
71
- * Scans the full method body text for concern keywords (same categories as class-level).
72
- */
73
- private analyzeMethodBodyConcerns;
74
- /**
75
- * Collects methods, get/set accessors (a get/set pair counts once) and
76
- * properties initialized with arrow functions or function expressions.
77
- */
78
- private collectCallableMembers;
79
- /**
80
- * Base-class signal: abstract classes, or classes extended by at least
81
- * `minSubclassesForBase` classes in the project, with a public/protected
82
- * callable surface of at least `baseClassSurfaceThreshold` members.
83
- * Subclasses are counted via references to the class name inside
84
- * `extends` heritage clauses (only computed for large surfaces).
85
- */
86
- private detectBaseClassSignal;
87
- private countSubclasses;
88
- /**
89
- * Analyze the responsibilities of callable members in a class.
90
- * Returns a set of responsibility category names found.
91
- */
92
- private analyzeResponsibilities;
57
+ private isComponent;
93
58
  }
94
59
  //# sourceMappingURL=srp-violation.rule.d.ts.map