@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.
- package/CHANGELOG.md +282 -0
- package/README.md +112 -99
- package/dist/index.d.ts +5 -3
- package/dist/index.js +4 -2
- package/dist/rules/dip-violation.rule.d.ts +38 -31
- package/dist/rules/dip-violation.rule.js +289 -106
- package/dist/rules/god-switch-analysis.rule.d.ts +44 -33
- package/dist/rules/god-switch-analysis.rule.js +146 -109
- package/dist/rules/isp-violation.rule.d.ts +35 -33
- package/dist/rules/isp-violation.rule.js +83 -202
- package/dist/rules/lsp-violation.rule.d.ts +15 -39
- package/dist/rules/lsp-violation.rule.js +17 -300
- package/dist/rules/ocp-violation.rule.d.ts +52 -36
- package/dist/rules/ocp-violation.rule.js +227 -145
- package/dist/rules/service-dip-violation.analysis.rule.d.ts +32 -56
- package/dist/rules/service-dip-violation.analysis.rule.js +21 -192
- package/dist/rules/srp-violation.rule.d.ts +36 -71
- package/dist/rules/srp-violation.rule.js +78 -384
- package/dist/solid-plugin.d.ts +13 -8
- package/dist/solid-plugin.js +17 -11
- package/package.json +7 -6
package/README.md
CHANGED
|
@@ -10,72 +10,94 @@ The `@angular-modernizer/plugin-solid` package provides analysis rules for detec
|
|
|
10
10
|
|
|
11
11
|
### Single Responsibility Principle (SRP)
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
Reports classes that are too large: more than 15 instance methods, Angular lifecycle hooks, accessors and function-valued properties not counted. Components and static-only classes are skipped. The rule makes no claim about responsibilities: it reads neither member names nor method bodies.
|
|
14
14
|
|
|
15
15
|
### Open/Closed Principle (OCP)
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
Reports if-else chains that dispatch on one value in more than 4 conditions, and (`solid:god-switch`) switches with more than 10 clauses that do more than return or assign a value. Both grow with each new case.
|
|
18
18
|
|
|
19
19
|
### Liskov Substitution Principle (LSP)
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
`solid:lsp-violation` is deprecated and reports nothing: a missing interface member or abstract method is a compile error, and an `instanceof` check alone shows no broken substitution. The id stays registered so configurations load; ConfigLoader warns when it is configured.
|
|
22
22
|
|
|
23
23
|
### Interface Segregation Principle (ISP)
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
Reports interfaces that declare more than 5 methods (overloads once, function-typed properties included).
|
|
26
26
|
|
|
27
27
|
### Dependency Inversion Principle (DIP)
|
|
28
28
|
|
|
29
|
-
|
|
29
|
+
Reports `@Injectable` classes of the project created with `new` and `Injector.get()` lookups inside class members: both bypass Angular DI. `solid:service-dip-violation` (concrete constructor injection) is deprecated and reports nothing; injections against the layer direction are imports that `architecture:layer-boundary-violation` reports.
|
|
30
30
|
|
|
31
31
|
## Analysis Rules
|
|
32
32
|
|
|
33
|
-
###
|
|
33
|
+
### SingleResponsibilityRule
|
|
34
34
|
|
|
35
35
|
**Rule ID:** `solid:srp-single-responsibility-violation`
|
|
36
36
|
**Severity:** Warning
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
One finding per class (`violationType: 'too-many-methods'`, at the class) when the class has more than 15 instance methods. Counted: method declarations that are not static (public, protected, private, `#` and abstract alike), an overloaded method once. Not counted: the Angular lifecycle hooks `ngOnInit`, `ngOnDestroy`, `ngOnChanges`, `ngDoCheck`, `ngAfterViewInit`, `ngAfterViewChecked`, `ngAfterContentInit` and `ngAfterContentChecked` (by exact name), get/set accessors and properties, also arrow-function and function-expression properties and signal fields such as `input()`, `output()`, `model()`, `computed()` and `effect()`.
|
|
39
|
+
|
|
40
|
+
Skipped: components (`@Component` and the decorators of `parser.componentDecorators`; `architecture:component-complexity` reports component size) and static-only classes. Directives, pipes, services and plain classes are counted.
|
|
41
|
+
|
|
42
|
+
Message: `Class 'UserService' has 16 instance methods without lifecycle hooks (threshold: 15).` Metadata: `className`, `methodCount`, `threshold`, `violationType`, `principle`.
|
|
43
|
+
|
|
44
|
+
Member names and method bodies are not read: the former checks for responsibility keywords in member names (`mixed-responsibilities`) and in method bodies (`single-method-multi-concern`) are removed. Responsibilities of services are reported by `architecture:service-bag`.
|
|
39
45
|
|
|
40
46
|
---
|
|
41
47
|
|
|
42
48
|
### DIPViolationRule
|
|
43
49
|
|
|
44
50
|
**Rule ID:** `solid:dip-violation-direct-instantiation`
|
|
45
|
-
**Severity:** Warning
|
|
51
|
+
**Severity:** Warning (info for `service-locator-outside-di`)
|
|
46
52
|
|
|
47
|
-
|
|
53
|
+
One warning per finding (`result.severity`), except `service-locator-outside-di` (info). Violation types (`violationType` in the metadata):
|
|
48
54
|
|
|
49
|
-
|
|
50
|
-
- `
|
|
51
|
-
- `
|
|
52
|
-
- Direct instantiation of classes ending with `Service`, `Repository`, `Store`, `Manager`, `Api`, `Client`, `Provider`, `Facade`, `Helper`, `Util` or `Utils`
|
|
53
|
-
- `injector.get()` service locator calls
|
|
55
|
+
- `direct-instantiation`: `new X()` where `X` resolves by symbol to a class declared in the project (not in a `.d.ts` file or `node_modules`) with an `Injectable` decorator from `@angular/core` (named, aliased or namespace import). Library classes (`new HttpClient(handler)`, third-party clients) and undecorated helpers or models are not reported, whatever their name. Metadata: `instantiatedType` (class name without qualifier or type arguments).
|
|
56
|
+
- `service-locator-pattern`: `.get(...)` on a receiver whose type is Angular's `Injector` (type checker), any receiver expression: `this.injector`, a parameter, `inject(Injector)`. A `Map` or other receiver only named like an injector is not reported. Metadata: `receiver`, `token`.
|
|
57
|
+
- `service-locator-outside-di` (severity info): the same `.get(...)` lookup anywhere in a class with no `Injectable`, `Component`, `Directive`, `Pipe` or `NgModule` decorator from `@angular/core` (matched by symbol, not by name), such as a handler created with `new`, including its constructor body and instance field initializers (a base class decorator does not count). The hidden dependency is real, but `inject()` is not available there: `suggestedFix` proposes a constructor parameter that the code creating the class fills, and `injectionContext` is `false`. Metadata: `receiver`, `token`.
|
|
54
58
|
|
|
55
|
-
|
|
59
|
+
Both are reported only inside class members (methods, constructors, accessors, property initializers). Not reported: a function that is the value of a `useFactory` property, a function passed to `provideAppInitializer`, `provideEnvironmentInitializer` or `providePlatformInitializer`, decorators and functions outside classes, since these build providers.
|
|
60
|
+
|
|
61
|
+
`suggestedFix` proposes `inject(X)` when the project uses Angular 14 or later (api `angularMajorVersion`, installed `@angular/core` first, else the declared range) and the call site is an injection context (an instance field initializer or the constructor body, not a nested callback, of a class with one of the decorators above; a class without one has no injection context); otherwise a constructor parameter (for `service-locator-outside-di` one filled by the creator of the class). Metadata also carries `principle: 'DIP'`, `injectionContext` and `angularMajorVersion`.
|
|
62
|
+
|
|
63
|
+
**Reported:**
|
|
56
64
|
|
|
57
65
|
```typescript
|
|
58
|
-
|
|
66
|
+
@Injectable({ providedIn: 'root' })
|
|
67
|
+
export class UserService {}
|
|
68
|
+
|
|
59
69
|
@Component({...})
|
|
60
70
|
export class UserComponent {
|
|
61
|
-
private userService = new UserService();
|
|
62
|
-
|
|
71
|
+
private userService = new UserService(); // direct-instantiation, fix: inject(UserService)
|
|
72
|
+
|
|
73
|
+
constructor(private injector: Injector) {}
|
|
74
|
+
|
|
75
|
+
load() {
|
|
76
|
+
return this.injector.get(UserService); // service-locator-pattern, fix: constructor parameter
|
|
77
|
+
}
|
|
63
78
|
}
|
|
64
79
|
|
|
65
|
-
//
|
|
66
|
-
constructor(private injector: Injector) {
|
|
67
|
-
|
|
80
|
+
export class ReportExporter { // created with new, no Angular DI
|
|
81
|
+
constructor(private injector: Injector) {}
|
|
82
|
+
|
|
83
|
+
export() {
|
|
84
|
+
return this.injector.get(UserService); // service-locator-outside-di (info), fix: constructor parameter filled by the creator
|
|
85
|
+
}
|
|
68
86
|
}
|
|
69
87
|
```
|
|
70
88
|
|
|
71
|
-
**
|
|
89
|
+
**Not reported:**
|
|
72
90
|
|
|
73
91
|
```typescript
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
92
|
+
export class ApiFactory {
|
|
93
|
+
create(handler: HttpHandler) {
|
|
94
|
+
return new HttpClient(handler); // library class
|
|
95
|
+
}
|
|
78
96
|
}
|
|
97
|
+
|
|
98
|
+
export const PROVIDERS = [
|
|
99
|
+
{ provide: UserStore, useFactory: (injector: Injector) => injector.get(UserService), deps: [Injector] },
|
|
100
|
+
];
|
|
79
101
|
```
|
|
80
102
|
|
|
81
103
|
**Analysis Result:**
|
|
@@ -83,23 +105,19 @@ export class UserComponent {
|
|
|
83
105
|
```json
|
|
84
106
|
{
|
|
85
107
|
"ruleId": "solid:dip-violation-direct-instantiation",
|
|
86
|
-
"
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
"description": "Convert to dependency injection using inject()"
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
]
|
|
108
|
+
"severity": "warning",
|
|
109
|
+
"message": "new UserService() creates an @Injectable class outside Angular DI (Dependency Inversion Principle): its own dependencies are not injected, providers and test doubles for UserService are bypassed.",
|
|
110
|
+
"filePath": "/src/app/user.component.ts",
|
|
111
|
+
"line": 6,
|
|
112
|
+
"column": 2,
|
|
113
|
+
"suggestedFix": "Replace 'new UserService()' with 'inject(UserService)'.",
|
|
114
|
+
"metadata": {
|
|
115
|
+
"instantiatedType": "UserService",
|
|
116
|
+
"violationType": "direct-instantiation",
|
|
117
|
+
"principle": "DIP",
|
|
118
|
+
"injectionContext": true,
|
|
119
|
+
"angularMajorVersion": 21
|
|
120
|
+
}
|
|
103
121
|
}
|
|
104
122
|
```
|
|
105
123
|
|
|
@@ -108,9 +126,9 @@ export class UserComponent {
|
|
|
108
126
|
### ServiceDipViolationRule
|
|
109
127
|
|
|
110
128
|
**Rule ID:** `solid:service-dip-violation`
|
|
111
|
-
**
|
|
129
|
+
**Status:** Deprecated, reports nothing (removed in 3.0)
|
|
112
130
|
|
|
113
|
-
|
|
131
|
+
Injecting a concrete `@Injectable` class is Angular's normal DI and no defect. The only harmful shape, an injection against the layer direction, is always an import upwards, which `architecture:layer-boundary-violation` reports for the configured `layers` / `layersSource` (and suppresses with its `suppressionComments` markers). The id stays registered so configurations load; ConfigLoader warns when `rules['solid:service-dip-violation']` is set. The transform `ServiceDipViolationTransformRule` detects its targets itself and is not affected.
|
|
114
132
|
|
|
115
133
|
---
|
|
116
134
|
|
|
@@ -119,35 +137,24 @@ Detects constructor parameters of `@Injectable` classes that inject concrete `@I
|
|
|
119
137
|
**Rule ID:** `solid:god-switch`
|
|
120
138
|
**Severity:** Warning
|
|
121
139
|
|
|
122
|
-
|
|
140
|
+
Reports a switch statement with more than 10 non-lookup clauses (threshold `maxCases`, default 10), one warning per switch at the switch. Switches are checked everywhere in the file.
|
|
123
141
|
|
|
124
|
-
|
|
125
|
-
-
|
|
126
|
-
-
|
|
127
|
-
-
|
|
142
|
+
How clauses are counted:
|
|
143
|
+
- A clause is a label with a body of its own: labels that fall through without statements form one clause with the next label that has statements. `default` counts like a case clause when it has a body.
|
|
144
|
+
- A clause is a lookup when its body, ignoring `break` and unwrapping blocks, is a single `return` or a single assignment expression statement and contains no call or `new` expression (`return 'x'`, `return row.active ? row.on : row.off`, `this.label = 'x'`), or whose value is one call with only constant arguments: literals, enum members and `const` variables (`return translate.instant('HEADER.NAME')`). `return this.compute()` and `return handle(input)` are no lookups. Lookups are not counted, so a value mapping is never reported. `return this.compute()` is no lookup.
|
|
145
|
+
- A clause whose body is only `break` does nothing and is not counted.
|
|
128
146
|
|
|
129
147
|
**Before:**
|
|
130
148
|
|
|
131
149
|
```typescript
|
|
132
|
-
//
|
|
150
|
+
// 11 clauses that each call a handler
|
|
133
151
|
export class OrderProcessor {
|
|
134
152
|
processOrder(status: string): void {
|
|
135
153
|
switch (status) {
|
|
136
|
-
case 'pending': break;
|
|
137
|
-
case 'processing': break;
|
|
138
|
-
case 'shipped': break;
|
|
139
|
-
|
|
140
|
-
case 'cancelled': break;
|
|
141
|
-
case 'refunded': break;
|
|
142
|
-
case 'returned': break;
|
|
143
|
-
case 'failed': break;
|
|
144
|
-
case 'on-hold': break;
|
|
145
|
-
case 'completed': break;
|
|
146
|
-
case 'archived': break;
|
|
147
|
-
case 'disputed': break;
|
|
148
|
-
case 'escalated': break;
|
|
149
|
-
case 'resolved': break;
|
|
150
|
-
case 'closed': break;
|
|
154
|
+
case 'pending': this.reserveStock(); break;
|
|
155
|
+
case 'processing': this.startPicking(); break;
|
|
156
|
+
case 'shipped': this.notifyCarrier(); break;
|
|
157
|
+
// ... 8 more clauses that call a handler
|
|
151
158
|
default: break;
|
|
152
159
|
}
|
|
153
160
|
}
|
|
@@ -189,17 +196,19 @@ class OrderStatusFactory {
|
|
|
189
196
|
```json
|
|
190
197
|
{
|
|
191
198
|
"ruleId": "solid:god-switch",
|
|
192
|
-
"
|
|
199
|
+
"severity": "warning",
|
|
200
|
+
"message": "Switch on 'status' has 11 clauses that do more than return or assign a value (threshold: 10).",
|
|
193
201
|
"filePath": "src/app/order-processor.ts",
|
|
194
202
|
"line": 3,
|
|
195
203
|
"column": 4,
|
|
196
|
-
"suggestedFix": "
|
|
204
|
+
"suggestedFix": "Move the behavior of each clause into a handler map or into polymorphic classes so a new case does not edit this switch.",
|
|
197
205
|
"metadata": {
|
|
198
|
-
"
|
|
199
|
-
"
|
|
206
|
+
"clauseCount": 11,
|
|
207
|
+
"lookupClauseCount": 0,
|
|
208
|
+
"nonLookupClauseCount": 11,
|
|
209
|
+
"maxCases": 10,
|
|
200
210
|
"switchExpression": "status",
|
|
201
211
|
"hasDefault": true,
|
|
202
|
-
"confidence": 0.9,
|
|
203
212
|
"caseLabels": ["pending", "processing", "shipped", "..."],
|
|
204
213
|
"violationType": "god-switch",
|
|
205
214
|
"principle": "Open/Closed Principle"
|
|
@@ -212,7 +221,7 @@ class OrderStatusFactory {
|
|
|
212
221
|
```typescript
|
|
213
222
|
interface GodSwitchConfig {
|
|
214
223
|
/**
|
|
215
|
-
* Maximum allowed
|
|
224
|
+
* Maximum allowed non-lookup clauses before violation
|
|
216
225
|
* Default: 10
|
|
217
226
|
*/
|
|
218
227
|
maxCases?: number;
|
|
@@ -224,10 +233,9 @@ const context = ContextFactory.createAnalysisContext({
|
|
|
224
233
|
project,
|
|
225
234
|
api: createPublicApi(),
|
|
226
235
|
config: {
|
|
227
|
-
solid:
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
},
|
|
236
|
+
// rules['solid:god-switch'] of .angular-modernizer.json
|
|
237
|
+
'solid:god-switch': {
|
|
238
|
+
maxCases: 15, // Custom threshold
|
|
231
239
|
},
|
|
232
240
|
},
|
|
233
241
|
});
|
|
@@ -240,9 +248,9 @@ const context = ContextFactory.createAnalysisContext({
|
|
|
240
248
|
**Rule ID:** `solid:isp-violation`
|
|
241
249
|
**Severity:** Warning
|
|
242
250
|
|
|
243
|
-
|
|
251
|
+
Reports an interface that declares more than 5 methods, one warning at the interface. Methods are the interface's own method signatures counted by name (overloads once) plus properties whose type is a plain function (`onSave: () => void`, also optional or through a type alias). Callable types with properties of their own (signals such as `title: Signal<string>`), data properties, call and index signatures and members inherited through `extends` are not counted. Interfaces in `declare global` or `declare module` blocks and interfaces that merge with a declaration in a `.d.ts` file (a script-level `interface Window`) are skipped. Classes are not examined: how many interfaces a class implements is not reported.
|
|
244
252
|
|
|
245
|
-
`solid:import-direction-violation` and `solid:
|
|
253
|
+
`solid:import-direction-violation`, `solid:circular-dependency` and `solid:god-object-violation` use the `solid:` prefix but belong to `@angular-modernizer/plugin-architecture`.
|
|
246
254
|
|
|
247
255
|
---
|
|
248
256
|
|
|
@@ -251,16 +259,18 @@ Detects interfaces with more than 5 methods, interfaces whose members mix concer
|
|
|
251
259
|
**Rule ID:** `solid:ocp-violation`
|
|
252
260
|
**Severity:** Warning
|
|
253
261
|
|
|
254
|
-
|
|
262
|
+
Reports an if-else chain with more than 4 conditions (the `if` plus its `else if` links; a final plain `else` is not counted) when every condition compares the same discriminant with `===` or `==`, also joined by `||` (`kind === 'a' || kind === 'b'`). The discriminant is a variable, parameter, property access chain such as `this.state.kind` or element access with a reference or literal key such as `values[key]`; two references match when they resolve to the same symbols and keys, so `a.kind` and `b.kind` are different discriminants. One warning per chain at its first `if`; the message names the enclosing function or method, the discriminant and the number of conditions and suggests a lookup map or polymorphism.
|
|
263
|
+
|
|
264
|
+
Chains are checked in the whole file: methods, constructors, nested classes (each chain once) and functions outside classes. Switch statements are reported by `solid:god-switch`; parameter counts are not reported (no Open/Closed claim; ESLint `max-params` covers them).
|
|
255
265
|
|
|
256
266
|
---
|
|
257
267
|
|
|
258
268
|
### LSPViolationRule
|
|
259
269
|
|
|
260
270
|
**Rule ID:** `solid:lsp-violation`
|
|
261
|
-
**
|
|
271
|
+
**Status:** Deprecated, reports nothing (removed in 3.0)
|
|
262
272
|
|
|
263
|
-
|
|
273
|
+
A class that misses a required member of an implemented interface or an abstract method of its base does not compile (TS2420, TS2515), so on code that builds these checks could only report members they did not see (inherited, optional, constructor parameter properties, arrow properties). An `instanceof` check alone (`error instanceof HttpErrorResponse`) shows no subtype that breaks its base's contract. The rule stays registered so configurations naming it load; ConfigLoader warns that `rules['solid:lsp-violation']` has no effect.
|
|
264
274
|
|
|
265
275
|
---
|
|
266
276
|
|
|
@@ -425,7 +435,7 @@ Transformation guarantees:
|
|
|
425
435
|
**Rule ID:** `solid:service-dip-violation-transform`
|
|
426
436
|
**Transformation Type:** `service-dip-violation-transform`
|
|
427
437
|
|
|
428
|
-
|
|
438
|
+
Reads no findings (the analysis rule `solid:service-dip-violation` is deprecated and reports nothing): for each constructor parameter of an `@Injectable` class that injects a concrete `@Injectable` class, it adds an `I{ClassName}` interface (public method signatures) and a `{CLASS_NAME}_TOKEN` `InjectionToken` to the injected service file, changes the parameter type to the interface, adds `@Inject(TOKEN)` and the needed imports. Parameters that already have `@Inject` are skipped; an existing interface is not created again.
|
|
429
439
|
|
|
430
440
|
---
|
|
431
441
|
|
|
@@ -476,11 +486,11 @@ const context = ContextFactory.createAnalysisContext({
|
|
|
476
486
|
config: {},
|
|
477
487
|
});
|
|
478
488
|
|
|
479
|
-
const
|
|
489
|
+
const results = await dipRule.analyze(context);
|
|
480
490
|
|
|
481
|
-
console.log('DIP Violations found:',
|
|
482
|
-
|
|
483
|
-
console.log(`- ${v.message} at line ${v.
|
|
491
|
+
console.log('DIP Violations found:', results.length);
|
|
492
|
+
results.forEach((v) => {
|
|
493
|
+
console.log(`- ${v.message} at line ${v.line}`);
|
|
484
494
|
});
|
|
485
495
|
```
|
|
486
496
|
|
|
@@ -592,9 +602,8 @@ Most rules use fixed thresholds. Configurable are:
|
|
|
592
602
|
|
|
593
603
|
| Rule | Option | Default | Source |
|
|
594
604
|
|-|-|-|-|
|
|
595
|
-
| `solid:god-switch` | `
|
|
605
|
+
| `solid:god-switch` | `maxCases` (non-lookup clauses) | `10` | `rules['solid:god-switch']` of `.angular-modernizer.json` (`context.config['solid:god-switch']`) |
|
|
596
606
|
| `solid:god-switch-transform` | `godSwitch.minCaseCount`, `generateInterfaces`, `generateFactory`, `strategyNamingPattern`, `factoryNamingPattern` | `10`, `true`, `true`, `'{CaseValue}Strategy'`, `'{SwitchExpression}Factory'` | `context.config` |
|
|
597
|
-
| `solid:service-dip-violation` | `crossLayerOnly` | `false` | `ServiceDipViolationRule` constructor |
|
|
598
607
|
|
|
599
608
|
### Example Configuration
|
|
600
609
|
|
|
@@ -604,7 +613,8 @@ const context = ContextFactory.createAnalysisContext({
|
|
|
604
613
|
project,
|
|
605
614
|
api: createPublicApi(project),
|
|
606
615
|
config: {
|
|
607
|
-
solid:
|
|
616
|
+
// rules['solid:god-switch'] of .angular-modernizer.json
|
|
617
|
+
'solid:god-switch': { maxCases: 15 },
|
|
608
618
|
},
|
|
609
619
|
});
|
|
610
620
|
```
|
|
@@ -675,6 +685,10 @@ describe('DIPViolationRule', () => {
|
|
|
675
685
|
const sourceFile = project.createSourceFile(
|
|
676
686
|
'test.component.ts',
|
|
677
687
|
`
|
|
688
|
+
import { Component, Injectable } from '@angular/core';
|
|
689
|
+
@Injectable() export class UserService {}
|
|
690
|
+
@Injectable() export class UserRepository {}
|
|
691
|
+
|
|
678
692
|
@Component({})
|
|
679
693
|
export class TestComponent {
|
|
680
694
|
private service = new UserService(); // Violation
|
|
@@ -689,11 +703,11 @@ describe('DIPViolationRule', () => {
|
|
|
689
703
|
api: createPublicApi(),
|
|
690
704
|
});
|
|
691
705
|
|
|
692
|
-
const
|
|
706
|
+
const results = await rule.analyze(context);
|
|
693
707
|
|
|
694
|
-
expect(
|
|
695
|
-
expect(
|
|
696
|
-
expect(
|
|
708
|
+
expect(results).toHaveLength(2);
|
|
709
|
+
expect(results[0].message).toContain('UserService');
|
|
710
|
+
expect(results[1].message).toContain('UserRepository');
|
|
697
711
|
});
|
|
698
712
|
|
|
699
713
|
it('should not flag dependency injection', async () => {
|
|
@@ -714,9 +728,9 @@ describe('DIPViolationRule', () => {
|
|
|
714
728
|
api: createPublicApi(),
|
|
715
729
|
});
|
|
716
730
|
|
|
717
|
-
const
|
|
731
|
+
const results = await rule.analyze(context);
|
|
718
732
|
|
|
719
|
-
expect(
|
|
733
|
+
expect(results).toHaveLength(0);
|
|
720
734
|
});
|
|
721
735
|
});
|
|
722
736
|
```
|
|
@@ -737,10 +751,9 @@ describe('DIPViolationRule', () => {
|
|
|
737
751
|
|
|
738
752
|
High-level modules should not depend on low-level modules. Both should depend on abstractions.
|
|
739
753
|
|
|
740
|
-
|
|
741
|
-
- Direct instantiation of
|
|
742
|
-
-
|
|
743
|
-
- Tight coupling between high-level and low-level modules
|
|
754
|
+
Reported by `solid:dip-violation-direct-instantiation`:
|
|
755
|
+
- Direct instantiation of project `@Injectable` classes (`new MyService()`)
|
|
756
|
+
- `Injector.get()` lookups inside class members (info in classes Angular DI does not create)
|
|
744
757
|
|
|
745
758
|
Best practices:
|
|
746
759
|
- Use dependency injection
|
package/dist/index.d.ts
CHANGED
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
* SOLID principles plugin for the Angular Modernizer.
|
|
3
3
|
*
|
|
4
4
|
* {@link SolidPlugin} registers seven analysis rules and two transform rules:
|
|
5
|
-
* - {@link DIPViolationRule}
|
|
5
|
+
* - {@link DIPViolationRule}: Dependency Inversion
|
|
6
|
+
* - {@link ServiceDipViolationRule}: concrete service injection (deprecated,
|
|
7
|
+
* reports nothing)
|
|
6
8
|
* - {@link SingleResponsibilityRule}: Single Responsibility
|
|
7
9
|
* - {@link OCPViolationRule}, {@link GodSwitchAnalysisRule}: Open/Closed
|
|
8
|
-
* - {@link LSPViolationRule}: Liskov Substitution
|
|
10
|
+
* - {@link LSPViolationRule}: Liskov Substitution (deprecated, reports nothing)
|
|
9
11
|
* - {@link ISPViolationRule}: Interface Segregation
|
|
10
12
|
* - {@link GodSwitchTransformRule}: replaces a large switch with a factory and
|
|
11
13
|
* strategy classes ({@link GodSwitchTransformOrchestrator})
|
|
@@ -17,7 +19,7 @@
|
|
|
17
19
|
*/
|
|
18
20
|
export { SolidPlugin } from './solid-plugin.js';
|
|
19
21
|
export { DIPViolationRule } from './rules/dip-violation.rule.js';
|
|
20
|
-
export { SingleResponsibilityRule } from './rules/srp-violation.rule.js';
|
|
22
|
+
export { SingleResponsibilityRule, type SingleResponsibilityRuleOptions, } from './rules/srp-violation.rule.js';
|
|
21
23
|
export { LSPViolationRule } from './rules/lsp-violation.rule.js';
|
|
22
24
|
export { OCPViolationRule } from './rules/ocp-violation.rule.js';
|
|
23
25
|
export { ISPViolationRule } from './rules/isp-violation.rule.js';
|
package/dist/index.js
CHANGED
|
@@ -3,10 +3,12 @@
|
|
|
3
3
|
* SOLID principles plugin for the Angular Modernizer.
|
|
4
4
|
*
|
|
5
5
|
* {@link SolidPlugin} registers seven analysis rules and two transform rules:
|
|
6
|
-
* - {@link DIPViolationRule}
|
|
6
|
+
* - {@link DIPViolationRule}: Dependency Inversion
|
|
7
|
+
* - {@link ServiceDipViolationRule}: concrete service injection (deprecated,
|
|
8
|
+
* reports nothing)
|
|
7
9
|
* - {@link SingleResponsibilityRule}: Single Responsibility
|
|
8
10
|
* - {@link OCPViolationRule}, {@link GodSwitchAnalysisRule}: Open/Closed
|
|
9
|
-
* - {@link LSPViolationRule}: Liskov Substitution
|
|
11
|
+
* - {@link LSPViolationRule}: Liskov Substitution (deprecated, reports nothing)
|
|
10
12
|
* - {@link ISPViolationRule}: Interface Segregation
|
|
11
13
|
* - {@link GodSwitchTransformRule}: replaces a large switch with a factory and
|
|
12
14
|
* strategy classes ({@link GodSwitchTransformOrchestrator})
|
|
@@ -1,51 +1,58 @@
|
|
|
1
1
|
import type { AnalysisRule, AnalysisContext, AnalysisResult } from '@angular-modernizer/plugin-system';
|
|
2
2
|
/**
|
|
3
|
-
* DIP Violation Rule (`solid:dip-violation-direct-instantiation`) -
|
|
4
|
-
*
|
|
3
|
+
* DIP Violation Rule (`solid:dip-violation-direct-instantiation`) - reports
|
|
4
|
+
* dependencies a class creates or looks up itself instead of declaring them
|
|
5
|
+
* for Angular DI. Severity warning per finding, except
|
|
6
|
+
* `service-locator-outside-di` (info).
|
|
5
7
|
*
|
|
6
|
-
*
|
|
7
|
-
* - `new X()`
|
|
8
|
-
* (
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* -
|
|
12
|
-
*
|
|
8
|
+
* Violation types (`violationType` in the metadata):
|
|
9
|
+
* - `direct-instantiation`: `new X()` where `X` resolves by symbol to a class
|
|
10
|
+
* declared in the project (not in a `.d.ts` file) that has an `Injectable`
|
|
11
|
+
* decorator from `@angular/core`. Library classes (`new HttpClient(handler)`)
|
|
12
|
+
* and undecorated helpers or models are not reported, whatever their name.
|
|
13
|
+
* - `service-locator-pattern`: `.get(...)` on a receiver whose type is
|
|
14
|
+
* Angular's `Injector` (type checker), any receiver expression
|
|
15
|
+
* (`this.injector`, a parameter, `inject(Injector)`).
|
|
16
|
+
* - `service-locator-outside-di` (severity info): the same `.get(...)` lookup
|
|
17
|
+
* outside an injection context in a class with no `Injectable`, `Component`,
|
|
18
|
+
* `Directive`, `Pipe` or `NgModule` decorator from `@angular/core`, such as
|
|
19
|
+
* a handler created with `new`. The hidden dependency is real, but
|
|
20
|
+
* `inject()` is not possible there: `suggestedFix` proposes a constructor
|
|
21
|
+
* parameter filled by the code that creates the class.
|
|
13
22
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
23
|
+
* Both are reported only inside class members (methods, constructors,
|
|
24
|
+
* accessors, property initializers), not inside a `useFactory` function, a
|
|
25
|
+
* function passed to `provideAppInitializer`, `provideEnvironmentInitializer`
|
|
26
|
+
* or `providePlatformInitializer`, a decorator or any function outside a class:
|
|
27
|
+
* these build providers and are DI configuration.
|
|
28
|
+
*
|
|
29
|
+
* `suggestedFix` proposes `inject(X)` when the project uses Angular 14 or later
|
|
30
|
+
* (api `angularMajorVersion`) and the call site is an injection context (an
|
|
31
|
+
* instance field initializer or the constructor body, not a nested function);
|
|
32
|
+
* otherwise a constructor parameter (for `service-locator-outside-di` one
|
|
33
|
+
* filled by the creator of the class). Metadata: `violationType`, `principle`,
|
|
34
|
+
* `instantiatedType` or `receiver` and `token`, `injectionContext`,
|
|
35
|
+
* `angularMajorVersion`.
|
|
16
36
|
*
|
|
17
37
|
* @example
|
|
18
38
|
* ```typescript
|
|
19
|
-
*
|
|
20
|
-
* class
|
|
21
|
-
*
|
|
39
|
+
* @Injectable({ providedIn: 'root' })
|
|
40
|
+
* export class UserService {}
|
|
41
|
+
*
|
|
42
|
+
* export class OrderComponent {
|
|
43
|
+
* private users = new UserService(); // reported: bypasses Angular DI
|
|
22
44
|
* }
|
|
23
45
|
* ```
|
|
24
46
|
*/
|
|
25
47
|
export declare class DIPViolationRule implements AnalysisRule {
|
|
26
48
|
readonly id = "solid:dip-violation-direct-instantiation";
|
|
27
49
|
readonly name = "Dependency Inversion Principle Violation";
|
|
28
|
-
readonly description = "Detects
|
|
50
|
+
readonly description = "Detects @Injectable classes created with new and Injector.get() lookups inside class members (info outside Angular DI)";
|
|
29
51
|
readonly severity = "warning";
|
|
30
52
|
readonly category = "solid-violation";
|
|
31
53
|
readonly tags: string[];
|
|
32
|
-
/**
|
|
33
|
-
* Service class suffixes to detect.
|
|
34
|
-
* Aligned with ServicePatternRecognizer patterns for consistency.
|
|
35
|
-
*/
|
|
36
|
-
private readonly defaultServiceSuffixes;
|
|
37
54
|
analyze(context: AnalysisContext): Promise<AnalysisResult[]>;
|
|
38
|
-
/**
|
|
39
|
-
* Check if a new expression violates DIP.
|
|
40
|
-
*/
|
|
41
55
|
private checkNewExpression;
|
|
42
|
-
|
|
43
|
-
* Detect service locator pattern: `injector.get(SomeService)` bypasses Angular DI.
|
|
44
|
-
*/
|
|
45
|
-
private analyzeServiceLocator;
|
|
46
|
-
/**
|
|
47
|
-
* Check if a class name represents a service that should be injected.
|
|
48
|
-
*/
|
|
49
|
-
private isServiceClass;
|
|
56
|
+
private checkInjectorGet;
|
|
50
57
|
}
|
|
51
58
|
//# sourceMappingURL=dip-violation.rule.d.ts.map
|