@openrewrite/recipes-react 0.14.0 → 0.16.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 (238) hide show
  1. package/dist/index.d.ts +12 -4
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +70 -17
  4. package/dist/index.js.map +1 -1
  5. package/dist/migration/cra-to-vite/add-vite-config.d.ts +9 -0
  6. package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -0
  7. package/dist/migration/cra-to-vite/add-vite-config.js +49 -0
  8. package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -0
  9. package/dist/migration/cra-to-vite/cra-blockers-table.d.ts +10 -0
  10. package/dist/migration/cra-to-vite/cra-blockers-table.d.ts.map +1 -0
  11. package/dist/migration/cra-to-vite/cra-blockers-table.js +31 -0
  12. package/dist/migration/cra-to-vite/cra-blockers-table.js.map +1 -0
  13. package/dist/migration/cra-to-vite/cra-to-vite.d.ts +14 -0
  14. package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -0
  15. package/dist/migration/cra-to-vite/cra-to-vite.js +73 -0
  16. package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -0
  17. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts +14 -0
  18. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -0
  19. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +177 -0
  20. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -0
  21. package/dist/migration/cra-to-vite/find-cra-env-file-blockers.d.ts +10 -0
  22. package/dist/migration/cra-to-vite/find-cra-env-file-blockers.d.ts.map +1 -0
  23. package/dist/migration/cra-to-vite/find-cra-env-file-blockers.js +67 -0
  24. package/dist/migration/cra-to-vite/find-cra-env-file-blockers.js.map +1 -0
  25. package/dist/migration/cra-to-vite/find-cra-source-blockers.d.ts +10 -0
  26. package/dist/migration/cra-to-vite/find-cra-source-blockers.d.ts.map +1 -0
  27. package/dist/migration/cra-to-vite/find-cra-source-blockers.js +168 -0
  28. package/dist/migration/cra-to-vite/find-cra-source-blockers.js.map +1 -0
  29. package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.d.ts +8 -0
  30. package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.d.ts.map +1 -0
  31. package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.js +31 -0
  32. package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.js.map +1 -0
  33. package/dist/migration/cra-to-vite/index.d.ts +16 -0
  34. package/dist/migration/cra-to-vite/index.d.ts.map +1 -0
  35. package/dist/migration/cra-to-vite/index.js +35 -0
  36. package/dist/migration/cra-to-vite/index.js.map +1 -0
  37. package/dist/migration/cra-to-vite/move-public-index-html.d.ts +11 -0
  38. package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -0
  39. package/dist/migration/cra-to-vite/move-public-index-html.js +124 -0
  40. package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -0
  41. package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts +9 -0
  42. package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -0
  43. package/dist/migration/cra-to-vite/rename-process-env-react-app.js +92 -0
  44. package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -0
  45. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.d.ts +9 -0
  46. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.d.ts.map +1 -0
  47. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +65 -0
  48. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -0
  49. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +14 -0
  50. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -0
  51. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +78 -0
  52. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -0
  53. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +21 -0
  54. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -0
  55. package/dist/migration/cra-to-vite/scan-cra-projects.js +87 -0
  56. package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -0
  57. package/dist/migration/cra-to-vite/shared.d.ts +24 -0
  58. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -0
  59. package/dist/migration/cra-to-vite/shared.js +105 -0
  60. package/dist/migration/cra-to-vite/shared.js.map +1 -0
  61. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts +9 -0
  62. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -0
  63. package/dist/migration/cra-to-vite/update-react-app-env-types.js +47 -0
  64. package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -0
  65. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +9 -0
  66. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -0
  67. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +62 -0
  68. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -0
  69. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts +10 -0
  70. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts.map +1 -0
  71. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js +44 -0
  72. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js.map +1 -0
  73. package/dist/react17/migrate-deprecated-lifecycles.d.ts +8 -0
  74. package/dist/react17/migrate-deprecated-lifecycles.d.ts.map +1 -0
  75. package/dist/react17/migrate-deprecated-lifecycles.js +258 -0
  76. package/dist/react17/migrate-deprecated-lifecycles.js.map +1 -0
  77. package/dist/react17/use-new-jsx-transform.d.ts +8 -0
  78. package/dist/react17/use-new-jsx-transform.d.ts.map +1 -0
  79. package/dist/react17/use-new-jsx-transform.js +121 -0
  80. package/dist/react17/use-new-jsx-transform.js.map +1 -0
  81. package/dist/react18/add-children-to-props.d.ts +8 -0
  82. package/dist/react18/add-children-to-props.d.ts.map +1 -0
  83. package/dist/react18/add-children-to-props.js +277 -0
  84. package/dist/react18/add-children-to-props.js.map +1 -0
  85. package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
  86. package/dist/react18/replace-reactdom-render.js +109 -12
  87. package/dist/react18/replace-reactdom-render.js.map +1 -1
  88. package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
  89. package/dist/react18/replace-unmount-component-at-node.js +62 -20
  90. package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
  91. package/dist/react19/replace-default-props.d.ts.map +1 -1
  92. package/dist/react19/replace-default-props.js +10 -13
  93. package/dist/react19/replace-default-props.js.map +1 -1
  94. package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
  95. package/dist/react19/replace-react-shallow-renderer.js +1 -6
  96. package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
  97. package/dist/refactoring/class-to-functional.d.ts.map +1 -1
  98. package/dist/refactoring/class-to-functional.js +81 -7
  99. package/dist/refactoring/class-to-functional.js.map +1 -1
  100. package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
  101. package/dist/refactoring/create-class-to-es6.js +4 -7
  102. package/dist/refactoring/create-class-to-es6.js.map +1 -1
  103. package/dist/refactoring/create-element-to-jsx.d.ts.map +1 -1
  104. package/dist/refactoring/create-element-to-jsx.js +3 -4
  105. package/dist/refactoring/create-element-to-jsx.js.map +1 -1
  106. package/dist/refactoring/fix-async-effect.d.ts +8 -0
  107. package/dist/refactoring/fix-async-effect.d.ts.map +1 -0
  108. package/dist/refactoring/fix-async-effect.js +71 -0
  109. package/dist/refactoring/fix-async-effect.js.map +1 -0
  110. package/dist/refactoring/prop-types-to-typescript.d.ts +8 -0
  111. package/dist/refactoring/prop-types-to-typescript.d.ts.map +1 -0
  112. package/dist/refactoring/prop-types-to-typescript.js +341 -0
  113. package/dist/refactoring/prop-types-to-typescript.js.map +1 -0
  114. package/dist/refactoring/pure-render-mixin.d.ts.map +1 -1
  115. package/dist/refactoring/pure-render-mixin.js +3 -6
  116. package/dist/refactoring/pure-render-mixin.js.map +1 -1
  117. package/dist/search/find-deprecated-lifecycles.d.ts +12 -0
  118. package/dist/search/find-deprecated-lifecycles.d.ts.map +1 -0
  119. package/dist/search/find-deprecated-lifecycles.js +86 -0
  120. package/dist/search/find-deprecated-lifecycles.js.map +1 -0
  121. package/dist/search/find-effects-without-cleanup.d.ts +9 -0
  122. package/dist/search/find-effects-without-cleanup.d.ts.map +1 -0
  123. package/dist/search/find-effects-without-cleanup.js +133 -0
  124. package/dist/search/find-effects-without-cleanup.js.map +1 -0
  125. package/dist/search/find-enzyme-usage.d.ts +9 -0
  126. package/dist/search/find-enzyme-usage.d.ts.map +1 -0
  127. package/dist/search/find-enzyme-usage.js +155 -0
  128. package/dist/search/find-enzyme-usage.js.map +1 -0
  129. package/dist/search/find-function-component-default-props.d.ts +11 -0
  130. package/dist/search/find-function-component-default-props.d.ts.map +1 -0
  131. package/dist/search/find-function-component-default-props.js +96 -0
  132. package/dist/search/find-function-component-default-props.js.map +1 -0
  133. package/dist/search/find-legacy-react-apis.d.ts +8 -0
  134. package/dist/search/find-legacy-react-apis.d.ts.map +1 -0
  135. package/dist/search/find-legacy-react-apis.js +41 -0
  136. package/dist/search/find-legacy-react-apis.js.map +1 -0
  137. package/dist/search/find-missing-use-client-directive.d.ts +9 -0
  138. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -0
  139. package/dist/search/find-missing-use-client-directive.js +127 -0
  140. package/dist/search/find-missing-use-client-directive.js.map +1 -0
  141. package/dist/search/find-reactdom-root-apis.d.ts +14 -0
  142. package/dist/search/find-reactdom-root-apis.d.ts.map +1 -0
  143. package/dist/search/find-reactdom-root-apis.js +122 -0
  144. package/dist/search/find-reactdom-root-apis.js.map +1 -0
  145. package/dist/testing/enzyme-host-components.d.ts +14 -0
  146. package/dist/testing/enzyme-host-components.d.ts.map +1 -0
  147. package/dist/testing/enzyme-host-components.js +245 -0
  148. package/dist/testing/enzyme-host-components.js.map +1 -0
  149. package/dist/testing/enzyme-to-react-testing-library.d.ts +41 -0
  150. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -0
  151. package/dist/testing/enzyme-to-react-testing-library.js +572 -0
  152. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -0
  153. package/dist/testing/enzyme-usage.d.ts +22 -0
  154. package/dist/testing/enzyme-usage.d.ts.map +1 -0
  155. package/dist/testing/enzyme-usage.js +107 -0
  156. package/dist/testing/enzyme-usage.js.map +1 -0
  157. package/dist/testing/enzyme-wrapper-scope.d.ts +51 -0
  158. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -0
  159. package/dist/testing/enzyme-wrapper-scope.js +420 -0
  160. package/dist/testing/enzyme-wrapper-scope.js.map +1 -0
  161. package/dist/util/module-imports.d.ts +12 -0
  162. package/dist/util/module-imports.d.ts.map +1 -0
  163. package/dist/util/module-imports.js +56 -0
  164. package/dist/util/module-imports.js.map +1 -0
  165. package/dist/util/react-class.d.ts +7 -0
  166. package/dist/util/react-class.d.ts.map +1 -0
  167. package/dist/util/react-class.js +42 -0
  168. package/dist/util/react-class.js.map +1 -0
  169. package/dist/util/tree-search.d.ts +6 -0
  170. package/dist/util/tree-search.d.ts.map +1 -0
  171. package/dist/util/tree-search.js +51 -0
  172. package/dist/util/tree-search.js.map +1 -0
  173. package/package.json +7 -4
  174. package/src/index.ts +53 -12
  175. package/src/migration/cra-to-vite/add-vite-config.ts +47 -0
  176. package/src/migration/cra-to-vite/cra-blockers-table.ts +27 -0
  177. package/src/migration/cra-to-vite/cra-to-vite.ts +76 -0
  178. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +173 -0
  179. package/src/migration/cra-to-vite/find-cra-env-file-blockers.ts +60 -0
  180. package/src/migration/cra-to-vite/find-cra-source-blockers.ts +138 -0
  181. package/src/migration/cra-to-vite/find-cra-to-vite-blockers.ts +21 -0
  182. package/src/migration/cra-to-vite/index.ts +26 -0
  183. package/src/migration/cra-to-vite/move-public-index-html.ts +132 -0
  184. package/src/migration/cra-to-vite/rename-process-env-react-app.ts +93 -0
  185. package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +61 -0
  186. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +71 -0
  187. package/src/migration/cra-to-vite/scan-cra-projects.ts +86 -0
  188. package/src/migration/cra-to-vite/shared.ts +123 -0
  189. package/src/migration/cra-to-vite/update-react-app-env-types.ts +40 -0
  190. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +64 -0
  191. package/src/migration/cra-to-vite/update-tsconfig-for-vite.ts +40 -0
  192. package/src/react17/migrate-deprecated-lifecycles.ts +265 -0
  193. package/src/react17/use-new-jsx-transform.ts +108 -0
  194. package/src/react18/add-children-to-props.ts +235 -0
  195. package/src/react18/replace-reactdom-render.ts +109 -20
  196. package/src/react18/replace-unmount-component-at-node.ts +78 -32
  197. package/src/react19/replace-default-props.ts +11 -15
  198. package/src/react19/replace-react-shallow-renderer.ts +2 -7
  199. package/src/refactoring/class-to-functional.ts +101 -13
  200. package/src/refactoring/create-class-to-es6.ts +6 -9
  201. package/src/refactoring/create-element-to-jsx.ts +4 -6
  202. package/src/refactoring/fix-async-effect.ts +88 -0
  203. package/src/refactoring/prop-types-to-typescript.ts +341 -0
  204. package/src/refactoring/pure-render-mixin.ts +4 -7
  205. package/src/search/find-deprecated-lifecycles.ts +64 -0
  206. package/src/search/find-effects-without-cleanup.ts +109 -0
  207. package/src/search/find-enzyme-usage.ts +117 -0
  208. package/src/search/find-function-component-default-props.ts +68 -0
  209. package/src/search/find-legacy-react-apis.ts +41 -0
  210. package/src/search/find-missing-use-client-directive.ts +99 -0
  211. package/src/search/find-reactdom-root-apis.ts +99 -0
  212. package/src/testing/enzyme-host-components.ts +283 -0
  213. package/src/testing/enzyme-to-react-testing-library.ts +622 -0
  214. package/src/testing/enzyme-usage.ts +94 -0
  215. package/src/testing/enzyme-wrapper-scope.ts +456 -0
  216. package/src/util/module-imports.ts +55 -0
  217. package/src/util/react-class.ts +35 -0
  218. package/src/util/tree-search.ts +32 -0
  219. package/dist/react16/upgrade-to-react-16.d.ts +0 -12
  220. package/dist/react16/upgrade-to-react-16.d.ts.map +0 -1
  221. package/dist/react16/upgrade-to-react-16.js +0 -66
  222. package/dist/react16/upgrade-to-react-16.js.map +0 -1
  223. package/dist/react17/upgrade-to-react-17.d.ts +0 -12
  224. package/dist/react17/upgrade-to-react-17.d.ts.map +0 -1
  225. package/dist/react17/upgrade-to-react-17.js +0 -62
  226. package/dist/react17/upgrade-to-react-17.js.map +0 -1
  227. package/dist/react18/upgrade-to-react-18.d.ts +0 -12
  228. package/dist/react18/upgrade-to-react-18.d.ts.map +0 -1
  229. package/dist/react18/upgrade-to-react-18.js +0 -64
  230. package/dist/react18/upgrade-to-react-18.js.map +0 -1
  231. package/dist/react19/upgrade-to-react-19.d.ts +0 -8
  232. package/dist/react19/upgrade-to-react-19.d.ts.map +0 -1
  233. package/dist/react19/upgrade-to-react-19.js +0 -68
  234. package/dist/react19/upgrade-to-react-19.js.map +0 -1
  235. package/src/react16/upgrade-to-react-16.ts +0 -59
  236. package/src/react17/upgrade-to-react-17.ts +0 -52
  237. package/src/react18/upgrade-to-react-18.ts +0 -55
  238. package/src/react19/upgrade-to-react-19.ts +0 -75
@@ -0,0 +1,88 @@
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
+ import {
3
+ capture,
4
+ isVendoredOrBundled,
5
+ JavaScriptVisitor,
6
+ pattern,
7
+ raw,
8
+ rewrite,
9
+ template
10
+ } from "@openrewrite/rewrite/javascript";
11
+ import {Expression, J} from "@openrewrite/rewrite/java";
12
+
13
+ const EFFECT_HOOKS = ['useEffect', 'useLayoutEffect'];
14
+
15
+ /**
16
+ * Wraps the body of an `async` effect callback in an immediately invoked async function.
17
+ *
18
+ * `useEffect` expects its callback to return nothing or a cleanup function. An `async` callback
19
+ * returns a promise, which React warns about and never uses as a cleanup. The effect still runs
20
+ * the same code in the same order; only the returned promise goes away.
21
+ *
22
+ * Before:
23
+ * ```tsx
24
+ * useEffect(async () => {
25
+ * const data = await load();
26
+ * setData(data);
27
+ * }, []);
28
+ * ```
29
+ *
30
+ * After:
31
+ * ```tsx
32
+ * useEffect(() => {
33
+ * (async () => {
34
+ * const data = await load();
35
+ * setData(data);
36
+ * })();
37
+ * }, []);
38
+ * ```
39
+ *
40
+ * Only `async` arrow functions passed directly to `useEffect` or `useLayoutEffect` (bare or as `React.useEffect`) are changed,
41
+ * with a block or an expression body. A `return` inside the body now returns from the inner
42
+ * function, as it effectively did before, since the outer promise was never a usable cleanup.
43
+ *
44
+ * @see https://react.dev/reference/react/useEffect#fetching-data-with-effects
45
+ */
46
+ export class FixAsyncEffect extends Recipe {
47
+ readonly name = "org.openrewrite.react.refactoring.fix-async-effect";
48
+ readonly displayName = "Fix `async` effect callbacks";
49
+ readonly description = "Wraps the body of an `async` callback passed to `useEffect` or `useLayoutEffect` in an immediately invoked async function, so the effect no longer returns a promise.";
50
+
51
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
52
+ const context = {
53
+ context: ['import { useEffect, useLayoutEffect } from "react";'],
54
+ dependencies: {'@types/react': '^18.0.0'}
55
+ };
56
+ const body = capture();
57
+ const deps = capture<Expression>();
58
+
59
+ const rulesFor = (callee: string) => [
60
+ rewrite(() => ({
61
+ before: pattern`${raw(callee)}(async () => ${body}, ${deps})`.configure(context),
62
+ after: template`${raw(callee)}(() => {(async () => ${body})();}, ${deps})`.configure(context),
63
+ })),
64
+ rewrite(() => ({
65
+ before: pattern`${raw(callee)}(async () => ${body})`.configure(context),
66
+ after: template`${raw(callee)}(() => {(async () => ${body})();})`.configure(context),
67
+ })),
68
+ ];
69
+ const bareRules = EFFECT_HOOKS.flatMap(hook => rulesFor(hook));
70
+ const reactRules = EFFECT_HOOKS.flatMap(hook => rulesFor(`React.${hook}`));
71
+
72
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
73
+ override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
74
+ const m = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
75
+ // Only a direct call of an effect hook can match, so skip the structural matching for every other call.
76
+ if (!EFFECT_HOOKS.includes(m.name.simpleName)) return m;
77
+ const select = m.select?.element;
78
+ const qualified = select?.kind === J.Kind.Identifier && (select as J.Identifier).simpleName === 'React';
79
+ if (select && !qualified) return m;
80
+ for (const rule of qualified ? reactRules : bareRules) {
81
+ const result = await rule.tryOn(this.cursor, m, {visitor: this});
82
+ if (result) return result;
83
+ }
84
+ return m;
85
+ }
86
+ }());
87
+ }
88
+ }
@@ -0,0 +1,341 @@
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
+ import {isObjectLiteral, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeAddImport, raw, template} from "@openrewrite/rewrite/javascript";
3
+ import {emptySpace, J, singleSpace} from "@openrewrite/rewrite/java";
4
+
5
+ /** `PropTypes.<name>` validators with a fixed TypeScript type, and the `react` type each one needs. */
6
+ const SIMPLE_TYPES = new Map<string, { type: string; react?: string }>([
7
+ ['string', {type: 'string'}],
8
+ ['number', {type: 'number'}],
9
+ ['bool', {type: 'boolean'}],
10
+ ['func', {type: '(...args: any[]) => any'}],
11
+ ['object', {type: 'Record<string, any>'}],
12
+ ['array', {type: 'any[]'}],
13
+ ['symbol', {type: 'symbol'}],
14
+ ['any', {type: 'any'}],
15
+ ['node', {type: 'ReactNode', react: 'ReactNode'}],
16
+ ['element', {type: 'ReactElement', react: 'ReactElement'}],
17
+ ['elementType', {type: 'ElementType', react: 'ElementType'}],
18
+ ]);
19
+
20
+ /** Types that already admit `null`, so an optional prop needs no `| null`. */
21
+ const NULLABLE_ALREADY = new Set(['any', 'ReactNode']);
22
+
23
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
24
+
25
+ interface PropType {
26
+ type: string;
27
+ required: boolean;
28
+ }
29
+
30
+ /** Converts a `PropTypes` expression to a TypeScript type, or `undefined` when it has no TypeScript equivalent here. */
31
+ function toPropType(expr: J, reactTypes: Set<string>): PropType | undefined {
32
+ let required = false;
33
+ let e: J = expr;
34
+ if (e.kind === J.Kind.FieldAccess && (e as J.FieldAccess).name.element.simpleName === 'isRequired') {
35
+ required = true;
36
+ e = (e as J.FieldAccess).target;
37
+ }
38
+
39
+ if (e.kind === J.Kind.FieldAccess) {
40
+ const fa = e as J.FieldAccess;
41
+ if (!isPropTypes(fa.target)) return undefined;
42
+ const simple = SIMPLE_TYPES.get(fa.name.element.simpleName);
43
+ if (!simple) return undefined;
44
+ if (simple.react) reactTypes.add(simple.react);
45
+ return {type: simple.type, required};
46
+ }
47
+
48
+ if (e.kind !== J.Kind.MethodInvocation) return undefined;
49
+ const call = e as J.MethodInvocation;
50
+ if (!call.select || !isPropTypes(call.select.element)) return undefined;
51
+ const args = call.arguments.elements.map(a => a.element);
52
+ if (args.length !== 1) return undefined;
53
+ const arg = args[0];
54
+ const type = ((): string | undefined => {
55
+ switch (call.name.simpleName) {
56
+ case 'arrayOf': {
57
+ const inner = toPropType(arg, reactTypes);
58
+ return inner && `${/[|&]|=>/.test(inner.type) ? `(${inner.type})` : inner.type}[]`;
59
+ }
60
+ case 'objectOf': {
61
+ const inner = toPropType(arg, reactTypes);
62
+ return inner && `Record<string, ${inner.type}>`;
63
+ }
64
+ case 'instanceOf':
65
+ return arg.kind === J.Kind.Identifier ? (arg as J.Identifier).simpleName : undefined;
66
+ case 'oneOf': {
67
+ if (arg.kind !== J.Kind.NewArray) return undefined;
68
+ const values = ((arg as J.NewArray).initializer?.elements ?? []).map(v => v.element);
69
+ if (values.length === 0 || !values.every(v => v.kind === J.Kind.Literal)) return undefined;
70
+ return values.map(v => (v as J.Literal).valueSource).join(' | ');
71
+ }
72
+ case 'oneOfType': {
73
+ if (arg.kind !== J.Kind.NewArray) return undefined;
74
+ const members = ((arg as J.NewArray).initializer?.elements ?? []).map(v => toPropType(v.element, reactTypes));
75
+ if (members.length === 0 || members.some(m => !m)) return undefined;
76
+ return members.map(m => /=>/.test(m!.type) ? `(${m!.type})` : m!.type).join(' | ');
77
+ }
78
+ case 'shape':
79
+ case 'exact': {
80
+ const members = objectMembers(arg, reactTypes);
81
+ return members && `{ ${members.join('; ')} }`;
82
+ }
83
+ default:
84
+ return undefined;
85
+ }
86
+ })();
87
+ return type ? {type, required} : undefined;
88
+ }
89
+
90
+ function isPropTypes(expr: J): boolean {
91
+ return expr.kind === J.Kind.Identifier && (expr as J.Identifier).simpleName === 'PropTypes';
92
+ }
93
+
94
+ /** `name: type` / `name?: type` for each property of an object literal, or `undefined` if any is unsupported. */
95
+ function objectMembers(literal: J, reactTypes: Set<string>, names?: Set<string>): string[] | undefined {
96
+ if (!isObjectLiteral(literal)) return undefined;
97
+ const body = literal.body;
98
+ if (!body) return undefined;
99
+ const members: string[] = [];
100
+ for (const statement of body.statements) {
101
+ const property = statement.element;
102
+ if (property.kind !== JS.Kind.PropertyAssignment) return undefined;
103
+ const assignment = property as JS.PropertyAssignment;
104
+ const key = assignment.name.element;
105
+ let name: string;
106
+ if (key.kind === J.Kind.Identifier) name = (key as J.Identifier).simpleName;
107
+ else if (key.kind === J.Kind.Literal && typeof (key as J.Literal).value === 'string') name = (key as J.Literal).value as string;
108
+ else return undefined;
109
+ if (!assignment.initializer) return undefined;
110
+ const type = toPropType(assignment.initializer, reactTypes);
111
+ if (!type) return undefined;
112
+ names?.add(name);
113
+ // PropTypes accept `null` (and `undefined`) for an optional prop, so the optional type admits `null` too.
114
+ const typeText = type.required || NULLABLE_ALREADY.has(type.type) ? type.type : `${/=>/.test(type.type) ? `(${type.type})` : type.type} | null`;
115
+ members.push(`${IDENTIFIER.test(name) ? name : JSON.stringify(name)}${type.required ? '' : '?'}: ${typeText}`);
116
+ }
117
+ return members.length > 0 ? members : undefined;
118
+ }
119
+
120
+ /** The component a statement declares (`function X` or `const X = ...`) with its first parameter, if untyped. */
121
+ function componentOf(statement: J): { name: string; param: J.VariableDeclarations } | undefined {
122
+ if (statement.kind === J.Kind.MethodDeclaration) {
123
+ const method = statement as J.MethodDeclaration;
124
+ const param = method.parameters.elements[0]?.element;
125
+ return param?.kind === J.Kind.VariableDeclarations && !(param as J.VariableDeclarations).typeExpression
126
+ ? {name: method.name.simpleName, param: param as J.VariableDeclarations} : undefined;
127
+ }
128
+ if (statement.kind === J.Kind.VariableDeclarations) {
129
+ const variable = (statement as J.VariableDeclarations).variables[0]?.element;
130
+ const init = variable?.initializer?.element;
131
+ if (!variable || init?.kind !== JS.Kind.ArrowFunction) return undefined;
132
+ const param = (init as JS.ArrowFunction).lambda.parameters.parameters[0]?.element;
133
+ return param?.kind === J.Kind.VariableDeclarations && !(param as J.VariableDeclarations).typeExpression
134
+ ? {name: (variable.name as J.Identifier).simpleName, param: param as J.VariableDeclarations} : undefined;
135
+ }
136
+ return undefined;
137
+ }
138
+
139
+ /**
140
+ * The names of the props a component reads: its destructured parameter names, or the `props.<x>` reads and
141
+ * `const {x} = props` destructurings of an identifier parameter. `undefined` when a name cannot be told.
142
+ */
143
+ async function propsRead(component: J): Promise<Set<string> | undefined> {
144
+ const param = componentOf(component)?.param;
145
+ const declarator = param?.variables[0]?.element.name as J | undefined;
146
+ if (!declarator) return undefined;
147
+ const names = new Set<string>();
148
+ let ok = true;
149
+ const keyOf = (element: J): string | undefined => {
150
+ if (element.kind === J.Kind.Identifier) return (element as J.Identifier).simpleName;
151
+ if (element.kind === JS.Kind.BindingElement) {
152
+ const binding = element as JS.BindingElement;
153
+ if (binding.name.kind === JS.Kind.Spread) return undefined; // a rest element reads whatever is left over
154
+ const key = binding.propertyName?.element ?? binding.name;
155
+ if (key.kind === J.Kind.Identifier) return (key as J.Identifier).simpleName;
156
+ if (key.kind === J.Kind.Literal && typeof (key as J.Literal).value === 'string') return (key as J.Literal).value as string;
157
+ ok = false;
158
+ }
159
+ return undefined; // a rest element reads whatever is left over
160
+ };
161
+ const addBindings = (pattern: J) => {
162
+ for (const e of (pattern as JS.ObjectBindingPattern).bindings.elements) {
163
+ const key = keyOf(e.element);
164
+ if (key) names.add(key);
165
+ }
166
+ };
167
+ if (declarator.kind === JS.Kind.ObjectBindingPattern) {
168
+ addBindings(declarator);
169
+ return ok ? names : undefined;
170
+ }
171
+ if (declarator.kind !== J.Kind.Identifier) return undefined;
172
+ const propsName = (declarator as J.Identifier).simpleName;
173
+ await new class extends JavaScriptVisitor<ExecutionContext> {
174
+ override async visitFieldAccess(fa: J.FieldAccess, ctx: ExecutionContext): Promise<J | undefined> {
175
+ if (fa.target.kind === J.Kind.Identifier && (fa.target as J.Identifier).simpleName === propsName) {
176
+ names.add(fa.name.element.simpleName);
177
+ }
178
+ return super.visitFieldAccess(fa, ctx);
179
+ }
180
+
181
+ override async visitVariableDeclarations(decl: J.VariableDeclarations, ctx: ExecutionContext): Promise<J | undefined> {
182
+ for (const v of decl.variables) {
183
+ const init = v.element.initializer?.element;
184
+ if (init?.kind === J.Kind.Identifier && (init as J.Identifier).simpleName === propsName && v.element.name.kind === JS.Kind.ObjectBindingPattern) {
185
+ addBindings(v.element.name);
186
+ }
187
+ }
188
+ return super.visitVariableDeclarations(decl, ctx);
189
+ }
190
+ }().visit(component, {} as ExecutionContext);
191
+ return ok ? names : undefined;
192
+ }
193
+
194
+ /** Clears the space after a bare parameter's name, so a type annotation can follow it directly. */
195
+ function withoutTrailingSpace(param: J.VariableDeclarations): J.VariableDeclarations {
196
+ return {...param, variables: param.variables.map(v => ({...v, after: emptySpace}))};
197
+ }
198
+
199
+ /** Every identifier spelled anywhere in the file, so a generated type name can be checked for a clash. */
200
+ async function identifierNames(cu: JS.CompilationUnit): Promise<Set<string>> {
201
+ const names = new Set<string>();
202
+ await new class extends JavaScriptVisitor<ExecutionContext> {
203
+ protected override async visitIdentifier(ident: J.Identifier, ctx: ExecutionContext): Promise<J | undefined> {
204
+ names.add(ident.simpleName);
205
+ return super.visitIdentifier(ident, ctx);
206
+ }
207
+ }().visit(cu, {} as ExecutionContext);
208
+ return names;
209
+ }
210
+
211
+ /**
212
+ * Declares a props type from `Component.propTypes` and annotates the component's parameter with it.
213
+ *
214
+ * Before:
215
+ * ```tsx
216
+ * function Greeting({name, onDone}) { ... }
217
+ * Greeting.propTypes = {
218
+ * name: PropTypes.string.isRequired,
219
+ * onDone: PropTypes.func,
220
+ * };
221
+ * ```
222
+ *
223
+ * After:
224
+ * ```tsx
225
+ * interface GreetingProps {
226
+ * name: string;
227
+ * onDone?: (...args: any[]) => any;
228
+ * }
229
+ *
230
+ * function Greeting({name, onDone}: GreetingProps) { ... }
231
+ * Greeting.propTypes = { ... };
232
+ * ```
233
+ *
234
+ * The `propTypes` assignment is kept, so the runtime checks still run; follow with `RemovePropTypes`
235
+ * when they are no longer wanted. A component is converted only when it is a function declaration or
236
+ * an arrow function assigned to a `const`, its first parameter has no type, and every `propTypes`
237
+ * entry maps to a TypeScript type (an optional prop also admits `null`, as `PropTypes` does, and
238
+ * `PropTypes.object` becomes `Record<string, any>`). A component that reads a prop `propTypes` does not
239
+ * declare, such as `children`, is left alone, since the interface would not cover it. Anything else is left alone. Only `.ts` and `.tsx` files
240
+ * are changed.
241
+ */
242
+ export class PropTypesToTypeScript extends Recipe {
243
+ readonly name = "org.openrewrite.react.refactoring.prop-types-to-typescript";
244
+ readonly displayName = "Convert `propTypes` to a TypeScript props type";
245
+ readonly description = "Declares an `interface` from a function component's `propTypes` and annotates the component's props parameter with it, keeping the `propTypes` assignment. Components with an unsupported `propTypes` entry are left alone.";
246
+
247
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
248
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
249
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
250
+ if (!isTypeScript(cu)) return cu;
251
+
252
+ const reactTypes = new Set<string>();
253
+ const plans: { index: number; propsName: string; source: string }[] = [];
254
+ let taken: Set<string> | undefined;
255
+ for (const statement of cu.statements) {
256
+ const assignment = this.propTypesAssignment(statement.element);
257
+ if (!assignment) continue;
258
+ const index = cu.statements.findIndex(s => s.element && componentOf(s.element)?.name === assignment.component);
259
+ if (index < 0 || plans.some(p => p.index === index)) continue;
260
+ const propsName = `${assignment.component}Props`;
261
+ taken ??= await identifierNames(cu);
262
+ if (taken.has(propsName)) continue;
263
+ const types = new Set<string>();
264
+ const declared = new Set<string>();
265
+ const members = objectMembers(assignment.object, types, declared);
266
+ if (!members) continue;
267
+ // The interface lists only the declared props, so a component that reads any other prop
268
+ // (`children`, `className`, ...) would no longer type-check against it.
269
+ const read = await propsRead(cu.statements[index].element);
270
+ if (!read || [...read].some(name => !declared.has(name))) continue;
271
+ types.forEach(t => reactTypes.add(t));
272
+ const source = `interface ${propsName} {\n${members.map(m => ` ${m};`).join('\n')}\n}`;
273
+ plans.push({index, propsName, source});
274
+ }
275
+ if (plans.length === 0) return cu;
276
+
277
+ const statements = [...cu.statements];
278
+ for (const plan of plans.sort((a, b) => b.index - a.index)) {
279
+ const original = statements[plan.index];
280
+ const component = original.element as J;
281
+ const typed = await this.annotate(component, plan.propsName, cu);
282
+ const declared = await template`${raw(plan.source)}`.apply(cu, this.cursor) as J.ClassDeclaration | undefined;
283
+ if (!typed || !declared) continue;
284
+ const space = (component as any).prefix;
285
+ statements.splice(plan.index, 1,
286
+ {...original, element: {...declared, prefix: {...space, comments: []}}, markers: {...original.markers, markers: []}},
287
+ {...original, element: {...typed, prefix: {...space, whitespace: "\n\n"}}});
288
+ }
289
+ reactTypes.forEach(member => maybeAddImport(this, {module: 'react', member, onlyIfReferenced: false}));
290
+ return {...cu, statements} as JS.CompilationUnit;
291
+ }
292
+
293
+ /** `X.propTypes = {...}` as the component name and the object literal. */
294
+ private propTypesAssignment(statement: J | undefined): { component: string; object: J } | undefined {
295
+ let expr: J | undefined = statement;
296
+ if (expr?.kind === JS.Kind.ExpressionStatement) expr = (expr as JS.ExpressionStatement).expression;
297
+ if (expr?.kind !== J.Kind.Assignment) return undefined;
298
+ const assignment = expr as J.Assignment;
299
+ if (assignment.variable.kind !== J.Kind.FieldAccess) return undefined;
300
+ const fa = assignment.variable as J.FieldAccess;
301
+ if (fa.name.element.simpleName !== 'propTypes' || fa.target.kind !== J.Kind.Identifier) return undefined;
302
+ return {component: (fa.target as J.Identifier).simpleName, object: assignment.assignment.element};
303
+ }
304
+
305
+ /** The component with its first parameter annotated, using the parsed annotation of a template. */
306
+ private async annotate(component: J, propsName: string, anchor: J): Promise<J | undefined> {
307
+ const sample = await template`function sample(props: ${raw(propsName)}) {}`.apply(anchor, this.cursor) as J.MethodDeclaration | undefined;
308
+ const typeInfo = (sample?.parameters.elements[0]?.element as J.VariableDeclarations | undefined)?.typeExpression;
309
+ if (!typeInfo) return undefined;
310
+ const withType = (param: J.VariableDeclarations): J.VariableDeclarations => ({...param, typeExpression: typeInfo});
311
+
312
+ if (component.kind === J.Kind.MethodDeclaration) {
313
+ const method = component as J.MethodDeclaration;
314
+ const [first, ...rest] = method.parameters.elements;
315
+ return {...method, parameters: {...method.parameters, elements: [{...first, element: withType(first.element as J.VariableDeclarations)}, ...rest]}} as J.MethodDeclaration;
316
+ }
317
+ const decl = component as J.VariableDeclarations;
318
+ const variable = decl.variables[0];
319
+ const arrow = variable.element.initializer!.element as JS.ArrowFunction;
320
+ const params = arrow.lambda.parameters;
321
+ const [first, ...rest] = params.parameters;
322
+ // `props => ...` needs parentheses once the parameter has a type, and the space that
323
+ // followed the bare parameter now belongs before the arrow.
324
+ const bare = !params.parenthesized;
325
+ const lambda = {
326
+ ...arrow.lambda,
327
+ arrow: bare ? singleSpace : arrow.lambda.arrow,
328
+ parameters: {
329
+ ...params,
330
+ parenthesized: true,
331
+ parameters: [{...first, after: bare ? emptySpace : first.after, element: withType(bare ? withoutTrailingSpace(first.element as J.VariableDeclarations) : first.element as J.VariableDeclarations)}, ...rest],
332
+ },
333
+ };
334
+ return {
335
+ ...decl,
336
+ variables: [{...variable, element: {...variable.element, initializer: {...variable.element.initializer!, element: {...arrow, lambda}}}}, ...decl.variables.slice(1)],
337
+ } as J.VariableDeclarations;
338
+ }
339
+ }());
340
+ }
341
+ }
@@ -1,5 +1,5 @@
1
1
  import {Cursor, ExecutionContext, findMarker, Marker, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
- import {JavaScriptVisitor, JS, maybeRemoveImport, template, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
2
+ import {isObjectLiteral, JavaScriptVisitor, JS, maybeRemoveImport, template, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
3
3
  import {J, TextComment} from "@openrewrite/rewrite/java";
4
4
 
5
5
  /**
@@ -53,11 +53,8 @@ export class PureRenderMixin extends Recipe {
53
53
  const args = m.arguments.elements;
54
54
  if (args.length === 0) return m;
55
55
 
56
- const specArg = args[0].element;
57
- if (specArg.kind !== J.Kind.NewClass) return m;
58
-
59
- const specObj = specArg as J.NewClass;
60
- if (!specObj.body) return m;
56
+ const specObj = args[0].element;
57
+ if (!isObjectLiteral(specObj) || !specObj.body) return m;
61
58
 
62
59
  // Find the mixins property and check for PureRenderMixin
63
60
  const mixinsInfo = this.findPureRenderMixin(specObj.body);
@@ -173,7 +170,7 @@ export class PureRenderMixin extends Recipe {
173
170
  return React.addons.shallowCompare(this, nextProps, nextState);
174
171
  }
175
172
  }`.apply(specObj, new Cursor(specObj, this.cursor));
176
- const method = obj?.kind === J.Kind.NewClass ? (obj as J.NewClass).body?.statements[0]?.element : undefined;
173
+ const method = obj && isObjectLiteral(obj) ? obj.body?.statements[0]?.element : undefined;
177
174
  return method?.kind === J.Kind.MethodDeclaration ? method as J.MethodDeclaration : undefined;
178
175
  }
179
176
 
@@ -0,0 +1,64 @@
1
+ import {Column, DataTable, ExecutionContext, foundSearchResult, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
+ import {isVendoredOrBundled, JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
3
+ import {J} from "@openrewrite/rewrite/java";
4
+ import {extendsReactComponentByName} from "../util/react-class";
5
+
6
+ class DeprecatedLifecycleRow {
7
+ @Column({displayName: "File path", description: "The file where the lifecycle is declared"})
8
+ filePath!: string;
9
+
10
+ @Column({displayName: "Class", description: "The component class that declares it"})
11
+ className!: string;
12
+
13
+ @Column({displayName: "Lifecycle", description: "`componentWillMount`, `componentWillReceiveProps` or `componentWillUpdate`"})
14
+ lifecycle!: string;
15
+
16
+ @Column({displayName: "Upgrade step", description: "The step recipe that renames it to its `UNSAFE_` form, or moves it where that is safe"})
17
+ upgradeStep!: string;
18
+ }
19
+
20
+ /** The lifecycles React 16.3 deprecated and 17 started warning about, and the step recipe that handles them. */
21
+ export const DEPRECATED_LIFECYCLES = new Set(['componentWillMount', 'componentWillReceiveProps', 'componentWillUpdate']);
22
+ export const DEPRECATED_LIFECYCLE_STEP = 'org.openrewrite.react.migrate.react-16-to-17';
23
+ export const DEPRECATED_LIFECYCLE_MIGRATORS = ['org.openrewrite.react.17.rename-unsafe-lifecycles', 'org.openrewrite.react.17.migrate-deprecated-lifecycles'];
24
+
25
+ /**
26
+ * Finds the `componentWillMount`, `componentWillReceiveProps` and `componentWillUpdate` lifecycles declared on a class
27
+ * component. The `UNSAFE_` forms are not reported, since they are what the migration produces.
28
+ *
29
+ * @see https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html
30
+ */
31
+ export class FindDeprecatedLifecycles extends Recipe {
32
+ readonly name = "org.openrewrite.react.search.find-deprecated-lifecycles";
33
+ readonly displayName = "Find deprecated component lifecycles";
34
+ readonly description = "Finds `componentWillMount`, `componentWillReceiveProps` and `componentWillUpdate` on class components, and records the step recipe that migrates them in a data table.";
35
+
36
+ private dataTable = new DataTable<DeprecatedLifecycleRow>(
37
+ "org.openrewrite.react.search.DeprecatedLifecyclesTable",
38
+ "Deprecated lifecycle usages",
39
+ "Deprecated component lifecycles found on class components, with the step recipe that migrates them.",
40
+ DeprecatedLifecycleRow
41
+ );
42
+
43
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
44
+ const dataTable = this.dataTable;
45
+
46
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
47
+ private filePath = "";
48
+
49
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
50
+ this.filePath = cu.sourcePath ?? "";
51
+ return super.visitJsCompilationUnit(cu, ctx);
52
+ }
53
+
54
+ override async visitMethodDeclaration(method: J.MethodDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
55
+ const m = await super.visitMethodDeclaration(method, ctx) as J.MethodDeclaration;
56
+ if (!DEPRECATED_LIFECYCLES.has(m.name.simpleName)) return m;
57
+ const owner = this.cursor.firstEnclosing((n: any): n is J.ClassDeclaration => n?.kind === J.Kind.ClassDeclaration);
58
+ if (!owner || !extendsReactComponentByName(owner)) return m;
59
+ dataTable.insertRow(ctx, {filePath: this.filePath, className: owner.name.simpleName, lifecycle: m.name.simpleName, upgradeStep: DEPRECATED_LIFECYCLE_STEP});
60
+ return foundSearchResult(m, m.name.simpleName) as J.MethodDeclaration;
61
+ }
62
+ }());
63
+ }
64
+ }
@@ -0,0 +1,109 @@
1
+ import {Column, DataTable, ExecutionContext, foundSearchResult, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
+ import {JavaScriptVisitor, JS, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
3
+ import {J} from "@openrewrite/rewrite/java";
4
+ import {firstResult} from "../util/tree-search";
5
+
6
+ class EffectRow {
7
+ @Column({displayName: "File path", description: "The file containing the effect"})
8
+ filePath!: string;
9
+
10
+ @Column({displayName: "Hook", description: "`useEffect` or `useLayoutEffect`"})
11
+ hook!: string;
12
+
13
+ @Column({displayName: "Subscription call", description: "The call in the effect that sets something up and has no cleanup"})
14
+ call!: string;
15
+ }
16
+
17
+ const EFFECT_HOOKS = new Set(['useEffect', 'useLayoutEffect']);
18
+ /** Calls that register something that must be undone, so an effect that makes one needs a cleanup. */
19
+ const SETUP_CALLS = new Set(['addEventListener', 'setInterval', 'subscribe', 'observe', 'addListener', 'on', 'connect']);
20
+
21
+ /** The first setup-style call anywhere in the subtree, if any. `on` is too common a name without a receiver to mean an event registration. */
22
+ const findSetupCall = (tree: J): Promise<string | undefined> => firstResult(tree, n => {
23
+ if (n.kind !== J.Kind.MethodInvocation) return undefined;
24
+ const call = n as J.MethodInvocation;
25
+ const name = call.name.simpleName;
26
+ return SETUP_CALLS.has(name) && (name !== 'on' || call.select) ? name : undefined;
27
+ });
28
+
29
+ /**
30
+ * Whether the callback returns a value anywhere in its own body, such as inside an `if` or `try`.
31
+ * Returns inside nested functions belong to those functions and do not count.
32
+ */
33
+ const returnsValue = async (body: J): Promise<boolean> => {
34
+ let found = false;
35
+ await new class extends JavaScriptVisitor<ExecutionContext> {
36
+ protected override async visitReturn(ret: J.Return, ctx: ExecutionContext): Promise<J | undefined> {
37
+ if (ret.expression) found = true;
38
+ return super.visitReturn(ret, ctx);
39
+ }
40
+
41
+ protected override async visitMethodDeclaration(method: J.MethodDeclaration): Promise<J | undefined> {
42
+ return method;
43
+ }
44
+
45
+ protected override async visitArrowFunction(arrow: JS.ArrowFunction): Promise<J | undefined> {
46
+ return arrow;
47
+ }
48
+
49
+ protected override async visitLambda(lambda: J.Lambda): Promise<J | undefined> {
50
+ return lambda;
51
+ }
52
+ }().visit(body, {} as ExecutionContext);
53
+ return found;
54
+ };
55
+
56
+ /**
57
+ * Finds effects that register a listener, timer or subscription but return no cleanup function.
58
+ *
59
+ * React 18's `StrictMode` runs every effect's setup, cleanup and setup again in development, so an
60
+ * effect without a cleanup registers twice and exposes leaks and double subscriptions. This is a
61
+ * heuristic over call names: only effects with a block-bodied arrow function callback are considered,
62
+ * and an effect whose callback returns a value anywhere outside nested functions counts as having a cleanup.
63
+ */
64
+ export class FindEffectsWithoutCleanup extends Recipe {
65
+ readonly name = "org.openrewrite.react.search.find-effects-without-cleanup";
66
+ readonly displayName = "Find effects that subscribe without cleanup";
67
+ readonly description = "Finds `useEffect` and `useLayoutEffect` callbacks that add an event listener, interval, observer or subscription but return no cleanup function, which React 18 `StrictMode` surfaces by running effects twice in development.";
68
+
69
+ private dataTable = new DataTable<EffectRow>(
70
+ "org.openrewrite.react.search.EffectsWithoutCleanupTable",
71
+ "Effects without cleanup",
72
+ "Effects that set up a listener, timer or subscription and return no cleanup function.",
73
+ EffectRow
74
+ );
75
+
76
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
77
+ const dataTable = this.dataTable;
78
+
79
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
80
+ private filePath = "";
81
+
82
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
83
+ this.filePath = cu.sourcePath ?? "";
84
+ return super.visitJsCompilationUnit(cu, ctx);
85
+ }
86
+
87
+ override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
88
+ const m = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
89
+ const hook = m.name.simpleName;
90
+ if (!EFFECT_HOOKS.has(hook)) return m;
91
+ // Only the bare hook or `React.useEffect`; `scheduler.useEffect` is something else.
92
+ const select = m.select?.element;
93
+ if (select && !(select.kind === J.Kind.Identifier && (select as J.Identifier).simpleName === 'React')) return m;
94
+
95
+ const callback = m.arguments.elements[0]?.element;
96
+ if (callback?.kind !== JS.Kind.ArrowFunction) return m;
97
+ const body = (callback as JS.ArrowFunction).lambda.body;
98
+ if (body.kind !== J.Kind.Block) return m;
99
+
100
+ if (await returnsValue(body as J)) return m;
101
+
102
+ const call = await findSetupCall(body as J);
103
+ if (!call) return m;
104
+ dataTable.insertRow(ctx, {filePath: this.filePath, hook, call});
105
+ return foundSearchResult(m, `${hook} sets up ${call} without cleanup`);
106
+ }
107
+ }());
108
+ }
109
+ }