@openrewrite/recipes-react 0.11.0 → 0.13.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 (197) hide show
  1. package/dist/migration/change-component-prop-value.d.ts.map +1 -1
  2. package/dist/migration/change-component-prop-value.js +2 -2
  3. package/dist/migration/change-component-prop-value.js.map +1 -1
  4. package/dist/react-native/view-prop-types.d.ts.map +1 -1
  5. package/dist/react-native/view-prop-types.js +2 -2
  6. package/dist/react-native/view-prop-types.js.map +1 -1
  7. package/dist/react16/error-boundaries.d.ts.map +1 -1
  8. package/dist/react16/error-boundaries.js +2 -2
  9. package/dist/react16/error-boundaries.js.map +1 -1
  10. package/dist/react16/find-dom-node.d.ts.map +1 -1
  11. package/dist/react16/find-dom-node.js +2 -2
  12. package/dist/react16/find-dom-node.js.map +1 -1
  13. package/dist/react16/react-dom-factories.d.ts.map +1 -1
  14. package/dist/react16/react-dom-factories.js +10 -9
  15. package/dist/react16/react-dom-factories.js.map +1 -1
  16. package/dist/react16/react-prop-types.d.ts.map +1 -1
  17. package/dist/react16/react-prop-types.js +2 -2
  18. package/dist/react16/react-prop-types.js.map +1 -1
  19. package/dist/react16/react-to-react-dom.d.ts.map +1 -1
  20. package/dist/react16/react-to-react-dom.js +2 -2
  21. package/dist/react16/react-to-react-dom.js.map +1 -1
  22. package/dist/react16/replace-create-factory.d.ts.map +1 -1
  23. package/dist/react16/replace-create-factory.js +3 -3
  24. package/dist/react16/replace-create-factory.js.map +1 -1
  25. package/dist/react16/upgrade-to-react-16.d.ts.map +1 -1
  26. package/dist/react16/upgrade-to-react-16.js +2 -0
  27. package/dist/react16/upgrade-to-react-16.js.map +1 -1
  28. package/dist/react17/remove-event-persist.d.ts.map +1 -1
  29. package/dist/react17/remove-event-persist.js +2 -2
  30. package/dist/react17/remove-event-persist.js.map +1 -1
  31. package/dist/react17/rename-unsafe-lifecycles.d.ts.map +1 -1
  32. package/dist/react17/rename-unsafe-lifecycles.js +2 -2
  33. package/dist/react17/rename-unsafe-lifecycles.js.map +1 -1
  34. package/dist/react17/update-react-imports.d.ts.map +1 -1
  35. package/dist/react17/update-react-imports.js +2 -2
  36. package/dist/react17/update-react-imports.js.map +1 -1
  37. package/dist/react17/upgrade-to-react-17.d.ts.map +1 -1
  38. package/dist/react17/upgrade-to-react-17.js +2 -0
  39. package/dist/react17/upgrade-to-react-17.js.map +1 -1
  40. package/dist/react18/remove-unstable-batched-updates.d.ts.map +1 -1
  41. package/dist/react18/remove-unstable-batched-updates.js +2 -2
  42. package/dist/react18/remove-unstable-batched-updates.js.map +1 -1
  43. package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
  44. package/dist/react18/replace-reactdom-render.js +2 -2
  45. package/dist/react18/replace-reactdom-render.js.map +1 -1
  46. package/dist/react18/replace-render-callback.d.ts.map +1 -1
  47. package/dist/react18/replace-render-callback.js +2 -2
  48. package/dist/react18/replace-render-callback.js.map +1 -1
  49. package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
  50. package/dist/react18/replace-unmount-component-at-node.js +2 -2
  51. package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
  52. package/dist/react18/upgrade-to-react-18.d.ts.map +1 -1
  53. package/dist/react18/upgrade-to-react-18.js +2 -0
  54. package/dist/react18/upgrade-to-react-18.js.map +1 -1
  55. package/dist/react19/deprecated-react-types.d.ts.map +1 -1
  56. package/dist/react19/deprecated-react-types.js +2 -2
  57. package/dist/react19/deprecated-react-types.js.map +1 -1
  58. package/dist/react19/find-context-consumer.d.ts.map +1 -1
  59. package/dist/react19/find-context-consumer.js +2 -2
  60. package/dist/react19/find-context-consumer.js.map +1 -1
  61. package/dist/react19/find-deprecated-reactdom-apis.d.ts.map +1 -1
  62. package/dist/react19/find-deprecated-reactdom-apis.js +2 -2
  63. package/dist/react19/find-deprecated-reactdom-apis.js.map +1 -1
  64. package/dist/react19/find-element-ref.d.ts.map +1 -1
  65. package/dist/react19/find-element-ref.js +2 -2
  66. package/dist/react19/find-element-ref.js.map +1 -1
  67. package/dist/react19/find-legacy-context-api.d.ts.map +1 -1
  68. package/dist/react19/find-legacy-context-api.js +11 -11
  69. package/dist/react19/find-legacy-context-api.js.map +1 -1
  70. package/dist/react19/no-implicit-ref-callback-return.d.ts.map +1 -1
  71. package/dist/react19/no-implicit-ref-callback-return.js +9 -3
  72. package/dist/react19/no-implicit-ref-callback-return.js.map +1 -1
  73. package/dist/react19/remove-context-provider.d.ts.map +1 -1
  74. package/dist/react19/remove-context-provider.js +2 -2
  75. package/dist/react19/remove-context-provider.js.map +1 -1
  76. package/dist/react19/remove-forward-ref.d.ts.map +1 -1
  77. package/dist/react19/remove-forward-ref.js +2 -2
  78. package/dist/react19/remove-forward-ref.js.map +1 -1
  79. package/dist/react19/remove-prop-types.d.ts.map +1 -1
  80. package/dist/react19/remove-prop-types.js +2 -2
  81. package/dist/react19/remove-prop-types.js.map +1 -1
  82. package/dist/react19/remove-react-fc.d.ts.map +1 -1
  83. package/dist/react19/remove-react-fc.js +2 -2
  84. package/dist/react19/remove-react-fc.js.map +1 -1
  85. package/dist/react19/replace-act-import.d.ts.map +1 -1
  86. package/dist/react19/replace-act-import.js +1 -1
  87. package/dist/react19/replace-act-import.js.map +1 -1
  88. package/dist/react19/replace-default-props.d.ts.map +1 -1
  89. package/dist/react19/replace-default-props.js +2 -2
  90. package/dist/react19/replace-default-props.js.map +1 -1
  91. package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
  92. package/dist/react19/replace-react-shallow-renderer.js +2 -2
  93. package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
  94. package/dist/react19/replace-reactdom-hydrate.d.ts.map +1 -1
  95. package/dist/react19/replace-reactdom-hydrate.js +2 -2
  96. package/dist/react19/replace-reactdom-hydrate.js.map +1 -1
  97. package/dist/react19/replace-string-ref.d.ts.map +1 -1
  98. package/dist/react19/replace-string-ref.js +2 -2
  99. package/dist/react19/replace-string-ref.js.map +1 -1
  100. package/dist/react19/replace-use-form-state.d.ts.map +1 -1
  101. package/dist/react19/replace-use-form-state.js +2 -2
  102. package/dist/react19/replace-use-form-state.js.map +1 -1
  103. package/dist/react19/scoped-jsx-namespace.d.ts.map +1 -1
  104. package/dist/react19/scoped-jsx-namespace.js +8 -4
  105. package/dist/react19/scoped-jsx-namespace.js.map +1 -1
  106. package/dist/react19/use-context-hook.d.ts.map +1 -1
  107. package/dist/react19/use-context-hook.js +2 -2
  108. package/dist/react19/use-context-hook.js.map +1 -1
  109. package/dist/react19/use-ref-required-initial.d.ts.map +1 -1
  110. package/dist/react19/use-ref-required-initial.js +2 -2
  111. package/dist/react19/use-ref-required-initial.js.map +1 -1
  112. package/dist/refactoring/class-to-functional.d.ts.map +1 -1
  113. package/dist/refactoring/class-to-functional.js +2 -2
  114. package/dist/refactoring/class-to-functional.js.map +1 -1
  115. package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
  116. package/dist/refactoring/create-class-to-es6.js +261 -65
  117. package/dist/refactoring/create-class-to-es6.js.map +1 -1
  118. package/dist/refactoring/create-element-to-jsx.d.ts.map +1 -1
  119. package/dist/refactoring/create-element-to-jsx.js +2 -2
  120. package/dist/refactoring/create-element-to-jsx.js.map +1 -1
  121. package/dist/refactoring/manual-bind-to-arrow.d.ts.map +1 -1
  122. package/dist/refactoring/manual-bind-to-arrow.js +2 -2
  123. package/dist/refactoring/manual-bind-to-arrow.js.map +1 -1
  124. package/dist/refactoring/pure-render-mixin.d.ts.map +1 -1
  125. package/dist/refactoring/pure-render-mixin.js +42 -83
  126. package/dist/refactoring/pure-render-mixin.js.map +1 -1
  127. package/dist/refactoring/sort-comp.d.ts.map +1 -1
  128. package/dist/refactoring/sort-comp.js +2 -2
  129. package/dist/refactoring/sort-comp.js.map +1 -1
  130. package/dist/search/find-hook-usage.d.ts.map +1 -1
  131. package/dist/search/find-hook-usage.js +2 -2
  132. package/dist/search/find-hook-usage.js.map +1 -1
  133. package/dist/search/find-prop-usage.d.ts.map +1 -1
  134. package/dist/search/find-prop-usage.js +2 -2
  135. package/dist/search/find-prop-usage.js.map +1 -1
  136. package/dist/search/find-react-component.d.ts.map +1 -1
  137. package/dist/search/find-react-component.js +2 -2
  138. package/dist/search/find-react-component.js.map +1 -1
  139. package/dist/search/find-server-rendering-usage.d.ts.map +1 -1
  140. package/dist/search/find-server-rendering-usage.js +2 -2
  141. package/dist/search/find-server-rendering-usage.js.map +1 -1
  142. package/dist/simplify-object-pattern-property.d.ts.map +1 -1
  143. package/dist/simplify-object-pattern-property.js +2 -2
  144. package/dist/simplify-object-pattern-property.js.map +1 -1
  145. package/dist/simplify-react-imports.d.ts.map +1 -1
  146. package/dist/simplify-react-imports.js +2 -2
  147. package/dist/simplify-react-imports.js.map +1 -1
  148. package/package.json +2 -2
  149. package/src/migration/change-component-prop-value.ts +4 -4
  150. package/src/react-native/view-prop-types.ts +4 -4
  151. package/src/react16/error-boundaries.ts +6 -4
  152. package/src/react16/find-dom-node.ts +7 -4
  153. package/src/react16/react-dom-factories.ts +15 -11
  154. package/src/react16/react-prop-types.ts +6 -5
  155. package/src/react16/react-to-react-dom.ts +6 -6
  156. package/src/react16/replace-create-factory.ts +6 -14
  157. package/src/react16/upgrade-to-react-16.ts +3 -1
  158. package/src/react17/remove-event-persist.ts +5 -5
  159. package/src/react17/rename-unsafe-lifecycles.ts +6 -4
  160. package/src/react17/update-react-imports.ts +4 -4
  161. package/src/react17/upgrade-to-react-17.ts +3 -1
  162. package/src/react18/remove-unstable-batched-updates.ts +4 -4
  163. package/src/react18/replace-reactdom-render.ts +5 -4
  164. package/src/react18/replace-render-callback.ts +4 -4
  165. package/src/react18/replace-unmount-component-at-node.ts +5 -4
  166. package/src/react18/upgrade-to-react-18.ts +2 -0
  167. package/src/react19/deprecated-react-types.ts +4 -4
  168. package/src/react19/find-context-consumer.ts +5 -5
  169. package/src/react19/find-deprecated-reactdom-apis.ts +5 -5
  170. package/src/react19/find-element-ref.ts +5 -5
  171. package/src/react19/find-legacy-context-api.ts +14 -21
  172. package/src/react19/no-implicit-ref-callback-return.ts +21 -13
  173. package/src/react19/remove-context-provider.ts +6 -5
  174. package/src/react19/remove-forward-ref.ts +25 -4
  175. package/src/react19/remove-prop-types.ts +5 -5
  176. package/src/react19/remove-react-fc.ts +5 -4
  177. package/src/react19/replace-act-import.ts +3 -3
  178. package/src/react19/replace-default-props.ts +5 -5
  179. package/src/react19/replace-react-shallow-renderer.ts +5 -5
  180. package/src/react19/replace-reactdom-hydrate.ts +6 -5
  181. package/src/react19/replace-string-ref.ts +4 -4
  182. package/src/react19/replace-use-form-state.ts +6 -5
  183. package/src/react19/scoped-jsx-namespace.ts +11 -7
  184. package/src/react19/use-context-hook.ts +7 -4
  185. package/src/react19/use-ref-required-initial.ts +5 -5
  186. package/src/refactoring/class-to-functional.ts +4 -4
  187. package/src/refactoring/create-class-to-es6.ts +319 -65
  188. package/src/refactoring/create-element-to-jsx.ts +4 -4
  189. package/src/refactoring/manual-bind-to-arrow.ts +4 -4
  190. package/src/refactoring/pure-render-mixin.ts +55 -126
  191. package/src/refactoring/sort-comp.ts +4 -4
  192. package/src/search/find-hook-usage.ts +4 -4
  193. package/src/search/find-prop-usage.ts +4 -4
  194. package/src/search/find-react-component.ts +4 -4
  195. package/src/search/find-server-rendering-usage.ts +4 -4
  196. package/src/simplify-object-pattern-property.ts +4 -4
  197. package/src/simplify-react-imports.ts +4 -4
@@ -1,6 +1,6 @@
1
- import {emptyMarkers, ExecutionContext, randomId, Recipe, TreeVisitor} from "@openrewrite/rewrite";
1
+ import {emptyMarkers, ExecutionContext, randomId, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
2
  import {emptySpace, isIdentifier, J, rightPadded, Type} from "@openrewrite/rewrite/java";
3
- import {JavaScriptVisitor, JS, maybeAddImport} from "@openrewrite/rewrite/javascript";
3
+ import {JavaScriptVisitor, JS, maybeAddImport, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
4
4
 
5
5
  /** Imports the scoped namespace that replaces React's global JSX types in React 19. */
6
6
  export class ScopedJsxNamespace extends Recipe {
@@ -9,7 +9,7 @@ export class ScopedJsxNamespace extends Recipe {
9
9
  readonly description = "Imports React's JSX namespace for references to the global namespace removed in React 19.";
10
10
 
11
11
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
12
- return new class extends JavaScriptVisitor<ExecutionContext> {
12
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
13
13
  private declarationFile = false;
14
14
  private declaresJsx = false;
15
15
 
@@ -38,9 +38,13 @@ export class ScopedJsxNamespace extends Recipe {
38
38
  if (this.declarationFile) {
39
39
  // An inline import type leaves ambient modules ambient and avoids introducing
40
40
  // a top-level import into a declaration file that was previously a script.
41
- const module: J.Literal = {
42
- kind: J.Kind.Literal, id: randomId(), prefix: emptySpace, markers: emptyMarkers,
43
- value: 'react', valueSource: "'react'", type: Type.Primitive.String
41
+ const module: JS.LiteralType = {
42
+ kind: JS.Kind.LiteralType, id: randomId(), prefix: emptySpace, markers: emptyMarkers,
43
+ literal: {
44
+ kind: J.Kind.Literal, id: randomId(), prefix: emptySpace, markers: emptyMarkers,
45
+ value: 'react', valueSource: "'react'", type: Type.Primitive.String
46
+ } as J.Literal,
47
+ type: Type.Primitive.String
44
48
  };
45
49
  return {
46
50
  kind: JS.Kind.ImportType, id: randomId(), prefix: fa.prefix, markers: fa.markers,
@@ -61,6 +65,6 @@ export class ScopedJsxNamespace extends Recipe {
61
65
  ...fa, target: {...fa.target, simpleName: local}
62
66
  } as J.FieldAccess;
63
67
  }
64
- }();
68
+ }());
65
69
  }
66
70
  }
@@ -1,11 +1,13 @@
1
- import {ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, not, and} from "@openrewrite/rewrite";
2
2
  import {
3
3
  JavaScriptVisitor,
4
4
  maybeRemoveImport,
5
5
  capture,
6
6
  pattern,
7
7
  rewrite,
8
- template
8
+ template,
9
+ isVendoredOrBundled,
10
+ usesMethod
9
11
  } from "@openrewrite/rewrite/javascript";
10
12
  import {Expression, J} from "@openrewrite/rewrite/java";
11
13
 
@@ -51,7 +53,8 @@ export class UseContextHook extends Recipe {
51
53
  })
52
54
  }));
53
55
 
54
- return new class extends JavaScriptVisitor<ExecutionContext> {
56
+ // Without type attribution the visitor cannot match anyway, so gating on the type is not an extra restriction.
57
+ return check(and(not(isVendoredOrBundled()), usesMethod("React useContext(..)")), new class extends JavaScriptVisitor<ExecutionContext> {
55
58
  override async visitMethodInvocation(method: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
56
59
  let m = await super.visitMethodInvocation(method, p) as J.MethodInvocation;
57
60
 
@@ -63,6 +66,6 @@ export class UseContextHook extends Recipe {
63
66
 
64
67
  return m;
65
68
  }
66
- }();
69
+ }());
67
70
  }
68
71
  }
@@ -1,5 +1,5 @@
1
- import {ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
- import {JavaScriptVisitor} from "@openrewrite/rewrite/javascript";
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
+ import {JavaScriptVisitor, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
3
3
  import {isIdentifier, J, Type} from "@openrewrite/rewrite/java";
4
4
  import {create} from "mutative";
5
5
 
@@ -19,7 +19,7 @@ import {create} from "mutative";
19
19
  * const ref = useRef(undefined);
20
20
  * ```
21
21
  *
22
- * @see https://react.dev/blog/2024/04/25/react-19-upgrade-guide#different-types
22
+ * @see https://react.dev/blog/2024/04/25/react-19-upgrade-guide#useref-requires-argument
23
23
  */
24
24
  export class UseRefRequiredInitial extends Recipe {
25
25
  readonly name = "org.openrewrite.react.19.use-ref-required-initial";
@@ -27,7 +27,7 @@ export class UseRefRequiredInitial extends Recipe {
27
27
  readonly description: string = "Adds `undefined` as initial argument to `useRef()` calls with no arguments. Required by `@types/react` 19.";
28
28
 
29
29
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
30
- return new class extends JavaScriptVisitor<ExecutionContext> {
30
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
31
31
  override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
32
32
  let m = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
33
33
 
@@ -71,6 +71,6 @@ export class UseRefRequiredInitial extends Recipe {
71
71
 
72
72
  return m;
73
73
  }
74
- }();
74
+ }());
75
75
  }
76
76
  }
@@ -1,5 +1,5 @@
1
- import {ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
- import {capture, JavaScriptVisitor, pattern, raw, rewrite, template} from "@openrewrite/rewrite/javascript";
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
+ import {capture, JavaScriptVisitor, pattern, raw, rewrite, template, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
3
3
  import {J} from "@openrewrite/rewrite/java";
4
4
 
5
5
  const LIFECYCLE_METHODS = new Set([
@@ -57,7 +57,7 @@ export class ClassToFunctional extends Recipe {
57
57
  after: template`props`
58
58
  }));
59
59
 
60
- return new class extends JavaScriptVisitor<ExecutionContext> {
60
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
61
61
  override async visitClassDeclaration(classDecl: J.ClassDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
62
62
  let cd = await super.visitClassDeclaration(classDecl, ctx) as J.ClassDeclaration;
63
63
 
@@ -224,6 +224,6 @@ export class ClassToFunctional extends Recipe {
224
224
  }).join('\n');
225
225
  return adjusted !== ws ? {...space, whitespace: adjusted} : space;
226
226
  }
227
- }();
227
+ }());
228
228
  }
229
229
  }
@@ -1,6 +1,6 @@
1
- import {ExecutionContext, printer, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
- import {JavaScriptVisitor, JS, raw, template} from "@openrewrite/rewrite/javascript";
3
- import {J} from "@openrewrite/rewrite/java";
1
+ import {Cursor, emptyMarkers, ExecutionContext, findMarker, Marker, printer, randomId, Recipe, Tree, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
+ import {compilationUnitOf, JavaScriptVisitor, JS, maybeBind, maybeUnbind, moduleBindings, raw, template, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
3
+ import {Comment, J, TextComment} from "@openrewrite/rewrite/java";
4
4
 
5
5
  const LIFECYCLE_METHODS = new Set([
6
6
  'render',
@@ -13,6 +13,12 @@ const LIFECYCLE_METHODS = new Set([
13
13
  'getDerivedStateFromProps', 'getDerivedStateFromError',
14
14
  ]);
15
15
 
16
+ /** The properties of a spec that become static fields of the class. */
17
+ const STATIC_PROPERTIES = new Set(['childContextTypes', 'contextTypes', 'displayName', 'propTypes']);
18
+
19
+ /** The methods a `createClass` component has and a `React.Component` doesn't, as react-codemod lists them. */
20
+ const CREATE_CLASS_METHODS = new Set(['getDOMNode', 'isMounted', 'replaceProps', 'replaceState', 'setProps']);
21
+
16
22
  const SEMICOLON_KIND = "org.openrewrite.java.marker.Semicolon";
17
23
 
18
24
  /**
@@ -22,9 +28,13 @@ const SEMICOLON_KIND = "org.openrewrite.java.marker.Semicolon";
22
28
  * - `getInitialState()` → class property `state = {...}`
23
29
  * - `getDefaultProps()` → `static defaultProps = {...}`
24
30
  * - Static properties (propTypes, contextTypes) → class statics
31
+ * - `displayName` → `static displayName`, unless it is the class's name
25
32
  * - Auto-binding of methods → arrow function class fields
26
33
  * - Lifecycle methods and render → regular class methods
27
- * - Skips conversion if mixins are present
34
+ * - A `createReactClass()` component extends the `Component` of the `react` the file binds, or binds one, and the
35
+ * `create-react-class` import goes where nothing else uses it
36
+ * - Skips conversion if mixins are present, or a member it has no conversion for, such as
37
+ * `render: function() {}` or `statics`
28
38
  *
29
39
  * @see https://github.com/reactjs/react-codemod#class
30
40
  */
@@ -34,7 +44,7 @@ export class CreateClassToES6 extends Recipe {
34
44
  readonly description: string = "Converts `React.createClass()` and `createReactClass()` calls to ES6 class syntax.";
35
45
 
36
46
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
37
- return new class extends JavaScriptVisitor<ExecutionContext> {
47
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
38
48
  private convertedClassIds = new Set<string>();
39
49
 
40
50
  private stripSemicolonFromConverted(statements: any[]): { modified: boolean, statements: any[] } {
@@ -82,6 +92,8 @@ export class CreateClassToES6 extends Recipe {
82
92
  let vd = await super.visitVariableDeclarations(varDecl, ctx) as J.VariableDeclarations;
83
93
 
84
94
  if (!vd.variables || vd.variables.length !== 1) return vd;
95
+ // One of several declarators, as in `const A = React.createClass({...}), b = 1`, is no statement a class can replace
96
+ if (this.cursor.parentTree()?.value.kind === JS.Kind.ScopedVariableDeclarations) return vd;
85
97
 
86
98
  const namedVar = vd.variables[0].element as J.VariableDeclarations.NamedVariable;
87
99
  if (!namedVar.initializer) return vd;
@@ -106,22 +118,40 @@ export class CreateClassToES6 extends Recipe {
106
118
 
107
119
  // Check for mixins — skip conversion if present
108
120
  if (this.hasMixins(specObj.body)) return vd;
121
+ // A class has no `this.isMounted()` and the like to call
122
+ if (await mentions(specObj.body, CREATE_CLASS_METHODS)) return vd;
109
123
 
110
124
  // Build transformed class members
111
- const memberIndent = this.getMemberIndent(specObj.body);
112
- const members = await this.transformMembers(specObj.body, memberIndent, ctx);
125
+ const members = await this.transformMembers(componentName, vd, specObj.body, ctx);
126
+ if (!members) return vd;
113
127
 
114
128
  // Construct class declaration using template
115
- const classDecl = await template`class ${raw(componentName)} extends React.Component {}`.apply(vd, this.cursor);
129
+ const component = this.componentClass(methodInv);
130
+ if (!component) return vd;
131
+ const classDecl = this.isExported(vd) ?
132
+ await template`export class ${raw(componentName)} extends ${raw(component)} {}`.apply(vd, this.cursor) :
133
+ await template`class ${raw(componentName)} extends ${raw(component)} {}`.apply(vd, this.cursor);
116
134
  if (!classDecl) return vd;
135
+ if (!methodInv.select) {
136
+ maybeUnbind(this, 'create-react-class');
137
+ }
117
138
 
118
139
  // Splice transformed members into class body
119
140
  const cd = classDecl as J.ClassDeclaration;
141
+ const end = specObj.body.end;
142
+ const last = members[members.length - 1];
120
143
  const result = {
121
144
  ...cd,
122
145
  body: {
123
146
  ...cd.body,
124
- statements: members
147
+ statements: members,
148
+ // The comments after the spec's last member stay ahead of the class's closing brace, on a line of
149
+ // their own where that member ends with a line comment
150
+ end: end.comments.length === 0 ? cd.body.end : {
151
+ ...end,
152
+ whitespace: last && /\n[ \t]*$/.test(spaceText(last.after)) ? '' : end.whitespace,
153
+ comments: end.comments.map((c, i) => i < end.comments.length - 1 ? c : {...c, suffix: cd.body.end.whitespace})
154
+ }
125
155
  }
126
156
  } as any as J.ClassDeclaration;
127
157
 
@@ -143,6 +173,28 @@ export class CreateClassToES6 extends Recipe {
143
173
  return false;
144
174
  }
145
175
 
176
+ /**
177
+ * What the class extends: `React.Component` for `React.createClass`, and for `createReactClass` the `Component`
178
+ * of the `react` the file binds, or of one it binds here, or `undefined` where it can't bind one.
179
+ */
180
+ private componentClass(createClass: J.MethodInvocation): string | undefined {
181
+ const bindings = moduleBindings(this);
182
+ // A script that calls `createReactClass` has it and React as globals, as create-react-class's UMD build does
183
+ if (createClass.select || bindings.moduleSystem === 'none') return 'React.Component';
184
+ const react = bindings.bindingOf('react');
185
+ // A class can't extend what an `import type` binds
186
+ if (react !== undefined && !importsTypeOnly(compilationUnitOf(this), react)) return `${react}.Component`;
187
+ const component = maybeBind(this, {module: 'react', member: 'Component', onlyIfReferenced: false});
188
+ if (component !== undefined) return component;
189
+ // An AMD block binds a whole module, not one of its members
190
+ const module = maybeBind(this, {module: 'react', onlyIfReferenced: false});
191
+ return module === undefined ? undefined : `${module}.Component`;
192
+ }
193
+
194
+ private isExported(vd: J.VariableDeclarations): boolean {
195
+ return vd.modifiers.some(m => m.keyword === 'export');
196
+ }
197
+
146
198
  private hasMixins(body: J.Block): boolean {
147
199
  for (const stmt of body.statements) {
148
200
  const s = stmt.element;
@@ -162,63 +214,69 @@ export class CreateClassToES6 extends Recipe {
162
214
  return undefined;
163
215
  }
164
216
 
165
- private getMemberIndent(body: J.Block): any {
166
- // Get the prefix of the first member to use as indentation reference
167
- for (const stmt of body.statements) {
168
- if (stmt.element?.prefix) return stmt.element.prefix;
169
- }
170
- return undefined;
171
- }
172
-
173
- private async transformMembers(body: J.Block, memberIndent: any, ctx: ExecutionContext): Promise<any[]> {
217
+ /** The members of the class, or `undefined` when the spec holds one that has no conversion here. */
218
+ private async transformMembers(componentName: string, declaration: J.VariableDeclarations, body: J.Block, ctx: ExecutionContext): Promise<any[] | undefined> {
174
219
  const members: any[] = [];
175
220
 
176
- for (const stmt of body.statements) {
221
+ for (const [i, stmt] of body.statements.entries()) {
177
222
  const s = stmt.element;
223
+ // A converted member keeps the comments and indentation it had in the spec
224
+ const prefix = s.prefix;
225
+ // Whether a line comment the converted member ends with can end without a line break of its own
226
+ const lineFollows = i === body.statements.length - 1 ?
227
+ body.end.comments.length === 0 || body.end.whitespace.includes('\n') :
228
+ stmt.after.whitespace.includes('\n') || body.statements[i + 1].element.prefix.whitespace.includes('\n');
178
229
 
179
230
  if (s.kind === J.Kind.MethodDeclaration) {
180
231
  const method = s as J.MethodDeclaration;
181
232
  const name = method.name.simpleName;
182
233
 
183
234
  if (name === 'getInitialState') {
184
- const stateInit = await this.convertGetInitialState(method, memberIndent, ctx);
185
- if (stateInit) members.push({...stmt, element: stateInit});
235
+ const stateInit = await this.convertGetInitialState(stmt, method, lineFollows, ctx);
236
+ if (!stateInit) return undefined;
237
+ members.push(stateInit);
186
238
  } else if (name === 'getDefaultProps') {
187
- const defaultProps = await this.convertGetDefaultProps(method, memberIndent, ctx);
188
- if (defaultProps) members.push({...stmt, element: defaultProps});
239
+ const defaultProps = await this.convertGetDefaultProps(stmt, method, declaration, lineFollows);
240
+ if (!defaultProps) return undefined;
241
+ members.push(defaultProps);
189
242
  } else if (LIFECYCLE_METHODS.has(name)) {
190
243
  members.push(stmt);
191
244
  } else {
192
- const arrowProp = await this.convertToArrowProperty(method, memberIndent, ctx);
193
- if (arrowProp) {
194
- members.push({...stmt, element: arrowProp});
195
- } else {
196
- members.push(stmt);
197
- }
245
+ const arrowProp = await this.convertToArrowProperty(method, prefix, ctx);
246
+ if (!arrowProp) return undefined;
247
+ members.push({...stmt, element: arrowProp});
198
248
  }
199
249
  } else if (s.kind === JS.Kind.PropertyAssignment) {
200
250
  const prop = s as JS.PropertyAssignment;
201
251
  const keyName = this.getPropertyKeyName(prop);
202
252
 
203
- if (keyName === 'propTypes' || keyName === 'contextTypes' || keyName === 'childContextTypes') {
204
- const staticProp = await this.convertToStaticProperty(prop, keyName, memberIndent, ctx);
205
- if (staticProp) {
206
- members.push({...stmt, element: staticProp});
207
- } else {
208
- members.push(stmt);
209
- }
210
- } else if (keyName === 'displayName' || keyName === 'statics' || keyName === 'mixins') {
211
- // Skip displayName (inferred from class name), statics, mixins
253
+ if (keyName !== undefined && STATIC_PROPERTIES.has(keyName)) {
254
+ const staticProp = await this.convertToStaticProperty(stmt, prop, keyName, declaration, lineFollows);
255
+ if (!staticProp) return undefined;
256
+ members.push(staticProp);
212
257
  } else {
213
- members.push(stmt);
258
+ // `render: function() {}`, `statics` and other properties don't belong in a class body as they are
259
+ return undefined;
214
260
  }
261
+ } else {
262
+ return undefined;
215
263
  }
216
264
  }
217
265
 
218
- return members;
266
+ return members.map((member, i) => {
267
+ // A class body has no commas, so the spec's trailing comma goes
268
+ const markers = member.markers.markers.filter((m: Marker) => m.kind !== J.Markers.TrailingComma);
269
+ // and a field ends with a semicolon where the member after it starts on the same line
270
+ const semicolon = member.element.kind === J.Kind.VariableDeclarations && i < members.length - 1 &&
271
+ !(spaceText(member.after) + spaceText(members[i + 1].element.prefix)).includes('\n');
272
+ return !semicolon && markers.length === member.markers.markers.length ? member : {
273
+ ...member,
274
+ markers: {...member.markers, markers: semicolon ? [...markers, {kind: SEMICOLON_KIND, id: randomId()}] : markers}
275
+ };
276
+ });
219
277
  }
220
278
 
221
- private async convertGetInitialState(method: J.MethodDeclaration, indent: any, ctx: ExecutionContext): Promise<J | undefined> {
279
+ private async convertGetInitialState(stmt: J.RightPadded<J>, method: J.MethodDeclaration, lineFollows: boolean, ctx: ExecutionContext): Promise<J.RightPadded<J> | undefined> {
222
280
  if (!method.body) return undefined;
223
281
  const stmts = method.body.statements;
224
282
  if (stmts.length !== 1) return undefined;
@@ -230,13 +288,10 @@ export class CreateClassToES6 extends Recipe {
230
288
  if (!returnStmt.expression) return undefined;
231
289
 
232
290
  const result = await template`state = ${returnStmt.expression}`.apply(method, this.cursor);
233
- if (result && indent) {
234
- return {...(result as any), prefix: indent};
235
- }
236
- return result;
291
+ return result && inPlaceOf(stmt, classField(result), returnStmt.expression, lineFollows);
237
292
  }
238
293
 
239
- private async convertGetDefaultProps(method: J.MethodDeclaration, indent: any, ctx: ExecutionContext): Promise<J | undefined> {
294
+ private async convertGetDefaultProps(stmt: J.RightPadded<J>, method: J.MethodDeclaration, declaration: J.VariableDeclarations, lineFollows: boolean): Promise<J.RightPadded<J> | undefined> {
240
295
  if (!method.body) return undefined;
241
296
  const stmts = method.body.statements;
242
297
  if (stmts.length !== 1) return undefined;
@@ -247,15 +302,17 @@ export class CreateClassToES6 extends Recipe {
247
302
  const returnStmt = firstStmt as J.Return;
248
303
  if (!returnStmt.expression) return undefined;
249
304
 
250
- const result = await template`static defaultProps = ${returnStmt.expression}`.apply(method, this.cursor);
251
- if (result && indent) {
252
- return {...(result as any), prefix: indent};
253
- }
254
- return result;
305
+ return this.staticField('defaultProps', returnStmt.expression, stmt, declaration, lineFollows);
255
306
  }
256
307
 
257
- private async convertToArrowProperty(method: J.MethodDeclaration, indent: any, ctx: ExecutionContext): Promise<J | undefined> {
308
+ private async convertToArrowProperty(method: J.MethodDeclaration, prefix: any, ctx: ExecutionContext): Promise<J | undefined> {
258
309
  if (!method.body) return undefined;
310
+ // An arrow function can't be a generator or an accessor, and this one has no place for type parameters or a return type
311
+ if (findMarker(method, JS.Markers.Generator) || method.typeParameters || method.returnTypeExpression) return undefined;
312
+ const isAsync = method.modifiers.some(m => m.keyword === 'async');
313
+ if (method.modifiers.length !== (isAsync ? 1 : 0)) return undefined;
314
+ // Nor can it declare `this`, and a class field can't read `arguments`
315
+ if (declaresThis(method) || await mentions(method.body, new Set(['arguments']))) return undefined;
259
316
 
260
317
  const name = method.name.simpleName;
261
318
 
@@ -269,12 +326,14 @@ export class CreateClassToES6 extends Recipe {
269
326
  }
270
327
 
271
328
  // Create stub with empty body, then splice in original body to preserve whitespace
272
- const stub = await template`${raw(name)} = (${raw(paramsSource)}) => {}`.apply(method, this.cursor);
329
+ const stub = isAsync ?
330
+ await template`${raw(name)} = async (${raw(paramsSource)}) => {}`.apply(method, this.cursor) :
331
+ await template`${raw(name)} = (${raw(paramsSource)}) => {}`.apply(method, this.cursor);
273
332
  if (!stub) return undefined;
274
333
 
275
334
  // Navigate into the J.Assignment -> JS.ArrowFunction -> J.Lambda to replace the empty body
276
335
  const s = stub as any;
277
- const result = {
336
+ const result = classField({
278
337
  ...s,
279
338
  assignment: {
280
339
  ...s.assignment,
@@ -286,24 +345,219 @@ export class CreateClassToES6 extends Recipe {
286
345
  }
287
346
  }
288
347
  }
289
- };
290
- if (result && indent) {
291
- return {...(result as any), prefix: indent};
348
+ });
349
+ if (result && prefix) {
350
+ return {...(result as any), prefix};
292
351
  }
293
352
  return result;
294
353
  }
295
354
 
296
355
 
297
356
 
298
- private async convertToStaticProperty(prop: JS.PropertyAssignment, name: string, indent: any, ctx: ExecutionContext): Promise<J | undefined> {
299
- if (!prop.initializer) return undefined;
357
+ private async convertToStaticProperty(stmt: J.RightPadded<J>, prop: JS.PropertyAssignment, name: string, declaration: J.VariableDeclarations, lineFollows: boolean): Promise<J.RightPadded<J> | undefined> {
358
+ // A shorthand `propTypes` stands for `propTypes: propTypes`
359
+ return this.staticField(name, prop.initializer ?? prop.name.element, stmt, declaration, lineFollows);
360
+ }
300
361
 
301
- const result = await template`static ${raw(name)} = ${prop.initializer}`.apply(prop, this.cursor);
302
- if (result && indent) {
303
- return {...(result as any), prefix: indent};
304
- }
305
- return result;
362
+ /**
363
+ * The field `static name = value` that takes the place of the spec's `member`, as the parser makes it, which a
364
+ * template parses only inside a class, so it takes the field from a class laid out where the converted class
365
+ * replaces `declaration`.
366
+ */
367
+ private async staticField(name: string, value: J, member: J.RightPadded<J>, declaration: J.VariableDeclarations, lineFollows: boolean): Promise<J.RightPadded<J> | undefined> {
368
+ const cls = await template`class C {
369
+ static ${raw(name)} = ${value}
370
+ }`.apply(declaration, this.cursor);
371
+ const field = cls?.kind === J.Kind.ClassDeclaration ? (cls as J.ClassDeclaration).body.statements[0]?.element : undefined;
372
+ return field && inPlaceOf(member, field, value, lineFollows);
306
373
  }
307
- }();
374
+ }());
308
375
  }
309
376
  }
377
+
378
+ /** A class field as the parser makes it, a declaration, from the `name = value` assignment a template makes of it. */
379
+ function classField(tree: J): J {
380
+ if (tree.kind !== J.Kind.Assignment) return tree;
381
+ const assignment = tree as J.Assignment;
382
+ const emptySpace = {kind: 'org.openrewrite.java.tree.Space' as const, whitespace: '', comments: []};
383
+ return {
384
+ kind: J.Kind.VariableDeclarations,
385
+ id: assignment.id,
386
+ prefix: assignment.prefix,
387
+ markers: assignment.markers,
388
+ leadingAnnotations: [],
389
+ modifiers: [],
390
+ variables: [{
391
+ kind: J.Kind.RightPadded,
392
+ element: {
393
+ kind: J.Kind.NamedVariable,
394
+ id: randomId(),
395
+ prefix: emptySpace,
396
+ markers: emptyMarkers,
397
+ name: assignment.variable,
398
+ dimensionsAfterName: [],
399
+ initializer: assignment.assignment,
400
+ },
401
+ after: emptySpace,
402
+ markers: emptyMarkers,
403
+ }],
404
+ } as any as J.VariableDeclarations;
405
+ }
406
+
407
+ /**
408
+ * The `field` a template made of `value` in the place of the spec's `member`: with the member's prefix, with the value
409
+ * laid out as the spec has it, moved with the line it starts on to the line the member starts on, and with the comments
410
+ * the member holds around the value before and after it.
411
+ */
412
+ async function inPlaceOf(member: J.RightPadded<J>, field: J, value: J, lineFollows: boolean): Promise<J.RightPadded<J>> {
413
+ const prefix = member.element.prefix;
414
+ const variable = field.kind === J.Kind.VariableDeclarations ? (field as J.VariableDeclarations).variables[0] : undefined;
415
+ const initializer = variable?.element.initializer;
416
+ const around = await surroundings(member.element, value);
417
+ if (!variable || !initializer || !around) {
418
+ return {...member, element: {...field, prefix}};
419
+ }
420
+ const from = around.line;
421
+ const to = indentation(prefix);
422
+ const shift = (text: string) => from === undefined || to === undefined ? text : shiftLines(text, from, to);
423
+ const lineStart = to === undefined ? undefined : (/\r\n/.test(prefix.whitespace) ? '\r\n' : '\n') + to;
424
+ // A value the template put in parentheses, or one on a line whose indentation isn't known, keeps the template's layout
425
+ const laidOut = initializer.element.id !== value.id || (from === undefined) !== (to === undefined) ? initializer.element : {
426
+ ...(from === undefined || to === undefined ? value : await reindent(value, from, to)),
427
+ prefix: {...initializer.element.prefix, comments: value.prefix.comments}
428
+ };
429
+ // The comments before the value go on lines of their own above the field
430
+ const before = around.before.flatMap(space => space.comments)
431
+ .map(c => ({...shiftComment(c, shift), suffix: lineStart ?? shift(c.suffix)}));
432
+ // and those after it follow the field, ahead of what the member had before the comma that followed it
433
+ const after = around.after.flatMap((space, i) => space.comments.map((c, j) => {
434
+ const next = j < space.comments.length - 1 ? '' : around.after[i + 1]?.whitespace;
435
+ // The last one ends the line where a line comment would take in what follows
436
+ const suffix = next !== undefined ? shift(c.suffix + next) :
437
+ ((c as TextComment).multiline || lineFollows ? '' : lineStart ?? '\n') + member.after.whitespace;
438
+ return {...shiftComment(c, shift), suffix};
439
+ }));
440
+ return {
441
+ ...member,
442
+ element: {
443
+ ...field,
444
+ prefix: {...prefix, comments: [...prefix.comments, ...before]},
445
+ variables: [{...variable, element: {...variable.element, initializer: {...initializer, element: laidOut}}}]
446
+ } as J.VariableDeclarations,
447
+ after: after.length === 0 ? member.after :
448
+ {...member.after, whitespace: shift(around.after[0].whitespace), comments: [...after, ...member.after.comments]}
449
+ };
450
+ }
451
+
452
+ /** What `member` holds besides `value` and its own prefix. */
453
+ interface Surroundings {
454
+ /** The indentation of the line `value` starts on, unless `member` starts no line before it. */
455
+ line?: string
456
+ /** The whitespace with comments in it before `value`. */
457
+ before: J.Space[]
458
+ /** The whitespace with comments in it after `value`. */
459
+ after: J.Space[]
460
+ }
461
+
462
+ /** What `member` holds besides `value` and its own prefix, or `undefined` when `value` isn't in it. */
463
+ async function surroundings(member: J, value: J): Promise<Surroundings | undefined> {
464
+ const around: Surroundings = {before: [], after: []};
465
+ let found = false;
466
+ await new class extends JavaScriptVisitor<void> {
467
+ override async visit<R extends J>(tree: Tree, p: void, parent?: Cursor): Promise<R | undefined> {
468
+ if (tree !== value) {
469
+ return super.visit<R>(tree, p, parent);
470
+ }
471
+ around.line = indentation(value.prefix) ?? around.line;
472
+ found = true;
473
+ return tree as R;
474
+ }
475
+
476
+ override async visitSpace(space: J.Space, p: void): Promise<J.Space> {
477
+ if (!found) {
478
+ around.line = indentation(space) ?? around.line;
479
+ }
480
+ if (space !== member.prefix && space.comments.length > 0) {
481
+ (found ? around.after : around.before).push(space);
482
+ }
483
+ return space;
484
+ }
485
+ }().visit(member, undefined);
486
+ return found ? around : undefined;
487
+ }
488
+
489
+ /** The indentation of the last line `space` starts, or `undefined` when it holds no line break. */
490
+ function indentation(space: J.Space): string | undefined {
491
+ const text = spaceText(space);
492
+ const lineBreak = text.lastIndexOf('\n');
493
+ return lineBreak < 0 ? undefined : /^[ \t]*/.exec(text.substring(lineBreak + 1))![0];
494
+ }
495
+
496
+ /** The text the whitespace and comments of `space` print. */
497
+ function spaceText(space: J.Space): string {
498
+ return space.whitespace + space.comments.map(c => {
499
+ const comment = c as TextComment;
500
+ return (comment.multiline ? `/*${comment.text}*/` : `//${comment.text}`) + c.suffix;
501
+ }).join('');
502
+ }
503
+
504
+ /** The tree with each line it spans that is indented by `from` indented by `to` instead. */
505
+ async function reindent<T extends J>(tree: T, from: string, to: string): Promise<T> {
506
+ if (from === to) return tree;
507
+ const shift = (text: string) => shiftLines(text, from, to);
508
+ const shiftSpace = (space: J.Space): J.Space => ({
509
+ ...space,
510
+ whitespace: shift(space.whitespace),
511
+ comments: space.comments.map(c => ({...shiftComment(c, shift), suffix: shift(c.suffix)}))
512
+ });
513
+ return await new class extends JavaScriptVisitor<void> {
514
+ override async visitSpace(space: J.Space, p: void): Promise<J.Space> {
515
+ return shiftSpace(space);
516
+ }
517
+
518
+ // A trailing comma keeps the whitespace after it
519
+ protected override async visitMarker<M extends Marker>(marker: M, p: void): Promise<M> {
520
+ const suffix = (marker as any).suffix;
521
+ return suffix?.kind === J.Kind.Space ? {...marker, suffix: shiftSpace(suffix)} : marker;
522
+ }
523
+ }().visit(tree, undefined) as T;
524
+ }
525
+
526
+ /** The text with each line after its first that is indented by `from` indented by `to` instead. */
527
+ function shiftLines(text: string, from: string, to: string): string {
528
+ return text.split('\n').map((line, i) => i > 0 && line.startsWith(from) ? to + line.substring(from.length) : line).join('\n');
529
+ }
530
+
531
+ /** The comment with `shift` applied to the lines its text spans, as only a block comment's can. */
532
+ function shiftComment(comment: Comment, shift: (text: string) => string): Comment {
533
+ return (comment as TextComment).multiline ? {...comment, text: shift((comment as TextComment).text)} as TextComment : comment;
534
+ }
535
+
536
+ /** Whether the file binds `name` with an `import type`, as its default or namespace import. */
537
+ function importsTypeOnly(cu: JS.CompilationUnit | undefined, name: string): boolean {
538
+ return cu?.statements.some(({element}) => {
539
+ const clause = element.kind === JS.Kind.Import ? (element as JS.Import).importClause : undefined;
540
+ const namespace = clause?.namedBindings?.kind === JS.Kind.Alias ? (clause.namedBindings as JS.Alias).alias : undefined;
541
+ return clause?.typeOnly === true && [clause.name?.element, namespace]
542
+ .some(id => id?.kind === J.Kind.Identifier && (id as J.Identifier).simpleName === name);
543
+ }) ?? false;
544
+ }
545
+
546
+ /** Whether the method declares the TypeScript parameter `this`. */
547
+ function declaresThis(method: J.MethodDeclaration): boolean {
548
+ const first = method.parameters.elements[0]?.element;
549
+ return first?.kind === J.Kind.VariableDeclarations &&
550
+ ((first as J.VariableDeclarations).variables[0]?.element.name as J.Identifier | undefined)?.simpleName === 'this';
551
+ }
552
+
553
+ /** Whether an identifier with one of the names appears anywhere in the tree. */
554
+ async function mentions(tree: J, names: Set<string>): Promise<boolean> {
555
+ let found = false;
556
+ await new class extends JavaScriptVisitor<void> {
557
+ protected override async visitIdentifier(identifier: J.Identifier, p: void): Promise<J | undefined> {
558
+ found = found || names.has(identifier.simpleName);
559
+ return identifier;
560
+ }
561
+ }().visit(tree, undefined);
562
+ return found;
563
+ }