@openrewrite/recipes-react 0.13.0 → 0.15.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 (204) 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 +185 -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 +98 -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 +37 -0
  58. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -0
  59. package/dist/migration/cra-to-vite/shared.js +218 -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 +67 -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 +53 -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 +169 -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/refactoring/class-to-functional.d.ts.map +1 -1
  89. package/dist/refactoring/class-to-functional.js +81 -7
  90. package/dist/refactoring/class-to-functional.js.map +1 -1
  91. package/dist/refactoring/fix-async-effect.d.ts +8 -0
  92. package/dist/refactoring/fix-async-effect.d.ts.map +1 -0
  93. package/dist/refactoring/fix-async-effect.js +71 -0
  94. package/dist/refactoring/fix-async-effect.js.map +1 -0
  95. package/dist/refactoring/prop-types-to-typescript.d.ts +8 -0
  96. package/dist/refactoring/prop-types-to-typescript.d.ts.map +1 -0
  97. package/dist/refactoring/prop-types-to-typescript.js +342 -0
  98. package/dist/refactoring/prop-types-to-typescript.js.map +1 -0
  99. package/dist/search/find-deprecated-lifecycles.d.ts +12 -0
  100. package/dist/search/find-deprecated-lifecycles.d.ts.map +1 -0
  101. package/dist/search/find-deprecated-lifecycles.js +86 -0
  102. package/dist/search/find-deprecated-lifecycles.js.map +1 -0
  103. package/dist/search/find-effects-without-cleanup.d.ts +9 -0
  104. package/dist/search/find-effects-without-cleanup.d.ts.map +1 -0
  105. package/dist/search/find-effects-without-cleanup.js +133 -0
  106. package/dist/search/find-effects-without-cleanup.js.map +1 -0
  107. package/dist/search/find-enzyme-usage.d.ts +9 -0
  108. package/dist/search/find-enzyme-usage.d.ts.map +1 -0
  109. package/dist/search/find-enzyme-usage.js +155 -0
  110. package/dist/search/find-enzyme-usage.js.map +1 -0
  111. package/dist/search/find-function-component-default-props.d.ts +11 -0
  112. package/dist/search/find-function-component-default-props.d.ts.map +1 -0
  113. package/dist/search/find-function-component-default-props.js +96 -0
  114. package/dist/search/find-function-component-default-props.js.map +1 -0
  115. package/dist/search/find-legacy-react-apis.d.ts +8 -0
  116. package/dist/search/find-legacy-react-apis.d.ts.map +1 -0
  117. package/dist/search/find-legacy-react-apis.js +41 -0
  118. package/dist/search/find-legacy-react-apis.js.map +1 -0
  119. package/dist/search/find-missing-use-client-directive.d.ts +9 -0
  120. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -0
  121. package/dist/search/find-missing-use-client-directive.js +127 -0
  122. package/dist/search/find-missing-use-client-directive.js.map +1 -0
  123. package/dist/search/find-reactdom-root-apis.d.ts +14 -0
  124. package/dist/search/find-reactdom-root-apis.d.ts.map +1 -0
  125. package/dist/search/find-reactdom-root-apis.js +122 -0
  126. package/dist/search/find-reactdom-root-apis.js.map +1 -0
  127. package/dist/testing/enzyme-to-react-testing-library.d.ts +36 -0
  128. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -0
  129. package/dist/testing/enzyme-to-react-testing-library.js +547 -0
  130. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -0
  131. package/dist/testing/enzyme-usage.d.ts +22 -0
  132. package/dist/testing/enzyme-usage.d.ts.map +1 -0
  133. package/dist/testing/enzyme-usage.js +107 -0
  134. package/dist/testing/enzyme-usage.js.map +1 -0
  135. package/dist/testing/enzyme-wrapper-scope.d.ts +42 -0
  136. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -0
  137. package/dist/testing/enzyme-wrapper-scope.js +422 -0
  138. package/dist/testing/enzyme-wrapper-scope.js.map +1 -0
  139. package/dist/util/react-class.d.ts +6 -0
  140. package/dist/util/react-class.d.ts.map +1 -0
  141. package/dist/util/react-class.js +41 -0
  142. package/dist/util/react-class.js.map +1 -0
  143. package/dist/util/tree-search.d.ts +6 -0
  144. package/dist/util/tree-search.d.ts.map +1 -0
  145. package/dist/util/tree-search.js +51 -0
  146. package/dist/util/tree-search.js.map +1 -0
  147. package/package.json +7 -4
  148. package/src/index.ts +53 -12
  149. package/src/migration/cra-to-vite/add-vite-config.ts +47 -0
  150. package/src/migration/cra-to-vite/cra-blockers-table.ts +27 -0
  151. package/src/migration/cra-to-vite/cra-to-vite.ts +76 -0
  152. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +179 -0
  153. package/src/migration/cra-to-vite/find-cra-env-file-blockers.ts +60 -0
  154. package/src/migration/cra-to-vite/find-cra-source-blockers.ts +138 -0
  155. package/src/migration/cra-to-vite/find-cra-to-vite-blockers.ts +21 -0
  156. package/src/migration/cra-to-vite/index.ts +26 -0
  157. package/src/migration/cra-to-vite/move-public-index-html.ts +132 -0
  158. package/src/migration/cra-to-vite/rename-process-env-react-app.ts +93 -0
  159. package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +61 -0
  160. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +96 -0
  161. package/src/migration/cra-to-vite/scan-cra-projects.ts +86 -0
  162. package/src/migration/cra-to-vite/shared.ts +244 -0
  163. package/src/migration/cra-to-vite/update-react-app-env-types.ts +40 -0
  164. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +69 -0
  165. package/src/migration/cra-to-vite/update-tsconfig-for-vite.ts +47 -0
  166. package/src/react17/migrate-deprecated-lifecycles.ts +265 -0
  167. package/src/react17/use-new-jsx-transform.ts +150 -0
  168. package/src/react18/add-children-to-props.ts +235 -0
  169. package/src/react18/replace-reactdom-render.ts +109 -20
  170. package/src/refactoring/class-to-functional.ts +101 -13
  171. package/src/refactoring/fix-async-effect.ts +88 -0
  172. package/src/refactoring/prop-types-to-typescript.ts +341 -0
  173. package/src/search/find-deprecated-lifecycles.ts +64 -0
  174. package/src/search/find-effects-without-cleanup.ts +109 -0
  175. package/src/search/find-enzyme-usage.ts +117 -0
  176. package/src/search/find-function-component-default-props.ts +68 -0
  177. package/src/search/find-legacy-react-apis.ts +41 -0
  178. package/src/search/find-missing-use-client-directive.ts +99 -0
  179. package/src/search/find-reactdom-root-apis.ts +99 -0
  180. package/src/testing/enzyme-to-react-testing-library.ts +553 -0
  181. package/src/testing/enzyme-usage.ts +94 -0
  182. package/src/testing/enzyme-wrapper-scope.ts +449 -0
  183. package/src/util/react-class.ts +34 -0
  184. package/src/util/tree-search.ts +32 -0
  185. package/dist/react16/upgrade-to-react-16.d.ts +0 -12
  186. package/dist/react16/upgrade-to-react-16.d.ts.map +0 -1
  187. package/dist/react16/upgrade-to-react-16.js +0 -66
  188. package/dist/react16/upgrade-to-react-16.js.map +0 -1
  189. package/dist/react17/upgrade-to-react-17.d.ts +0 -12
  190. package/dist/react17/upgrade-to-react-17.d.ts.map +0 -1
  191. package/dist/react17/upgrade-to-react-17.js +0 -62
  192. package/dist/react17/upgrade-to-react-17.js.map +0 -1
  193. package/dist/react18/upgrade-to-react-18.d.ts +0 -12
  194. package/dist/react18/upgrade-to-react-18.d.ts.map +0 -1
  195. package/dist/react18/upgrade-to-react-18.js +0 -64
  196. package/dist/react18/upgrade-to-react-18.js.map +0 -1
  197. package/dist/react19/upgrade-to-react-19.d.ts +0 -8
  198. package/dist/react19/upgrade-to-react-19.d.ts.map +0 -1
  199. package/dist/react19/upgrade-to-react-19.js +0 -68
  200. package/dist/react19/upgrade-to-react-19.js.map +0 -1
  201. package/src/react16/upgrade-to-react-16.ts +0 -59
  202. package/src/react17/upgrade-to-react-17.ts +0 -52
  203. package/src/react18/upgrade-to-react-18.ts +0 -55
  204. package/src/react19/upgrade-to-react-19.ts +0 -75
@@ -0,0 +1,341 @@
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
+ import {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 (literal.kind !== J.Kind.NewClass) return undefined;
97
+ const body = (literal as J.NewClass).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 (!/\.tsx?$/.test(cu.sourcePath ?? "")) 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
+ }
@@ -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
+ }
@@ -0,0 +1,117 @@
1
+ import {and, check, not, or, DataTable, ExecutionContext, foundSearchResult, Recipe, RecipeRef, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {isVendoredOrBundled, JavaScriptVisitor, JS, usesMethod, usesType} from "@openrewrite/rewrite/javascript";
3
+ import {isIdentifier, J, Type, TypedTree} from "@openrewrite/rewrite/java";
4
+ import {enclosingScope, ENZYME_GUIDE, ENZYME_USAGE_TABLE, enzymeMethod, enzymeModule, enzymeWrapper, EnzymeUsageRow, migrationReason} from "../testing/enzyme-usage";
5
+
6
+ /**
7
+ * Inventories imports/setup even when types are unavailable; calls and wrapper fields are
8
+ * attributed to Enzyme by declaring type, not by names such as `find` or `state`.
9
+ *
10
+ * @see https://testing-library.com/docs/react-testing-library/migrate-from-enzyme/#how-to-migrate-from-enzyme-to-react-testing-library
11
+ */
12
+ export class FindEnzymeUsage extends Recipe {
13
+ readonly name = "org.openrewrite.react.search.find-enzyme-usage";
14
+ readonly displayName = "Find Enzyme usage";
15
+ readonly description = "Finds `enzyme` imports, re-exports, setup modules, typed calls, and wrapper fields, and reports review steps for migrating to React Testing Library. Module references are reported even when call types are unavailable.";
16
+
17
+ private readonly usages = new DataTable<EnzymeUsageRow>(
18
+ ENZYME_USAGE_TABLE, "Enzyme migration inventory",
19
+ "Remaining Enzyme usages and migration actions. Module rows include references whose call types may be unavailable; they are not counts of test cases.",
20
+ EnzymeUsageRow
21
+ );
22
+
23
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
24
+ const usages = this.usages;
25
+ // Keep untyped imports (including escaped module names), and attributed uses
26
+ // through helpers. The JVM evaluates these gates before serializing an LST to JS.
27
+ const relevant = or(
28
+ new RecipeRef("org.openrewrite.text.Find", {find: String.raw`enzyme|\\`, regex: true, caseSensitive: true}),
29
+ usesMethod("enzyme *(..)"), usesType("enzyme.*", true), usesType("enzyme..*", true)
30
+ );
31
+ return check(and(not(isVendoredOrBundled()), relevant), new class extends JavaScriptVisitor<ExecutionContext> {
32
+ private sourcePath = "";
33
+
34
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
35
+ this.sourcePath = cu.sourcePath;
36
+ return super.visitJsCompilationUnit(cu, ctx);
37
+ }
38
+
39
+ override async visitImportDeclaration(imp: JS.Import, ctx: ExecutionContext): Promise<J | undefined> {
40
+ const module = imp.moduleSpecifier?.element;
41
+ const moduleName = module?.kind === J.Kind.Literal ? (module as J.Literal).value : undefined;
42
+ const result = await super.visitImportDeclaration(imp, ctx) as JS.Import;
43
+ if (!enzymeModule(moduleName)) return result;
44
+ return this.report(result, moduleName, "MODULE_REFERENCE",
45
+ "Review this import and its consumers; unresolved or indirect calls require manual inspection. Keep it while Enzyme consumers remain.", ctx);
46
+ }
47
+
48
+ override async visitExportDeclaration(exp: JS.ExportDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
49
+ const result = await super.visitExportDeclaration(exp, ctx) as JS.ExportDeclaration;
50
+ const module = exp.moduleSpecifier?.element;
51
+ const moduleName = module?.kind === J.Kind.Literal ? (module as J.Literal).value : undefined;
52
+ if (!enzymeModule(moduleName)) return result;
53
+ return this.report(result, moduleName, "HELPER_REEXPORT",
54
+ "Trace downstream helper consumers before migrating or removing this Enzyme re-export.", ctx);
55
+ }
56
+
57
+ override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
58
+ const result = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
59
+ const args = method.arguments.elements.map(arg => arg.element);
60
+ const moduleName = args[0]?.kind === J.Kind.Literal ? (args[0] as J.Literal).value : undefined;
61
+ // A local function called require is not a module loader.
62
+ if (!method.select && method.name.simpleName === "require" && args.length === 1 && enzymeModule(moduleName)) {
63
+ const variable = method.name.fieldType;
64
+ const unresolved = !variable && (!method.methodType || method.methodType.declaringType.kind === Type.Kind.Unknown);
65
+ const nodeRequire = variable && Type.isOfTypeWithName(variable.type, false, name => name === "NodeJS.Require");
66
+ if (unresolved || nodeRequire) {
67
+ return this.report(result, moduleName, "MODULE_REFERENCE",
68
+ "Review this module load and its consumers; CommonJS and dynamic imports may need manual migration.", ctx);
69
+ }
70
+ }
71
+ const api = enzymeMethod(method);
72
+ if (!api) return result;
73
+ const {reason, suggestedAction} = migrationReason(api);
74
+ return this.report(result, api, reason, suggestedAction, ctx);
75
+ }
76
+
77
+ override async visitFunctionCall(call: JS.FunctionCall, ctx: ExecutionContext): Promise<J | undefined> {
78
+ const result = await super.visitFunctionCall(call, ctx) as JS.FunctionCall;
79
+ const callee = call.function?.element;
80
+ const args = call.arguments.elements;
81
+ const module = args[0]?.element;
82
+ const name = module?.kind === J.Kind.Literal ? (module as J.Literal).value : undefined;
83
+ if (!callee || !isIdentifier(callee) || callee.simpleName !== "import" ||
84
+ args.length !== 1 || !enzymeModule(name)) return result;
85
+ return this.report(result, name, "MODULE_REFERENCE",
86
+ "Trace the consumers of this dynamic Enzyme import before migrating them.", ctx);
87
+ }
88
+
89
+ override async visitFieldAccess(field: J.FieldAccess, ctx: ExecutionContext): Promise<J | undefined> {
90
+ const result = await super.visitFieldAccess(field, ctx) as J.FieldAccess;
91
+ if (!enzymeWrapper(TypedTree.getType(field.target))) return result;
92
+ const api = field.name.element.simpleName;
93
+ return this.report(result, api, "WRAPPER_FIELD",
94
+ "Preserve assertion cardinality and wrapper semantics when replacing this Enzyme field.", ctx);
95
+ }
96
+
97
+ override async visitIdentifier(identifier: J.Identifier, ctx: ExecutionContext): Promise<J | undefined> {
98
+ const result = await super.visitIdentifier(identifier, ctx) as J.Identifier;
99
+ if (!identifier.fieldType || !enzymeWrapper(identifier.type)) return result;
100
+ const parent = this.cursor.parentTree()?.value as J | undefined;
101
+ if (parent?.kind === J.Kind.NamedVariable &&
102
+ (parent as J.VariableDeclarations.NamedVariable).name === identifier) return result;
103
+ if (parent?.kind === J.Kind.MethodInvocation &&
104
+ (parent as J.MethodInvocation).select?.element === identifier) return result;
105
+ if (parent?.kind === J.Kind.FieldAccess && (parent as J.FieldAccess).target === identifier) return result;
106
+ return this.report(result, identifier.simpleName, "WRAPPER_ESCAPE",
107
+ "Trace this wrapper alias, argument, assignment, or return value before migrating its connected scope.", ctx);
108
+ }
109
+
110
+ private report<T extends J>(node: T, api: string, reason: string, suggestedAction: string, ctx: ExecutionContext): T {
111
+ usages.insertRow(ctx, {sourcePath: this.sourcePath, scope: enclosingScope(this.cursor), api,
112
+ status: "REVIEW", reason, suggestedAction});
113
+ return foundSearchResult(node, `Enzyme ${api}: ${reason}. See ${ENZYME_GUIDE}`);
114
+ }
115
+ }());
116
+ }
117
+ }