@openrewrite/recipes-angular 1.20.0 → 1.22.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.
Files changed (168) hide show
  1. package/dist/libraries/primeng/18/add-primeng-provider.d.ts.map +1 -1
  2. package/dist/libraries/primeng/18/add-primeng-provider.js +6 -22
  3. package/dist/libraries/primeng/18/add-primeng-provider.js.map +1 -1
  4. package/dist/libraries/primeng/18/mark-removed-primeng-modules.js +1 -1
  5. package/dist/libraries/primeng/18/mark-removed-primeng-modules.js.map +1 -1
  6. package/dist/libraries/primeng/18/migrate-p-fluid-to-wrapper.js +1 -1
  7. package/dist/libraries/primeng/18/migrate-p-fluid-to-wrapper.js.map +1 -1
  8. package/dist/migration/add-default-configuration.d.ts.map +1 -1
  9. package/dist/migration/add-default-configuration.js +8 -48
  10. package/dist/migration/add-default-configuration.js.map +1 -1
  11. package/dist/migration/add-eager-change-detection.js +1 -1
  12. package/dist/migration/add-eager-change-detection.js.map +1 -1
  13. package/dist/migration/add-istanbul-instrumenter.d.ts.map +1 -1
  14. package/dist/migration/add-istanbul-instrumenter.js +8 -22
  15. package/dist/migration/add-istanbul-instrumenter.js.map +1 -1
  16. package/dist/migration/add-module-with-providers-generic.js +1 -1
  17. package/dist/migration/add-module-with-providers-generic.js.map +1 -1
  18. package/dist/migration/add-static-false-to-view-queries.d.ts +11 -0
  19. package/dist/migration/add-static-false-to-view-queries.d.ts.map +1 -1
  20. package/dist/migration/add-static-false-to-view-queries.js +329 -36
  21. package/dist/migration/add-static-false-to-view-queries.js.map +1 -1
  22. package/dist/migration/add-strict-templates-false.d.ts.map +1 -1
  23. package/dist/migration/add-strict-templates-false.js +4 -35
  24. package/dist/migration/add-strict-templates-false.js.map +1 -1
  25. package/dist/migration/add-trust-proxy-headers.js +1 -1
  26. package/dist/migration/add-trust-proxy-headers.js.map +1 -1
  27. package/dist/migration/angular-http-support.d.ts +0 -1
  28. package/dist/migration/angular-http-support.d.ts.map +1 -1
  29. package/dist/migration/angular-http-support.js +1 -5
  30. package/dist/migration/angular-http-support.js.map +1 -1
  31. package/dist/migration/enable-aot-build.d.ts.map +1 -1
  32. package/dist/migration/enable-aot-build.js +8 -57
  33. package/dist/migration/enable-aot-build.js.map +1 -1
  34. package/dist/migration/explicit-standalone-flag.js +2 -2
  35. package/dist/migration/explicit-standalone-flag.js.map +1 -1
  36. package/dist/migration/js-support.d.ts +4 -0
  37. package/dist/migration/js-support.d.ts.map +1 -1
  38. package/dist/migration/js-support.js +12 -0
  39. package/dist/migration/js-support.js.map +1 -1
  40. package/dist/migration/json-support.d.ts +0 -11
  41. package/dist/migration/json-support.d.ts.map +1 -1
  42. package/dist/migration/json-support.js +1 -96
  43. package/dist/migration/json-support.js.map +1 -1
  44. package/dist/migration/migrate-input-to-signal.js +1 -1
  45. package/dist/migration/migrate-input-to-signal.js.map +1 -1
  46. package/dist/migration/migrate-model-with-output.js +1 -1
  47. package/dist/migration/migrate-model-with-output.js.map +1 -1
  48. package/dist/migration/migrate-query-to-signal.js +1 -1
  49. package/dist/migration/migrate-query-to-signal.js.map +1 -1
  50. package/dist/migration/migrate-to-solution-style-tsconfig.d.ts.map +1 -1
  51. package/dist/migration/migrate-to-solution-style-tsconfig.js +25 -56
  52. package/dist/migration/migrate-to-solution-style-tsconfig.js.map +1 -1
  53. package/dist/migration/remove-aot-summaries.js +1 -1
  54. package/dist/migration/remove-aot-summaries.js.map +1 -1
  55. package/dist/migration/remove-browser-module-with-server-transition.d.ts.map +1 -1
  56. package/dist/migration/remove-browser-module-with-server-transition.js +6 -16
  57. package/dist/migration/remove-browser-module-with-server-transition.js.map +1 -1
  58. package/dist/migration/remove-default-project.d.ts.map +1 -1
  59. package/dist/migration/remove-default-project.js +1 -17
  60. package/dist/migration/remove-default-project.js.map +1 -1
  61. package/dist/migration/remove-enable-ivy.d.ts.map +1 -1
  62. package/dist/migration/remove-enable-ivy.js +2 -15
  63. package/dist/migration/remove-enable-ivy.js.map +1 -1
  64. package/dist/migration/remove-entry-components.js +1 -1
  65. package/dist/migration/remove-entry-components.js.map +1 -1
  66. package/dist/migration/remove-es5-browser-support.d.ts.map +1 -1
  67. package/dist/migration/remove-es5-browser-support.js +2 -15
  68. package/dist/migration/remove-es5-browser-support.js.map +1 -1
  69. package/dist/migration/remove-extract-css.d.ts.map +1 -1
  70. package/dist/migration/remove-extract-css.js +2 -15
  71. package/dist/migration/remove-extract-css.js.map +1 -1
  72. package/dist/migration/remove-ie-polyfills.d.ts.map +1 -1
  73. package/dist/migration/remove-ie-polyfills.js +4 -18
  74. package/dist/migration/remove-ie-polyfills.js.map +1 -1
  75. package/dist/migration/remove-module-id.js +1 -1
  76. package/dist/migration/remove-module-id.js.map +1 -1
  77. package/dist/migration/remove-relative-link-resolution.js +1 -1
  78. package/dist/migration/remove-relative-link-resolution.js.map +1 -1
  79. package/dist/migration/remove-standalone-true.js +1 -1
  80. package/dist/migration/remove-standalone-true.js.map +1 -1
  81. package/dist/migration/remove-static-false.js +1 -1
  82. package/dist/migration/remove-static-false.js.map +1 -1
  83. package/dist/migration/remove-zone-js-polyfill.d.ts.map +1 -1
  84. package/dist/migration/remove-zone-js-polyfill.js +4 -18
  85. package/dist/migration/remove-zone-js-polyfill.js.map +1 -1
  86. package/dist/migration/rename-check-no-changes.d.ts.map +1 -1
  87. package/dist/migration/rename-check-no-changes.js +2 -4
  88. package/dist/migration/rename-check-no-changes.js.map +1 -1
  89. package/dist/migration/rename-ssr-experimental-platform.js +8 -28
  90. package/dist/migration/rename-ssr-experimental-platform.js.map +1 -1
  91. package/dist/migration/replace-deep-zone-js-imports.d.ts.map +1 -1
  92. package/dist/migration/replace-deep-zone-js-imports.js +6 -27
  93. package/dist/migration/replace-deep-zone-js-imports.js.map +1 -1
  94. package/dist/migration/replace-http-client-module.js +1 -1
  95. package/dist/migration/replace-http-client-module.js.map +1 -1
  96. package/dist/migration/replace-initial-navigation.d.ts.map +1 -1
  97. package/dist/migration/replace-initial-navigation.js +8 -8
  98. package/dist/migration/replace-initial-navigation.js.map +1 -1
  99. package/dist/migration/set-tsconfig-module-resolution-bundler.d.ts.map +1 -1
  100. package/dist/migration/set-tsconfig-module-resolution-bundler.js +7 -56
  101. package/dist/migration/set-tsconfig-module-resolution-bundler.js.map +1 -1
  102. package/dist/migration/suppress-safe-navigation-diagnostics.d.ts.map +1 -1
  103. package/dist/migration/suppress-safe-navigation-diagnostics.js +6 -8
  104. package/dist/migration/suppress-safe-navigation-diagnostics.js.map +1 -1
  105. package/dist/migration/update-component-template-url.d.ts.map +1 -1
  106. package/dist/migration/update-component-template-url.js +2 -2
  107. package/dist/migration/update-component-template-url.js.map +1 -1
  108. package/dist/migration/update-tsconfig-module.d.ts.map +1 -1
  109. package/dist/migration/update-tsconfig-module.js +8 -40
  110. package/dist/migration/update-tsconfig-module.js.map +1 -1
  111. package/dist/migration/update-tsconfig-target.d.ts.map +1 -1
  112. package/dist/migration/update-tsconfig-target.js +5 -34
  113. package/dist/migration/update-tsconfig-target.js.map +1 -1
  114. package/dist/migration/upgrade-angular-dependencies.js +2 -2
  115. package/dist/migration/upgrade-angular-dependencies.js.map +1 -1
  116. package/dist/migration/upgrade-to-angular-8.js +1 -1
  117. package/dist/migration/upgrade-to-angular-8.js.map +1 -1
  118. package/dist/search/find-empty-projectable-nodes.js +1 -1
  119. package/dist/search/find-empty-projectable-nodes.js.map +1 -1
  120. package/dist/search/find-provided-in-deprecated-usage.js +1 -1
  121. package/dist/search/find-provided-in-deprecated-usage.js.map +1 -1
  122. package/package.json +2 -2
  123. package/src/libraries/primeng/18/add-primeng-provider.ts +10 -36
  124. package/src/libraries/primeng/18/mark-removed-primeng-modules.ts +3 -3
  125. package/src/libraries/primeng/18/migrate-p-fluid-to-wrapper.ts +3 -3
  126. package/src/migration/add-default-configuration.ts +7 -71
  127. package/src/migration/add-eager-change-detection.ts +3 -3
  128. package/src/migration/add-istanbul-instrumenter.ts +9 -23
  129. package/src/migration/add-module-with-providers-generic.ts +3 -3
  130. package/src/migration/add-static-false-to-view-queries.ts +317 -40
  131. package/src/migration/add-strict-templates-false.ts +8 -39
  132. package/src/migration/add-trust-proxy-headers.ts +4 -4
  133. package/src/migration/angular-http-support.ts +2 -5
  134. package/src/migration/enable-aot-build.ts +10 -97
  135. package/src/migration/explicit-standalone-flag.ts +5 -5
  136. package/src/migration/js-support.ts +13 -1
  137. package/src/migration/json-support.ts +2 -102
  138. package/src/migration/migrate-input-to-signal.ts +3 -3
  139. package/src/migration/migrate-model-with-output.ts +3 -3
  140. package/src/migration/migrate-query-to-signal.ts +3 -3
  141. package/src/migration/migrate-to-solution-style-tsconfig.ts +29 -68
  142. package/src/migration/remove-aot-summaries.ts +3 -3
  143. package/src/migration/remove-browser-module-with-server-transition.ts +7 -27
  144. package/src/migration/remove-default-project.ts +2 -29
  145. package/src/migration/remove-enable-ivy.ts +3 -27
  146. package/src/migration/remove-entry-components.ts +3 -3
  147. package/src/migration/remove-es5-browser-support.ts +3 -27
  148. package/src/migration/remove-extract-css.ts +3 -27
  149. package/src/migration/remove-ie-polyfills.ts +5 -29
  150. package/src/migration/remove-module-id.ts +3 -3
  151. package/src/migration/remove-relative-link-resolution.ts +3 -3
  152. package/src/migration/remove-standalone-true.ts +3 -3
  153. package/src/migration/remove-static-false.ts +3 -3
  154. package/src/migration/remove-zone-js-polyfill.ts +5 -29
  155. package/src/migration/rename-check-no-changes.ts +3 -5
  156. package/src/migration/rename-ssr-experimental-platform.ts +8 -23
  157. package/src/migration/replace-deep-zone-js-imports.ts +11 -40
  158. package/src/migration/replace-http-client-module.ts +3 -3
  159. package/src/migration/replace-initial-navigation.ts +10 -14
  160. package/src/migration/set-tsconfig-module-resolution-bundler.ts +8 -52
  161. package/src/migration/suppress-safe-navigation-diagnostics.ts +8 -14
  162. package/src/migration/update-component-template-url.ts +4 -8
  163. package/src/migration/update-tsconfig-module.ts +10 -49
  164. package/src/migration/update-tsconfig-target.ts +6 -35
  165. package/src/migration/upgrade-angular-dependencies.ts +2 -2
  166. package/src/migration/upgrade-to-angular-8.ts +1 -1
  167. package/src/search/find-empty-projectable-nodes.ts +3 -3
  168. package/src/search/find-provided-in-deprecated-usage.ts +3 -3
@@ -5,8 +5,7 @@
5
5
  */
6
6
 
7
7
  import {ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
8
- import {detectIndent, getMemberKeyName, isObject, Json, JsonVisitor} from "@openrewrite/rewrite/json";
9
- import {addMemberPath, literal, memberIndent} from "./json-support";
8
+ import {isObject, Json, jsonLiteral, JsonVisitor, membersOf, getMemberKeyName, setAt, valueAt} from "@openrewrite/rewrite/json";
10
9
 
11
10
  const PACKAGE = 'istanbul-lib-instrument';
12
11
  const VERSION = '^6.0.3';
@@ -25,36 +24,23 @@ export class AddIstanbulInstrumenter extends Recipe {
25
24
  protected async visitDocument(doc: Json.Document, p: ExecutionContext): Promise<Json | undefined> {
26
25
  if (!doc.sourcePath.endsWith('package.json')) return doc;
27
26
 
28
- const root = doc.value;
29
- if (!isObject(root)) return doc;
30
-
31
- const declared = declaredPackages(root);
27
+ const declared = declaredPackages(doc);
32
28
  if (declared.has(PACKAGE)) return doc;
33
29
  if (![...declared].some(name => name === 'karma' || name.startsWith('karma-'))) return doc;
34
30
 
35
- const indentUnit = detectIndent(doc);
36
- const value = addMemberPath(root, ['devDependencies', PACKAGE],
37
- literal(`"${VERSION}"`, VERSION), memberIndent(root, indentUnit), indentUnit);
38
-
39
- return value === root ? doc : {...doc, value} as Json.Document;
31
+ return setAt(doc, ['devDependencies', PACKAGE], jsonLiteral(VERSION), {createMissing: true, position: 'sorted'});
40
32
  }
41
33
  }();
42
34
  }
43
35
  }
44
36
 
45
- function declaredPackages(root: Json.Object): Set<string> {
37
+ function declaredPackages(doc: Json.Document): Set<string> {
46
38
  const declared = new Set<string>();
47
- for (const rp of root.members) {
48
- const member = rp.element;
49
- if (member.kind !== Json.Kind.Member) continue;
50
- if (!DEPENDENCY_SCOPES.includes(getMemberKeyName(member as Json.Member) ?? '')) continue;
51
-
52
- const scope = (member as Json.Member).value;
53
- if (!isObject(scope)) continue;
54
-
55
- for (const dep of scope.members) {
56
- if (dep.element.kind !== Json.Kind.Member) continue;
57
- const name = getMemberKeyName(dep.element as Json.Member);
39
+ for (const scopeName of DEPENDENCY_SCOPES) {
40
+ const scope = valueAt(doc, [scopeName]);
41
+ if (!scope || !isObject(scope)) continue;
42
+ for (const dep of membersOf(scope)) {
43
+ const name = getMemberKeyName(dep);
58
44
  if (name) declared.add(name);
59
45
  }
60
46
  }
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import {ExecutionContext, Recipe, TreeVisitor, randomId, emptyMarkers} from "@openrewrite/rewrite";
8
- import {JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
8
+ import {JavaScriptVisitor, isObjectLiteral, JS} from "@openrewrite/rewrite/javascript";
9
9
  import {J, isIdentifier, emptySpace} from "@openrewrite/rewrite/java";
10
10
 
11
11
  export class AddModuleWithProvidersGeneric extends Recipe {
@@ -81,9 +81,9 @@ function findNgModuleName(body?: J.Block): string | undefined {
81
81
  if (s.kind !== J.Kind.Return) continue;
82
82
 
83
83
  const ret = s as J.Return;
84
- if (!ret.expression || ret.expression.kind !== J.Kind.NewClass) continue;
84
+ if (!ret.expression || !isObjectLiteral(ret.expression)) continue;
85
85
 
86
- const newClass = ret.expression as J.NewClass;
86
+ const newClass = ret.expression;
87
87
  if (!newClass.body) continue;
88
88
 
89
89
  for (const bodyStmt of newClass.body.statements) {
@@ -4,89 +4,366 @@
4
4
  * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
5
  */
6
6
 
7
- import {ExecutionContext, Recipe, TreeVisitor, emptyMarkers} from "@openrewrite/rewrite";
8
- import {JavaScriptVisitor, JS, template} from "@openrewrite/rewrite/javascript";
9
- import {J, isIdentifier, emptySpace, singleSpace} from "@openrewrite/rewrite/java";
7
+ import {Cursor, ExecutionContext, Recipe, TreeVisitor, foundSearchResult} from "@openrewrite/rewrite";
8
+ import {compilationUnitOf, isObjectLiteral, JavaScriptVisitor, JS, template, walk} from "@openrewrite/rewrite/javascript";
9
+ import {
10
+ J,
11
+ Type,
12
+ emptySpace,
13
+ isClassDeclaration,
14
+ isIdentifier,
15
+ isLiteral,
16
+ isMethodDeclaration,
17
+ isVariableDeclarations,
18
+ singleSpace
19
+ } from "@openrewrite/rewrite/java";
10
20
  import {create} from "mutative";
21
+ import {findTrailingComma, rightPadded, withTrailingComma, withoutTrailingComma} from "./js-support";
22
+ import {extendedClassName} from "../libraries/components/lst";
11
23
 
12
- const QUERY_DECORATORS = ['ViewChild', 'ContentChild'];
24
+ const GUIDE = "https://v8.angular.io/guide/static-query-migration";
13
25
 
26
+ /**
27
+ * The lifecycle hooks in which Angular 7 code could only have read a query that the compiler resolved
28
+ * statically, before the first change detection. These are the lists of the usage strategy of Angular's
29
+ * own v8 `static-queries` schematic (`STATIC_QUERY_LIFECYCLE_HOOKS`).
30
+ */
31
+ const EARLY_HOOKS = new Map<string, ReadonlySet<string>>([
32
+ ['@angular/core.ViewChild', new Set(['ngOnChanges', 'ngOnInit', 'ngDoCheck', 'ngAfterContentInit', 'ngAfterContentChecked'])],
33
+ ['@angular/core.ContentChild', new Set(['ngOnChanges', 'ngOnInit', 'ngDoCheck'])],
34
+ ]);
35
+ const ALL_HOOKS: ReadonlySet<string> = new Set([...EARLY_HOOKS.values()].flatMap(hooks => [...hooks]));
36
+ const CLASS_DECORATORS = new Set(['@angular/core.Component', '@angular/core.Directive']);
37
+ const INPUT = '@angular/core.Input';
38
+
39
+ const STATIC_TRUE = template`({ static: true })`;
40
+ const STATIC_FALSE = template`({ static: false })`;
41
+
42
+ const UNDECIDED = "Added `static: false`, but can't tell whether this query is read before the first change detection. " +
43
+ "Use `static: true` if the class reads it in `ngOnInit` or earlier (Angular 7 resolved it then " +
44
+ "unless it was inside `*ngIf` or `*ngFor`). See " + GUIDE;
45
+
46
+ /**
47
+ * Adds an explicit `static` flag to `@ViewChild` and `@ContentChild` queries, choosing the timing the
48
+ * way Angular's own v8 migration does from how the class uses the query.
49
+ *
50
+ * ```ts
51
+ * @ViewChild('input') input: ElementRef; // read in ngOnInit
52
+ * @ViewChild('input', { static: true }) input: ElementRef;
53
+ * ```
54
+ *
55
+ * @see https://v8.angular.io/guide/static-query-migration
56
+ */
14
57
  export class AddStaticFalseToViewQueries extends Recipe {
15
58
  readonly name = "org.openrewrite.angular.migration.add-static-false-to-view-queries";
16
- readonly displayName: string = "Add `static: false` to view queries";
17
- readonly description: string = "Adds `static: false` to `@ViewChild` and `@ContentChild` decorators that don't have the `static` property. " +
18
- "Angular 8 requires an explicit `static` flag for view query decorators. " +
19
- "Using `static: false` preserves the Angular 7 default behavior (queries resolved after change detection).";
59
+ readonly displayName: string = "Add the `static` flag to view queries";
60
+ readonly description: string = "Adds the `static` flag that Angular 8 requires to `@ViewChild` and `@ContentChild` queries that don't have one. " +
61
+ "In Angular 7 a query outside `*ngIf` and `*ngFor` was resolved before `ngOnInit`, so a query the class reads in " +
62
+ "`ngOnChanges`, `ngOnInit`, `ngDoCheck` or an `@Input` setter (for `@ViewChild` also `ngAfterContentInit` and " +
63
+ "`ngAfterContentChecked`), directly or through its own methods, gets `static: true`, and one it reads only later " +
64
+ "gets `static: false`. Where the class's code can't tell, such as a read inside a callback or an inherited lifecycle hook, " +
65
+ "the query gets `static: false` and is marked. Reads from templates are not analyzed.";
20
66
 
21
67
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
22
68
  return new class extends JavaScriptVisitor<ExecutionContext> {
69
+ private readonly classes = new WeakMap<J.ClassDeclaration, ClassAnalysis>();
70
+
23
71
  override async visitAnnotation(annotation: J.Annotation, p: ExecutionContext): Promise<J | undefined> {
24
72
  let a = await super.visitAnnotation(annotation, p) as J.Annotation;
25
73
  if (!a) return a;
26
74
 
27
- const annotType = a.annotationType;
28
- if (!isIdentifier(annotType)) return a;
29
- if (!QUERY_DECORATORS.includes(annotType.simpleName)) return a;
75
+ const earlyHooks = EARLY_HOOKS.get(decoratorType(a) ?? '');
76
+ if (!earlyHooks) return a;
30
77
 
31
- if (!a.arguments?.elements || a.arguments.elements.length === 0) return a;
78
+ // `@ViewChild()` has no selector to add options after.
79
+ if (!a.arguments?.elements || a.arguments.elements.every(e => e.element.kind === J.Kind.Empty)) return a;
32
80
 
81
+ let optionsObj: J.NewClass | undefined;
33
82
  if (a.arguments.elements.length >= 2) {
34
83
  const optionsArg = a.arguments.elements[1].element;
35
- if (optionsArg.kind !== J.Kind.NewClass) return a;
36
- const optionsObj = optionsArg as J.NewClass;
84
+ if (!isObjectLiteral(optionsArg)) return a;
85
+ optionsObj = optionsArg;
37
86
  if (!optionsObj.body) return a;
38
87
 
39
88
  for (const stmt of optionsObj.body.statements) {
40
- if (stmt.element.kind === JS.Kind.PropertyAssignment) {
41
- const prop = stmt.element as JS.PropertyAssignment;
42
- if (isIdentifier(prop.name.element) && prop.name.element.simpleName === 'static') {
43
- return a;
44
- }
89
+ // A spread may already carry `static`, which a flag added after it would override.
90
+ if (stmt.element.kind === JS.Kind.Spread) return a;
91
+ if (stmt.element.kind === JS.Kind.PropertyAssignment &&
92
+ propertyName(stmt.element as JS.PropertyAssignment) === 'static') {
93
+ return a;
45
94
  }
46
95
  }
96
+ }
97
+
98
+ const timing = await queryTiming(this.cursor, earlyHooks, this.classes);
99
+ const flagged = await this.addFlag(a, optionsObj, timing === true);
100
+ return timing === undefined ? foundSearchResult(flagged, UNDECIDED) : flagged;
101
+ }
102
+
103
+ private async addFlag(a: J.Annotation, optionsObj: J.NewClass | undefined, isStatic: boolean): Promise<J.Annotation> {
104
+ const obj = await (isStatic ? STATIC_TRUE : STATIC_FALSE).apply(a, this.cursor) as any;
47
105
 
48
- const obj = await template`({ static: false })`.apply(a, this.cursor) as any;
106
+ if (optionsObj) {
49
107
  const staticProp = obj.tree.element.body.statements[0].element;
50
- const refProp = optionsObj.body.statements[0]?.element as JS.PropertyAssignment | undefined;
108
+ const refProp = optionsObj.body!.statements[0]?.element as JS.PropertyAssignment | undefined;
51
109
 
52
- const wrappedProp: J.RightPadded<any> = {
53
- kind: J.Kind.RightPadded,
54
- element: refProp ? {...staticProp, prefix: refProp.prefix} : staticProp,
55
- after: emptySpace,
56
- markers: emptyMarkers,
57
- };
110
+ let wrappedProp = rightPadded(refProp ? {...staticProp, prefix: refProp.prefix} : staticProp);
111
+ const statements = [...optionsObj.body!.statements];
112
+ const last = statements.length - 1;
113
+ // `{ read: ElementRef, }` keeps its trailing comma after the flag rather than before it.
114
+ const trailingComma = last >= 0 ? findTrailingComma(statements[last]) : undefined;
115
+ if (trailingComma) {
116
+ statements[last] = withoutTrailingComma(statements[last]);
117
+ wrappedProp = withTrailingComma(wrappedProp, trailingComma);
118
+ }
58
119
 
59
120
  return create(a, draft => {
60
121
  const body = (draft.arguments!.elements[1].element as any).body!;
61
- body.statements = [...body.statements, wrappedProp];
122
+ body.statements = [...statements, wrappedProp];
62
123
  }) as J.Annotation;
63
124
  }
64
125
 
65
- const obj = await template`({ static: false })`.apply(a, this.cursor) as any;
66
126
  const optionsNode = obj.tree.element;
67
127
 
68
- const fixedStatements = optionsNode.body.statements.map((s: any, i: number, arr: any[]) => ({
128
+ // `{ static: false }` with one space inside each brace, whatever spacing the template parsed with.
129
+ const fixedStatements = optionsNode.body.statements.map((s: any) => ({
69
130
  ...s,
70
131
  element: {...s.element, prefix: singleSpace},
71
- after: i === arr.length - 1 ? singleSpace : s.after,
132
+ after: emptySpace,
72
133
  }));
73
134
  const fixedOptionsNode = {
74
135
  ...optionsNode,
75
136
  prefix: singleSpace,
76
- body: {...optionsNode.body, statements: fixedStatements},
77
- };
78
-
79
- const wrappedOptions: J.RightPadded<any> = {
80
- kind: J.Kind.RightPadded,
81
- element: fixedOptionsNode,
82
- after: emptySpace,
83
- markers: emptyMarkers,
137
+ body: {...optionsNode.body, statements: fixedStatements, end: singleSpace},
84
138
  };
85
139
 
86
140
  return create(a, draft => {
87
- draft.arguments!.elements = [...draft.arguments!.elements, wrappedOptions];
141
+ draft.arguments!.elements = [...draft.arguments!.elements, rightPadded(fixedOptionsNode)];
88
142
  }) as J.Annotation;
89
143
  }
90
144
  }();
91
145
  }
92
146
  }
147
+
148
+ /** The fully qualified type of a decorator, which resolves `@ViewChild`, an alias and `@ng.ViewChild` alike. */
149
+ function decoratorType(a: J.Annotation): string | undefined {
150
+ const type = (a.annotationType as J.Identifier | J.FieldAccess).type;
151
+ return Type.isClass(type) ? type.fullyQualifiedName : undefined;
152
+ }
153
+
154
+ function isAccessor(method: J.MethodDeclaration, keyword?: 'get' | 'set'): boolean {
155
+ return method.modifiers.some(m => m.type === J.ModifierType.LanguageExtension &&
156
+ (keyword ? m.keyword === keyword : m.keyword === 'get' || m.keyword === 'set'));
157
+ }
158
+
159
+ function isThis(tree: J | undefined): boolean {
160
+ return tree !== undefined && isIdentifier(tree) && tree.simpleName === 'this';
161
+ }
162
+
163
+ /** What a class's own code says about when it reads its properties, shared by all of its queries. */
164
+ interface ClassAnalysis {
165
+ readonly methods: Map<string, J.MethodDeclaration[]>;
166
+ /**
167
+ * The bodies of the arrow functions the class holds in properties, which `this.<name>()` calls as methods.
168
+ * Only arrow functions: a call to any other property, such as a bound method, counts as `this` escaping.
169
+ */
170
+ readonly functions: Map<string, J>;
171
+ /** A lifecycle hook written as an arrow function property. */
172
+ readonly arrowHook: boolean;
173
+ readonly reads: Map<ReadonlySet<string>, Promise<ReadCollector>>;
174
+ inherits?: boolean;
175
+ }
176
+
177
+ function analyzeClass(clazz: J.ClassDeclaration): ClassAnalysis {
178
+ const methods = new Map<string, J.MethodDeclaration[]>();
179
+ const functions = new Map<string, J>();
180
+ let arrowHook = false;
181
+ for (const {element} of clazz.body.statements) {
182
+ if (isMethodDeclaration(element) && element.body && !isStatic(element.modifiers)) {
183
+ methods.set(element.name.simpleName, [...methods.get(element.name.simpleName) ?? [], element]);
184
+ } else if (isVariableDeclarations(element) && !isStatic(element.modifiers)) {
185
+ for (const {element: v} of element.variables) {
186
+ if (!isIdentifier(v.name)) continue;
187
+ if (ALL_HOOKS.has(v.name.simpleName)) arrowHook = true;
188
+ const initializer = v.initializer?.element;
189
+ if (initializer?.kind === JS.Kind.ArrowFunction) {
190
+ functions.set(v.name.simpleName, (initializer as JS.ArrowFunction).lambda.body);
191
+ }
192
+ }
193
+ }
194
+ }
195
+ return {methods, functions, arrowHook, reads: new Map()};
196
+ }
197
+
198
+ function isStatic(modifiers: J.Modifier[]): boolean {
199
+ return modifiers.some(m => m.type === J.ModifierType.Static);
200
+ }
201
+
202
+ /**
203
+ * `true` when the class reads the query before its first change detection, `false` when it reads it
204
+ * only later, and `undefined` when its own code can't tell. The cursor is on the query's decorator.
205
+ */
206
+ async function queryTiming(cursor: Cursor, earlyHooks: ReadonlySet<string>,
207
+ classes: WeakMap<J.ClassDeclaration, ClassAnalysis>): Promise<boolean | undefined> {
208
+ const member = cursor.parentTree()?.value;
209
+ const clazz = cursor.firstEnclosing(isClassDeclaration);
210
+ // A query declared on a setter has no property to follow, as in Angular's own migration.
211
+ if (!clazz || !isVariableDeclarations(member) || member.variables.length !== 1) return undefined;
212
+ const property = member.variables[0].element.name;
213
+ if (!isIdentifier(property)) return undefined;
214
+
215
+ let analysis = classes.get(clazz);
216
+ if (!analysis) {
217
+ analysis = analyzeClass(clazz);
218
+ classes.set(clazz, analysis);
219
+ }
220
+ if (analysis.arrowHook) return undefined;
221
+
222
+ let pending = analysis.reads.get(earlyHooks);
223
+ if (!pending) {
224
+ const {methods, functions} = analysis;
225
+ const isInput = (name: string) => (methods.get(name) ?? []).some(m =>
226
+ isAccessor(m) && m.leadingAnnotations.some(a => decoratorType(a) === INPUT));
227
+ // `@Input()` may sit on the getter of the setter that receives the input.
228
+ const roots = [...methods.values()].flat().filter(m =>
229
+ isAccessor(m, 'set') ? isInput(m.name.simpleName) : !isAccessor(m) && earlyHooks.has(m.name.simpleName));
230
+ pending = new ReadCollector(methods, functions).collect(roots);
231
+ analysis.reads.set(earlyHooks, pending);
232
+ }
233
+ const reads = await pending;
234
+
235
+ if (reads.sync.has(property.simpleName)) return true;
236
+ if (reads.ambiguous.has(property.simpleName) || reads.thisEscapes) return undefined;
237
+ analysis.inherits ??= mayInheritOrBeInherited(clazz, cursor);
238
+ if (analysis.inherits) return undefined;
239
+ return false;
240
+ }
241
+
242
+ /**
243
+ * Whether lifecycle hooks this class's code doesn't show may read the query: inherited ones, ones in a
244
+ * subclass in the same file, or the hooks of whatever class this undecorated one is a base of. Subclasses
245
+ * in other files are not visible here.
246
+ */
247
+ function mayInheritOrBeInherited(clazz: J.ClassDeclaration, cursor: Cursor): boolean {
248
+ if (clazz.extends || clazz.modifiers.some(m => m.type === J.ModifierType.Abstract)) return true;
249
+
250
+ const classDecorator = clazz.leadingAnnotations.find(a => CLASS_DECORATORS.has(decoratorType(a) ?? ''));
251
+ if (!classDecorator) return true;
252
+ // Inputs declared in the metadata may name setters that run before `ngOnInit`.
253
+ const metadata = classDecorator.arguments?.elements[0]?.element;
254
+ if (metadata?.kind === J.Kind.NewClass && (metadata as J.NewClass).body?.statements.some(s =>
255
+ s.element.kind === JS.Kind.PropertyAssignment && propertyName(s.element as JS.PropertyAssignment) === 'inputs')) {
256
+ return true;
257
+ }
258
+
259
+ const cu = compilationUnitOf(cursor);
260
+ if (!cu) return true;
261
+ let extended = false;
262
+ walk(cu, node => {
263
+ if (isClassDeclaration(node) && extendedClassName(node) === clazz.name.simpleName) extended = true;
264
+ return !extended;
265
+ });
266
+ return extended;
267
+ }
268
+
269
+ /** The name of a property in an object literal, written `name` or `'name'`. */
270
+ function propertyName(prop: JS.PropertyAssignment): string | undefined {
271
+ const name = prop.name.element;
272
+ if (isIdentifier(name)) return name.simpleName;
273
+ return isLiteral(name) && typeof name.value === 'string' ? name.value : undefined;
274
+ }
275
+
276
+ /**
277
+ * Collects the `this.<name>` reads reachable from the given member bodies, following calls to the class's
278
+ * own methods and accessors. A read inside a nested function, or in a method only referenced and not
279
+ * called, may or may not run then, so it is ambiguous, as in Angular's own migration.
280
+ */
281
+ class ReadCollector extends JavaScriptVisitor<ExecutionContext> {
282
+ readonly sync = new Set<string>();
283
+ readonly ambiguous = new Set<string>();
284
+ thisEscapes = false;
285
+
286
+ private mode: 'sync' | 'ambiguous' = 'sync';
287
+ private readonly queues = {sync: [] as J[], ambiguous: [] as J[]};
288
+ private readonly visited = {sync: new Set<J>(), ambiguous: new Set<J>()};
289
+
290
+ constructor(private readonly methods: Map<string, J.MethodDeclaration[]>,
291
+ private readonly functions: Map<string, J>) {
292
+ super();
293
+ }
294
+
295
+ async collect(roots: J.MethodDeclaration[]): Promise<this> {
296
+ roots.forEach(m => this.enqueue(m.body!, 'sync'));
297
+ const ctx = new ExecutionContext();
298
+ for (const mode of ['sync', 'ambiguous'] as const) {
299
+ this.mode = mode;
300
+ for (let next = this.queues[mode].shift(); next; next = this.queues[mode].shift()) {
301
+ // A body queued as ambiguous may since have been walked as synchronous.
302
+ if (mode === 'ambiguous' && this.visited.sync.has(next)) continue;
303
+ await this.visit(next, ctx);
304
+ }
305
+ }
306
+ return this;
307
+ }
308
+
309
+ private enqueue(body: J, mode: 'sync' | 'ambiguous') {
310
+ if (this.visited.sync.has(body) || this.visited[mode].has(body)) return;
311
+ this.visited[mode].add(body);
312
+ this.queues[mode].push(body);
313
+ }
314
+
315
+ /** Walked as synchronous, a nested function is queued to be walked later as ambiguous. */
316
+ private defer(nested: J): J {
317
+ this.queues.ambiguous.push(nested);
318
+ return nested;
319
+ }
320
+
321
+ private touch(name: string, called: boolean) {
322
+ this[this.mode].add(name);
323
+ for (const method of this.methods.get(name) ?? []) {
324
+ this.enqueue(method.body!, called || isAccessor(method) ? this.mode : 'ambiguous');
325
+ }
326
+ const fn = this.functions.get(name);
327
+ if (fn) this.enqueue(fn, called ? this.mode : 'ambiguous');
328
+ // A function the class doesn't declare as a method, such as `this.doFocus.bind(this)` held in a property,
329
+ // can read any property.
330
+ if (called && !fn && !this.methods.has(name)) this.thisEscapes = true;
331
+ }
332
+
333
+ override async visitFieldAccess(fieldAccess: J.FieldAccess, p: ExecutionContext): Promise<J | undefined> {
334
+ if (isThis(fieldAccess.target)) this.touch(fieldAccess.name.element.simpleName, false);
335
+ return super.visitFieldAccess(fieldAccess, p);
336
+ }
337
+
338
+ override async visitMethodInvocation(method: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
339
+ if (isThis(method.select?.element)) this.touch(method.name.simpleName, true);
340
+ return super.visitMethodInvocation(method, p);
341
+ }
342
+
343
+ override async visitIdentifier(identifier: J.Identifier, p: ExecutionContext): Promise<J | undefined> {
344
+ if (isThis(identifier)) {
345
+ const parent = this.cursor.parentTree()?.value;
346
+ const asReceiver = (parent?.kind === J.Kind.FieldAccess && (parent as J.FieldAccess).target === identifier) ||
347
+ (parent?.kind === J.Kind.MethodInvocation && (parent as J.MethodInvocation).select?.element === identifier);
348
+ // `const {input} = this`, `this['input']` or `register(this)` can read any property.
349
+ if (!asReceiver) this.thisEscapes = true;
350
+ }
351
+ return super.visitIdentifier(identifier, p);
352
+ }
353
+
354
+ override async visitArrowFunction(arrowFunction: JS.ArrowFunction, p: ExecutionContext): Promise<J | undefined> {
355
+ return this.mode === 'sync' ? this.defer(arrowFunction) : super.visitArrowFunction(arrowFunction, p);
356
+ }
357
+
358
+ override async visitLambda(lambda: J.Lambda, p: ExecutionContext): Promise<J | undefined> {
359
+ return this.mode === 'sync' ? this.defer(lambda) : super.visitLambda(lambda, p);
360
+ }
361
+
362
+ override async visitMethodDeclaration(method: J.MethodDeclaration, p: ExecutionContext): Promise<J | undefined> {
363
+ return this.mode === 'sync' ? this.defer(method) : super.visitMethodDeclaration(method, p);
364
+ }
365
+
366
+ override async visitClassDeclaration(classDecl: J.ClassDeclaration, p: ExecutionContext): Promise<J | undefined> {
367
+ return this.mode === 'sync' ? this.defer(classDecl) : super.visitClassDeclaration(classDecl, p);
368
+ }
369
+ }
@@ -4,9 +4,11 @@
4
4
  * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
5
  */
6
6
 
7
- import {emptyMarkers, ExecutionContext, randomId, Recipe, TreeVisitor} from "@openrewrite/rewrite";
8
- import {detectIndent, getMemberKeyName, isMember, isObject, Json, JsonVisitor, rightPadded, space} from "@openrewrite/rewrite/json";
9
- import {appendMember, buildMember, declaresAngularCompilerOptions, isRootTsconfig, literal, memberIndent} from "./json-support";
7
+ import {ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
8
+ import {Json, jsonLiteral, JsonVisitor, setAt, valueAt} from "@openrewrite/rewrite/json";
9
+ import {declaresAngularCompilerOptions, isRootTsconfig} from "./json-support";
10
+
11
+ const PATH = ['angularCompilerOptions', 'strictTemplates'];
10
12
 
11
13
  export class AddStrictTemplatesFalse extends Recipe {
12
14
  readonly name = "org.openrewrite.angular.migration.add-strict-templates-false";
@@ -16,43 +18,10 @@ export class AddStrictTemplatesFalse extends Recipe {
16
18
 
17
19
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
18
20
  return new class extends JsonVisitor<ExecutionContext> {
19
- private baseIndent = ' ';
20
-
21
21
  protected async visitDocument(doc: Json.Document, p: ExecutionContext): Promise<Json | undefined> {
22
- this.baseIndent = detectIndent(doc);
23
-
24
- if (declaresAngularCompilerOptions(doc)) return super.visitDocument(doc, p);
25
- if (!isRootTsconfig(doc.sourcePath)) return doc;
26
-
27
- const root = doc.value;
28
- if (!isObject(root)) return doc;
29
-
30
- const indent = memberIndent(root, this.baseIndent);
31
- const newMember = buildMember('angularCompilerOptions', {
32
- kind: Json.Kind.Object,
33
- id: randomId(),
34
- prefix: space(' '),
35
- markers: emptyMarkers,
36
- members: [rightPadded(
37
- buildMember('strictTemplates', literal('false', false), '\n' + indent + this.baseIndent),
38
- space('\n' + indent))],
39
- } as Json.Object, '\n' + indent);
40
-
41
- return {...doc, value: appendMember(root, newMember, '\n')} as Json.Document;
42
- }
43
-
44
- protected async visitMember(member: Json.Member, p: ExecutionContext): Promise<Json | undefined> {
45
- if (getMemberKeyName(member) !== 'angularCompilerOptions' || !isObject(member.value)) return member;
46
-
47
- const options = member.value as Json.Object;
48
- const hasStrictTemplates = options.members.some(rp =>
49
- isMember(rp.element) && getMemberKeyName(rp.element as Json.Member) === 'strictTemplates');
50
- if (hasStrictTemplates) return member;
51
-
52
- const indent = memberIndent(options, this.baseIndent.repeat(2));
53
- const newMember = buildMember('strictTemplates', literal('false', false), '\n' + indent);
54
-
55
- return {...member, value: appendMember(options, newMember, '\n' + this.baseIndent)} as Json.Member;
22
+ if (!isRootTsconfig(doc.sourcePath) && !declaresAngularCompilerOptions(doc)) return doc;
23
+ if (valueAt(doc, PATH) !== undefined) return doc;
24
+ return setAt(doc, PATH, jsonLiteral(false), {createMissing: true});
56
25
  }
57
26
  }();
58
27
  }
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import {ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
8
- import {JavaScriptVisitor, JS, Template} from "@openrewrite/rewrite/javascript";
8
+ import {JavaScriptVisitor, isObjectLiteral, JS, Template} from "@openrewrite/rewrite/javascript";
9
9
  import {isIdentifier, J} from "@openrewrite/rewrite/java";
10
10
 
11
11
  const APP_ENGINES = ['AngularNodeAppEngine', 'AngularAppEngine'];
@@ -31,11 +31,11 @@ export class AddTrustProxyHeaders extends Recipe {
31
31
  if (args.length > 1) return n;
32
32
 
33
33
  const options = args.length === 1 ? args[0].element : undefined;
34
- if (options && options.kind !== J.Kind.NewClass) return n;
35
- if (options && declaresTrustProxyHeaders(options as J.NewClass)) return n;
34
+ if (options && !isObjectLiteral(options)) return n;
35
+ if (options && declaresTrustProxyHeaders(options)) return n;
36
36
 
37
37
  const engine = n.class.simpleName;
38
- const existing = (options as J.NewClass | undefined)?.body?.statements
38
+ const existing = options?.body?.statements
39
39
  .filter(rp => rp.element.kind !== J.Kind.Empty) ?? [];
40
40
 
41
41
  let builder = Template.builder().code(`new ${engine}({\n ${TODO_COMMENT}\n trustProxyHeaders: ['x-forwarded-host', 'x-forwarded-proto'],`);
@@ -4,7 +4,7 @@
4
4
  * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
5
  */
6
6
 
7
- import {capture, JS, TemplateOptions} from "@openrewrite/rewrite/javascript";
7
+ import {capture, isObjectLiteral, JS, TemplateOptions} from "@openrewrite/rewrite/javascript";
8
8
  import {isIdentifier, J, Type} from "@openrewrite/rewrite/java";
9
9
 
10
10
  export const OLD_MODULE = "@angular/http";
@@ -99,11 +99,8 @@ export function isOldShapeRequest(call: J.MethodInvocation): boolean {
99
99
  return first?.kind !== J.Kind.Literal || !REQUEST_METHODS.has((first as J.Literal).value as string);
100
100
  }
101
101
 
102
- /** An object literal is a `J.NewClass` with a body and no class name. */
103
102
  export function objectLiteralBody(expression: J | undefined): J.Block | undefined {
104
- if (expression?.kind !== J.Kind.NewClass) return undefined;
105
- const literal = expression as J.NewClass;
106
- return literal.class === undefined ? literal.body : undefined;
103
+ return expression !== undefined && isObjectLiteral(expression) ? expression.body : undefined;
107
104
  }
108
105
 
109
106
  export function propertyName(statement: J): string | undefined {