@angular-modernizer/plugin-solid 2.0.0 → 2.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @angular-modernizer/plugin-solid
2
2
 
3
+ ## 2.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [028078f]
8
+ - Updated dependencies [938445c]
9
+ - @angular-modernizer/api@2.1.1
10
+ - @angular-modernizer/core@2.1.1
11
+ - @angular-modernizer/plugin-system@2.1.1
12
+
13
+ ## 2.1.0
14
+
15
+ ### Patch Changes
16
+
17
+ - 8e55c18: `solid:dip-violation-direct-instantiation`: a constructor body or instance field initializer counts as an injection context only in a class with an `Injectable`, `Component`, `Directive`, `Pipe` or `NgModule` decorator from `@angular/core`. An `Injector.get()` lookup in the constructor or a field initializer of an undecorated class (such as a handler created with `new`) is now reported as `service-locator-outside-di` with severity `info`, `injectionContext: false` and a constructor parameter fix instead of `inject()`. `new X()` of an `@Injectable` class in such a site keeps severity `warning` but now gets the constructor parameter fix and `injectionContext: false`. Decorated classes are unchanged.
18
+ - a3d2ad1: `solid:dip-violation-direct-instantiation`: an `Injector.get()` lookup outside an injection context in a class with no `Injectable`, `Component`, `Directive`, `Pipe` or `NgModule` decorator from `@angular/core` (such as a handler created with `new`) is now reported with severity `info` and `violationType` `service-locator-outside-di`; `suggestedFix` proposes a constructor parameter filled by the creator of the class instead of `inject()`. Lookups in DI-created classes and in injection contexts are unchanged.
19
+ - Updated dependencies [3f77a02]
20
+ - Updated dependencies [a7a2e6a]
21
+ - @angular-modernizer/api@2.1.0
22
+ - @angular-modernizer/core@2.1.0
23
+ - @angular-modernizer/plugin-system@2.1.0
24
+
3
25
  ## 2.0.0
4
26
 
5
27
  ### Minor Changes
package/README.md CHANGED
@@ -48,16 +48,17 @@ Member names and method bodies are not read: the former checks for responsibilit
48
48
  ### DIPViolationRule
49
49
 
50
50
  **Rule ID:** `solid:dip-violation-direct-instantiation`
51
- **Severity:** Warning
51
+ **Severity:** Warning (info for `service-locator-outside-di`)
52
52
 
53
- One warning per finding (`result.severity`). Violation types (`violationType` in the metadata):
53
+ One warning per finding (`result.severity`), except `service-locator-outside-di` (info). Violation types (`violationType` in the metadata):
54
54
 
55
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
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`.
57
58
 
58
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.
59
60
 
60
- `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); otherwise a constructor parameter. Metadata also carries `principle: 'DIP'`, `injectionContext` and `angularMajorVersion`.
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`.
61
62
 
62
63
  **Reported:**
63
64
 
@@ -75,6 +76,14 @@ export class UserComponent {
75
76
  return this.injector.get(UserService); // service-locator-pattern, fix: constructor parameter
76
77
  }
77
78
  }
79
+
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
+ }
86
+ }
78
87
  ```
79
88
 
80
89
  **Not reported:**
@@ -744,7 +753,7 @@ High-level modules should not depend on low-level modules. Both should depend on
744
753
 
745
754
  Reported by `solid:dip-violation-direct-instantiation`:
746
755
  - Direct instantiation of project `@Injectable` classes (`new MyService()`)
747
- - `Injector.get()` lookups inside class members
756
+ - `Injector.get()` lookups inside class members (info in classes Angular DI does not create)
748
757
 
749
758
  Best practices:
750
759
  - Use dependency injection
@@ -2,7 +2,8 @@ import type { AnalysisRule, AnalysisContext, AnalysisResult } from '@angular-mod
2
2
  /**
3
3
  * DIP Violation Rule (`solid:dip-violation-direct-instantiation`) - reports
4
4
  * dependencies a class creates or looks up itself instead of declaring them
5
- * for Angular DI. Severity warning per finding.
5
+ * for Angular DI. Severity warning per finding, except
6
+ * `service-locator-outside-di` (info).
6
7
  *
7
8
  * Violation types (`violationType` in the metadata):
8
9
  * - `direct-instantiation`: `new X()` where `X` resolves by symbol to a class
@@ -12,6 +13,12 @@ import type { AnalysisRule, AnalysisContext, AnalysisResult } from '@angular-mod
12
13
  * - `service-locator-pattern`: `.get(...)` on a receiver whose type is
13
14
  * Angular's `Injector` (type checker), any receiver expression
14
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.
15
22
  *
16
23
  * Both are reported only inside class members (methods, constructors,
17
24
  * accessors, property initializers), not inside a `useFactory` function, a
@@ -22,7 +29,8 @@ import type { AnalysisRule, AnalysisContext, AnalysisResult } from '@angular-mod
22
29
  * `suggestedFix` proposes `inject(X)` when the project uses Angular 14 or later
23
30
  * (api `angularMajorVersion`) and the call site is an injection context (an
24
31
  * instance field initializer or the constructor body, not a nested function);
25
- * otherwise a constructor parameter. Metadata: `violationType`, `principle`,
32
+ * otherwise a constructor parameter (for `service-locator-outside-di` one
33
+ * filled by the creator of the class). Metadata: `violationType`, `principle`,
26
34
  * `instantiatedType` or `receiver` and `token`, `injectionContext`,
27
35
  * `angularMajorVersion`.
28
36
  *
@@ -39,7 +47,7 @@ import type { AnalysisRule, AnalysisContext, AnalysisResult } from '@angular-mod
39
47
  export declare class DIPViolationRule implements AnalysisRule {
40
48
  readonly id = "solid:dip-violation-direct-instantiation";
41
49
  readonly name = "Dependency Inversion Principle Violation";
42
- readonly description = "Detects @Injectable classes created with new and Injector.get() lookups inside class members";
50
+ readonly description = "Detects @Injectable classes created with new and Injector.get() lookups inside class members (info outside Angular DI)";
43
51
  readonly severity = "warning";
44
52
  readonly category = "solid-violation";
45
53
  readonly tags: string[];
@@ -13,10 +13,13 @@ const INITIALIZER_FUNCTIONS = new Set([
13
13
  'provideEnvironmentInitializer',
14
14
  'providePlatformInitializer',
15
15
  ]);
16
+ /** `@angular/core` decorators that make Angular DI create the class. */
17
+ const DI_DECORATORS = ['Injectable', 'Component', 'Directive', 'Pipe', 'NgModule'];
16
18
  /**
17
19
  * DIP Violation Rule (`solid:dip-violation-direct-instantiation`) - reports
18
20
  * dependencies a class creates or looks up itself instead of declaring them
19
- * for Angular DI. Severity warning per finding.
21
+ * for Angular DI. Severity warning per finding, except
22
+ * `service-locator-outside-di` (info).
20
23
  *
21
24
  * Violation types (`violationType` in the metadata):
22
25
  * - `direct-instantiation`: `new X()` where `X` resolves by symbol to a class
@@ -26,6 +29,12 @@ const INITIALIZER_FUNCTIONS = new Set([
26
29
  * - `service-locator-pattern`: `.get(...)` on a receiver whose type is
27
30
  * Angular's `Injector` (type checker), any receiver expression
28
31
  * (`this.injector`, a parameter, `inject(Injector)`).
32
+ * - `service-locator-outside-di` (severity info): the same `.get(...)` lookup
33
+ * outside an injection context in a class with no `Injectable`, `Component`,
34
+ * `Directive`, `Pipe` or `NgModule` decorator from `@angular/core`, such as
35
+ * a handler created with `new`. The hidden dependency is real, but
36
+ * `inject()` is not possible there: `suggestedFix` proposes a constructor
37
+ * parameter filled by the code that creates the class.
29
38
  *
30
39
  * Both are reported only inside class members (methods, constructors,
31
40
  * accessors, property initializers), not inside a `useFactory` function, a
@@ -36,7 +45,8 @@ const INITIALIZER_FUNCTIONS = new Set([
36
45
  * `suggestedFix` proposes `inject(X)` when the project uses Angular 14 or later
37
46
  * (api `angularMajorVersion`) and the call site is an injection context (an
38
47
  * instance field initializer or the constructor body, not a nested function);
39
- * otherwise a constructor parameter. Metadata: `violationType`, `principle`,
48
+ * otherwise a constructor parameter (for `service-locator-outside-di` one
49
+ * filled by the creator of the class). Metadata: `violationType`, `principle`,
40
50
  * `instantiatedType` or `receiver` and `token`, `injectionContext`,
41
51
  * `angularMajorVersion`.
42
52
  *
@@ -53,7 +63,7 @@ const INITIALIZER_FUNCTIONS = new Set([
53
63
  class DIPViolationRule {
54
64
  id = 'solid:dip-violation-direct-instantiation';
55
65
  name = 'Dependency Inversion Principle Violation';
56
- description = 'Detects @Injectable classes created with new and Injector.get() lookups inside class members';
66
+ description = 'Detects @Injectable classes created with new and Injector.get() lookups inside class members (info outside Angular DI)';
57
67
  severity = 'warning';
58
68
  category = 'solid-violation';
59
69
  tags = [
@@ -124,6 +134,26 @@ class DIPViolationRule {
124
134
  const token = call.getArguments()[0]?.getText() ?? 'token';
125
135
  const major = version();
126
136
  const injectionContext = isInjectionContext(call);
137
+ const plainClass = injectionContext ? undefined : classOutsideDi(call);
138
+ if (plainClass !== undefined) {
139
+ return {
140
+ ruleId: this.id,
141
+ severity: 'info',
142
+ message: `Service locator outside Angular DI: ${receiver}.get(${token}) looks up ${token} at runtime in ${plainClass}, a class that Angular DI does not create, so inject() is not available there; the class's dependencies are hidden from its signature.`,
143
+ filePath: sourceFile.getFilePath(),
144
+ line: call.getStartLineNumber(),
145
+ column: call.getStart() - call.getStartLinePos(),
146
+ suggestedFix: `Declare ${token} as a constructor parameter of ${plainClass}, pass it in from the code that creates ${plainClass}, and use it instead of '${receiver}.get(${token})'.`,
147
+ metadata: {
148
+ violationType: 'service-locator-outside-di',
149
+ principle: 'DIP',
150
+ receiver,
151
+ token,
152
+ injectionContext,
153
+ angularMajorVersion: major,
154
+ },
155
+ };
156
+ }
127
157
  return {
128
158
  ruleId: this.id,
129
159
  severity: 'warning',
@@ -173,6 +203,23 @@ function hasAngularInjectable(cls) {
173
203
  return isAngularCoreReference(name, 'Injectable');
174
204
  });
175
205
  }
206
+ /**
207
+ * Name of the class around `node` when it has no `@angular/core` decorator
208
+ * that makes Angular DI create it (`Injectable`, `Component`, `Directive`,
209
+ * `Pipe`, `NgModule`); `undefined` for a DI-created class or no class.
210
+ */
211
+ function classOutsideDi(node) {
212
+ const cls = node.getFirstAncestor((ancestor) => ts_morph_1.Node.isClassDeclaration(ancestor) || ts_morph_1.Node.isClassExpression(ancestor));
213
+ if (!ts_morph_1.Node.isClassDeclaration(cls) && !ts_morph_1.Node.isClassExpression(cls)) {
214
+ return undefined;
215
+ }
216
+ const createdByDi = cls.getDecorators().some((decorator) => {
217
+ const call = decorator.getCallExpression();
218
+ const name = call ? call.getExpression() : decorator.getExpression();
219
+ return DI_DECORATORS.some((exported) => isAngularCoreReference(name, exported));
220
+ });
221
+ return createdByDi ? undefined : (cls.getName() ?? 'class');
222
+ }
176
223
  /** `true` when the type of `receiver` is the `Injector` class of `@angular/core`. */
177
224
  function isAngularInjectorType(receiver) {
178
225
  const type = receiver.getType();
@@ -268,15 +315,17 @@ function isInClassMember(node) {
268
315
  /**
269
316
  * `true` when `node` runs in Angular's injection context: directly in an
270
317
  * instance field initializer or the constructor body, with no function in
271
- * between (a callback runs later, outside the context).
318
+ * between (a callback runs later, outside the context), of a class that
319
+ * Angular DI creates (see `classOutsideDi`). A class created with `new` has
320
+ * no injection context.
272
321
  */
273
322
  function isInjectionContext(node) {
274
323
  for (let current = node.getParent(); current !== undefined; current = current.getParent()) {
275
324
  if (ts_morph_1.Node.isConstructorDeclaration(current)) {
276
- return true;
325
+ return classOutsideDi(current) === undefined;
277
326
  }
278
327
  if (ts_morph_1.Node.isPropertyDeclaration(current)) {
279
- return !current.isStatic();
328
+ return !current.isStatic() && classOutsideDi(current) === undefined;
280
329
  }
281
330
  if (ts_morph_1.Node.isFunctionLikeDeclaration(current) || ts_morph_1.Node.isClassStaticBlockDeclaration(current)) {
282
331
  return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@angular-modernizer/plugin-solid",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "description": "Analysis plugin for detecting SOLID principle violations.",
5
5
  "keywords": [
6
6
  "angular",
@@ -22,9 +22,9 @@
22
22
  "!dist/**/*.map"
23
23
  ],
24
24
  "dependencies": {
25
- "@angular-modernizer/core": "2.0.0",
26
- "@angular-modernizer/plugin-system": "2.0.0",
27
- "@angular-modernizer/api": "2.0.0"
25
+ "@angular-modernizer/core": "2.1.1",
26
+ "@angular-modernizer/plugin-system": "2.1.1",
27
+ "@angular-modernizer/api": "2.1.1"
28
28
  },
29
29
  "devDependencies": {
30
30
  "@types/jest": "^30.0.0",