@openrewrite/recipes-react 0.15.0 → 0.17.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 (216) hide show
  1. package/dist/index.d.ts.map +1 -1
  2. package/dist/index.js +1 -0
  3. package/dist/index.js.map +1 -1
  4. package/dist/migration/cra-to-vite/add-vite-config.d.ts +7 -0
  5. package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -1
  6. package/dist/migration/cra-to-vite/add-vite-config.js +58 -1
  7. package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -1
  8. package/dist/migration/cra-to-vite/cra-file-gate.d.ts +3 -0
  9. package/dist/migration/cra-to-vite/cra-file-gate.d.ts.map +1 -0
  10. package/dist/migration/cra-to-vite/cra-file-gate.js +10 -0
  11. package/dist/migration/cra-to-vite/cra-file-gate.js.map +1 -0
  12. package/dist/migration/cra-to-vite/cra-runtime.d.ts +2 -0
  13. package/dist/migration/cra-to-vite/cra-runtime.d.ts.map +1 -0
  14. package/dist/migration/cra-to-vite/cra-runtime.js +24 -0
  15. package/dist/migration/cra-to-vite/cra-runtime.js.map +1 -0
  16. package/dist/migration/cra-to-vite/cra-script.d.ts +8 -0
  17. package/dist/migration/cra-to-vite/cra-script.d.ts.map +1 -0
  18. package/dist/migration/cra-to-vite/cra-script.js +82 -0
  19. package/dist/migration/cra-to-vite/cra-script.js.map +1 -0
  20. package/dist/migration/cra-to-vite/cra-to-vite.d.ts +2 -1
  21. package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -1
  22. package/dist/migration/cra-to-vite/cra-to-vite.js +23 -16
  23. package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -1
  24. package/dist/migration/cra-to-vite/cra-typecheck.d.ts +4 -0
  25. package/dist/migration/cra-to-vite/cra-typecheck.d.ts.map +1 -0
  26. package/dist/migration/cra-to-vite/cra-typecheck.js +35 -0
  27. package/dist/migration/cra-to-vite/cra-typecheck.js.map +1 -0
  28. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
  29. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +22 -29
  30. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
  31. package/dist/migration/cra-to-vite/index.d.ts +8 -2
  32. package/dist/migration/cra-to-vite/index.d.ts.map +1 -1
  33. package/dist/migration/cra-to-vite/index.js +17 -2
  34. package/dist/migration/cra-to-vite/index.js.map +1 -1
  35. package/dist/migration/cra-to-vite/migrate-cra-package.d.ts +17 -0
  36. package/dist/migration/cra-to-vite/migrate-cra-package.d.ts.map +1 -0
  37. package/dist/migration/cra-to-vite/migrate-cra-package.js +181 -0
  38. package/dist/migration/cra-to-vite/migrate-cra-package.js.map +1 -0
  39. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts +9 -0
  40. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts.map +1 -0
  41. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js +66 -0
  42. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js.map +1 -0
  43. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts +49 -0
  44. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts.map +1 -0
  45. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js +506 -0
  46. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js.map +1 -0
  47. package/dist/migration/cra-to-vite/move-public-index-html.d.ts +2 -0
  48. package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -1
  49. package/dist/migration/cra-to-vite/move-public-index-html.js +12 -7
  50. package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -1
  51. package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts +30 -0
  52. package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts.map +1 -0
  53. package/dist/migration/cra-to-vite/plan-cra-to-vite.js +428 -0
  54. package/dist/migration/cra-to-vite/plan-cra-to-vite.js.map +1 -0
  55. package/dist/migration/cra-to-vite/prepare-cra-package.d.ts +15 -0
  56. package/dist/migration/cra-to-vite/prepare-cra-package.d.ts.map +1 -0
  57. package/dist/migration/cra-to-vite/prepare-cra-package.js +100 -0
  58. package/dist/migration/cra-to-vite/prepare-cra-package.js.map +1 -0
  59. package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts +12 -0
  60. package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts.map +1 -0
  61. package/dist/migration/cra-to-vite/remove-cra-configuration.js +85 -0
  62. package/dist/migration/cra-to-vite/remove-cra-configuration.js.map +1 -0
  63. package/dist/migration/cra-to-vite/rename-jsx-files.d.ts +20 -0
  64. package/dist/migration/cra-to-vite/rename-jsx-files.d.ts.map +1 -0
  65. package/dist/migration/cra-to-vite/rename-jsx-files.js +220 -0
  66. package/dist/migration/cra-to-vite/rename-jsx-files.js.map +1 -0
  67. package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -1
  68. package/dist/migration/cra-to-vite/rename-process-env-react-app.js +6 -3
  69. package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -1
  70. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +1 -1
  71. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -1
  72. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +11 -4
  73. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -1
  74. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +47 -50
  75. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -1
  76. package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts +3 -0
  77. package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts.map +1 -0
  78. package/dist/migration/cra-to-vite/resolved-cra-dependency.js +42 -0
  79. package/dist/migration/cra-to-vite/resolved-cra-dependency.js.map +1 -0
  80. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +13 -0
  81. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -1
  82. package/dist/migration/cra-to-vite/scan-cra-projects.js +52 -4
  83. package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -1
  84. package/dist/migration/cra-to-vite/shared.d.ts +2 -15
  85. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
  86. package/dist/migration/cra-to-vite/shared.js +32 -130
  87. package/dist/migration/cra-to-vite/shared.js.map +1 -1
  88. package/dist/migration/cra-to-vite/svg-component.d.ts +5 -0
  89. package/dist/migration/cra-to-vite/svg-component.d.ts.map +1 -0
  90. package/dist/migration/cra-to-vite/svg-component.js +60 -0
  91. package/dist/migration/cra-to-vite/svg-component.js.map +1 -0
  92. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
  93. package/dist/migration/cra-to-vite/update-react-app-env-types.js +8 -2
  94. package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
  95. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +3 -2
  96. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -1
  97. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +28 -29
  98. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -1
  99. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts.map +1 -1
  100. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js +4 -13
  101. package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js.map +1 -1
  102. package/dist/react17/migrate-deprecated-lifecycles.js +1 -1
  103. package/dist/react17/migrate-deprecated-lifecycles.js.map +1 -1
  104. package/dist/react17/use-new-jsx-transform.d.ts.map +1 -1
  105. package/dist/react17/use-new-jsx-transform.js +30 -78
  106. package/dist/react17/use-new-jsx-transform.js.map +1 -1
  107. package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
  108. package/dist/react18/replace-reactdom-render.js +16 -8
  109. package/dist/react18/replace-reactdom-render.js.map +1 -1
  110. package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
  111. package/dist/react18/replace-unmount-component-at-node.js +62 -20
  112. package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
  113. package/dist/react19/replace-default-props.d.ts.map +1 -1
  114. package/dist/react19/replace-default-props.js +10 -13
  115. package/dist/react19/replace-default-props.js.map +1 -1
  116. package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
  117. package/dist/react19/replace-react-shallow-renderer.js +1 -6
  118. package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
  119. package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
  120. package/dist/refactoring/create-class-to-es6.js +4 -7
  121. package/dist/refactoring/create-class-to-es6.js.map +1 -1
  122. package/dist/refactoring/create-element-to-jsx.d.ts.map +1 -1
  123. package/dist/refactoring/create-element-to-jsx.js +3 -4
  124. package/dist/refactoring/create-element-to-jsx.js.map +1 -1
  125. package/dist/refactoring/prop-types-to-typescript.js +2 -3
  126. package/dist/refactoring/prop-types-to-typescript.js.map +1 -1
  127. package/dist/refactoring/pure-render-mixin.d.ts.map +1 -1
  128. package/dist/refactoring/pure-render-mixin.js +3 -6
  129. package/dist/refactoring/pure-render-mixin.js.map +1 -1
  130. package/dist/testing/enzyme-constant-strings.d.ts +12 -0
  131. package/dist/testing/enzyme-constant-strings.d.ts.map +1 -0
  132. package/dist/testing/enzyme-constant-strings.js +101 -0
  133. package/dist/testing/enzyme-constant-strings.js.map +1 -0
  134. package/dist/testing/enzyme-host-components.d.ts +14 -0
  135. package/dist/testing/enzyme-host-components.d.ts.map +1 -0
  136. package/dist/testing/enzyme-host-components.js +248 -0
  137. package/dist/testing/enzyme-host-components.js.map +1 -0
  138. package/dist/testing/enzyme-portals.d.ts +38 -0
  139. package/dist/testing/enzyme-portals.d.ts.map +1 -0
  140. package/dist/testing/enzyme-portals.js +226 -0
  141. package/dist/testing/enzyme-portals.js.map +1 -0
  142. package/dist/testing/enzyme-selector-names.d.ts +9 -0
  143. package/dist/testing/enzyme-selector-names.d.ts.map +1 -0
  144. package/dist/testing/enzyme-selector-names.js +50 -0
  145. package/dist/testing/enzyme-selector-names.js.map +1 -0
  146. package/dist/testing/enzyme-to-react-testing-library.d.ts +80 -12
  147. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  148. package/dist/testing/enzyme-to-react-testing-library.js +447 -135
  149. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  150. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  151. package/dist/testing/enzyme-usage.js +27 -4
  152. package/dist/testing/enzyme-usage.js.map +1 -1
  153. package/dist/testing/enzyme-wrapper-scope.d.ts +23 -8
  154. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  155. package/dist/testing/enzyme-wrapper-scope.js +291 -169
  156. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  157. package/dist/util/java-recipe-proxy.d.ts +16 -0
  158. package/dist/util/java-recipe-proxy.d.ts.map +1 -0
  159. package/dist/util/java-recipe-proxy.js +85 -0
  160. package/dist/util/java-recipe-proxy.js.map +1 -0
  161. package/dist/util/module-imports.d.ts +13 -0
  162. package/dist/util/module-imports.d.ts.map +1 -0
  163. package/dist/util/module-imports.js +60 -0
  164. package/dist/util/module-imports.js.map +1 -0
  165. package/dist/util/react-class.d.ts +1 -0
  166. package/dist/util/react-class.d.ts.map +1 -1
  167. package/dist/util/react-class.js +3 -2
  168. package/dist/util/react-class.js.map +1 -1
  169. package/package.json +4 -4
  170. package/src/index.ts +2 -1
  171. package/src/migration/cra-to-vite/add-vite-config.ts +53 -1
  172. package/src/migration/cra-to-vite/cra-file-gate.ts +8 -0
  173. package/src/migration/cra-to-vite/cra-runtime.ts +16 -0
  174. package/src/migration/cra-to-vite/cra-script.ts +61 -0
  175. package/src/migration/cra-to-vite/cra-to-vite.ts +25 -36
  176. package/src/migration/cra-to-vite/cra-typecheck.ts +33 -0
  177. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +23 -28
  178. package/src/migration/cra-to-vite/index.ts +10 -2
  179. package/src/migration/cra-to-vite/migrate-cra-package.ts +127 -0
  180. package/src/migration/cra-to-vite/migrate-cra-svg-imports.ts +41 -0
  181. package/src/migration/cra-to-vite/migrate-cra-tests-to-vitest.ts +376 -0
  182. package/src/migration/cra-to-vite/move-public-index-html.ts +12 -7
  183. package/src/migration/cra-to-vite/plan-cra-to-vite.ts +283 -0
  184. package/src/migration/cra-to-vite/prepare-cra-package.ts +86 -0
  185. package/src/migration/cra-to-vite/remove-cra-configuration.ts +64 -0
  186. package/src/migration/cra-to-vite/rename-jsx-files.ts +155 -0
  187. package/src/migration/cra-to-vite/rename-process-env-react-app.ts +6 -3
  188. package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +1 -1
  189. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +48 -54
  190. package/src/migration/cra-to-vite/resolved-cra-dependency.ts +41 -0
  191. package/src/migration/cra-to-vite/scan-cra-projects.ts +57 -6
  192. package/src/migration/cra-to-vite/shared.ts +35 -146
  193. package/src/migration/cra-to-vite/svg-component.ts +39 -0
  194. package/src/migration/cra-to-vite/update-react-app-env-types.ts +11 -4
  195. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +30 -41
  196. package/src/migration/cra-to-vite/update-tsconfig-for-vite.ts +6 -13
  197. package/src/react17/migrate-deprecated-lifecycles.ts +2 -2
  198. package/src/react17/use-new-jsx-transform.ts +30 -72
  199. package/src/react18/replace-reactdom-render.ts +17 -8
  200. package/src/react18/replace-unmount-component-at-node.ts +78 -32
  201. package/src/react19/replace-default-props.ts +11 -15
  202. package/src/react19/replace-react-shallow-renderer.ts +2 -7
  203. package/src/refactoring/create-class-to-es6.ts +6 -9
  204. package/src/refactoring/create-element-to-jsx.ts +4 -6
  205. package/src/refactoring/prop-types-to-typescript.ts +4 -4
  206. package/src/refactoring/pure-render-mixin.ts +4 -7
  207. package/src/testing/enzyme-constant-strings.ts +95 -0
  208. package/src/testing/enzyme-host-components.ts +287 -0
  209. package/src/testing/enzyme-portals.ts +279 -0
  210. package/src/testing/enzyme-selector-names.ts +59 -0
  211. package/src/testing/enzyme-to-react-testing-library.ts +584 -140
  212. package/src/testing/enzyme-usage.ts +29 -4
  213. package/src/testing/enzyme-wrapper-scope.ts +309 -151
  214. package/src/util/java-recipe-proxy.ts +81 -0
  215. package/src/util/module-imports.ts +60 -0
  216. package/src/util/react-class.ts +2 -1
@@ -15,9 +15,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
15
15
  });
16
16
  };
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.EnzymeToReactTestingLibrary = void 0;
18
+ exports.EnzymeSnapshotsToReactTestingLibrary = exports.EnzymeToReactTestingLibrary = exports.AddTestingLibraryDom18 = exports.AddTestingLibraryReact18 = exports.AddTestingLibraryReact = void 0;
19
+ exports.lockfileScopes = lockfileScopes;
20
+ exports.rtlLanded = rtlLanded;
19
21
  exports.supportsResolvingGate = supportsResolvingGate;
20
22
  exports.rewriteVersion = rewriteVersion;
23
+ exports.injectsRootStyles = injectsRootStyles;
21
24
  exports.reactMajor = reactMajor;
22
25
  exports.simulatesEvents = simulatesEvents;
23
26
  const rewrite_1 = require("@openrewrite/rewrite");
@@ -29,14 +32,152 @@ const fs_1 = require("fs");
29
32
  const path_1 = require("path");
30
33
  const semver_1 = require("semver");
31
34
  const find_enzyme_usage_1 = require("../search/find-enzyme-usage");
35
+ const java_recipe_proxy_1 = require("../util/java-recipe-proxy");
36
+ const module_imports_1 = require("../util/module-imports");
32
37
  const enzyme_usage_1 = require("./enzyme-usage");
38
+ const enzyme_host_components_1 = require("./enzyme-host-components");
39
+ const enzyme_portals_1 = require("./enzyme-portals");
40
+ const enzyme_constant_strings_1 = require("./enzyme-constant-strings");
41
+ const enzyme_selector_names_1 = require("./enzyme-selector-names");
33
42
  const enzyme_wrapper_scope_1 = require("./enzyme-wrapper-scope");
34
43
  const RTL = "@testing-library/react";
35
44
  const REACT_RANGE = ">=16.9.0 <18";
45
+ const REACT_18_RANGE = ">=18.0.0 <19";
46
+ const resolvingReact = (range) => [`react@${range}`, `react-dom@${range}`];
36
47
  const RTL_ADDITION = {
37
48
  packageName: RTL, version: "^12.1.5", scope: "devDependencies",
38
- onlyIfDeclaring: ["enzyme"], onlyIfResolving: [`react@${REACT_RANGE}`, `react-dom@${REACT_RANGE}`]
49
+ onlyIfDeclaring: ["enzyme"], onlyIfResolving: resolvingReact(REACT_RANGE)
39
50
  };
51
+ const RTL_18_ADDITION = Object.assign(Object.assign({}, RTL_ADDITION), { version: "^16.3.0", onlyIfResolving: resolvingReact(REACT_18_RANGE) });
52
+ const DOM = "@testing-library/dom";
53
+ const DOM_18_ADDITION = Object.assign(Object.assign({}, RTL_18_ADDITION), { packageName: DOM, version: "^10.4.0" });
54
+ function packageRoot(manifestPath) {
55
+ return manifestPath.slice(0, -"package.json".length);
56
+ }
57
+ function lockfileScopes(manifests) {
58
+ var _a, _b;
59
+ const scopes = new Map();
60
+ for (const manifest of manifests) {
61
+ const root = packageRoot(manifest.sourcePath);
62
+ if (!scopes.has(manifest.sourcePath))
63
+ scopes.set(manifest.sourcePath, root);
64
+ for (const member of (_b = (_a = (0, javascript_1.findNodeResolutionResult)(manifest)) === null || _a === void 0 ? void 0 : _a.workspacePackagePaths) !== null && _b !== void 0 ? _b : []) {
65
+ scopes.set(member.replace(/^\.\//, ""), root);
66
+ }
67
+ }
68
+ return scopes;
69
+ }
70
+ class EnzymeTestDependency extends java_recipe_proxy_1.JavaDependencyRecipe {
71
+ constructor(addition, forecast) {
72
+ super("org.openrewrite.javascript.AddDependency", addition);
73
+ this.addition = addition;
74
+ this.forecast = forecast;
75
+ this.landed = new Set();
76
+ this.manifests = [];
77
+ this.held = [];
78
+ }
79
+ initialValue() {
80
+ this.landed.clear();
81
+ this.manifests.length = 0;
82
+ this.held.length = 0;
83
+ return super.initialValue();
84
+ }
85
+ candidates() {
86
+ return new Set(this.manifests.map(manifest => packageRoot(manifest.sourcePath)));
87
+ }
88
+ scanned(manifest) {
89
+ if (manifest.kind !== json_1.Json.Kind.Document || !/(^|\/)package\.json$/.test(manifest.sourcePath))
90
+ return true;
91
+ if (!this.admits(manifest))
92
+ return false;
93
+ if (this.addition.onlyIfDeclaring.some(name => declares(manifest, name)))
94
+ this.manifests.push(manifest);
95
+ this.held.push(manifest);
96
+ return false;
97
+ }
98
+ admits(_manifest) {
99
+ return true;
100
+ }
101
+ generate(acc, ctx) {
102
+ const _super = Object.create(null, {
103
+ generate: { get: () => super.generate }
104
+ });
105
+ return __awaiter(this, void 0, void 0, function* () {
106
+ var _a, _b;
107
+ const converting = yield ((_b = (_a = this.forecast).converting) === null || _b === void 0 ? void 0 : _b.call(_a));
108
+ const scopes = lockfileScopes(this.held);
109
+ const forwarded = new Set(this.held.filter(manifest => {
110
+ var _a;
111
+ const scope = (_a = scopes.get(manifest.sourcePath)) !== null && _a !== void 0 ? _a : packageRoot(manifest.sourcePath);
112
+ return !converting || [...converting].some(source => source.startsWith(scope));
113
+ }));
114
+ const scanner = yield this.java.scanner(acc);
115
+ for (const manifest of forwarded)
116
+ yield scanner.visit(manifest, ctx);
117
+ const kept = this.manifests.filter(manifest => forwarded.has(manifest));
118
+ this.manifests.length = 0;
119
+ this.manifests.push(...kept);
120
+ const generated = yield _super.generate.call(this, acc, ctx);
121
+ const editor = yield this.java.editorWithData(acc);
122
+ for (const manifest of this.manifests) {
123
+ const edited = yield editor.visit(manifest, ctx);
124
+ if (edited && edited !== manifest && declares(edited, this.addition.packageName))
125
+ this.landed.add(manifest.sourcePath.slice(0, -"package.json".length));
126
+ }
127
+ return generated;
128
+ });
129
+ }
130
+ }
131
+ class AddTestingLibraryReact extends EnzymeTestDependency {
132
+ constructor(forecast = {}) {
133
+ super(RTL_ADDITION, forecast);
134
+ this.name = "org.openrewrite.react.migrate.add-testing-library-react";
135
+ this.displayName = "Add `@testing-library/react` where Enzyme tests are migrated";
136
+ this.description = "Adds `@testing-library/react` 12 as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 16.9 to 17.";
137
+ }
138
+ }
139
+ exports.AddTestingLibraryReact = AddTestingLibraryReact;
140
+ class AddTestingLibraryReact18 extends EnzymeTestDependency {
141
+ constructor(forecast = {}) {
142
+ super(RTL_18_ADDITION, forecast);
143
+ this.name = "org.openrewrite.react.migrate.add-testing-library-react-18";
144
+ this.displayName = "Add `@testing-library/react` 16 where Enzyme tests on React 18 are migrated";
145
+ this.description = "Adds `@testing-library/react` 16 as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 18.";
146
+ }
147
+ }
148
+ exports.AddTestingLibraryReact18 = AddTestingLibraryReact18;
149
+ class AddTestingLibraryDom18 extends EnzymeTestDependency {
150
+ constructor(forecast = {}) {
151
+ super(DOM_18_ADDITION, forecast);
152
+ this.name = "org.openrewrite.react.migrate.add-testing-library-dom-18";
153
+ this.displayName = "Add `@testing-library/dom` where Enzyme tests on React 18 are migrated";
154
+ this.description = "Adds `@testing-library/dom` 10, the peer of `@testing-library/react` 16, as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 18.";
155
+ }
156
+ admits(manifest) {
157
+ var _a, _b;
158
+ const rtl = declaration(manifest, RTL);
159
+ if (rtl === undefined || !declares(manifest, enzyme_usage_1.ENZYME) || declares(manifest, DOM))
160
+ return true;
161
+ const resolved = (_b = (_a = rtl.resolved) === null || _a === void 0 ? void 0 : _a.version.match(/^(\d+)\./)) === null || _b === void 0 ? void 0 : _b[1];
162
+ if (resolved !== undefined)
163
+ return Number(resolved) === 16;
164
+ const version = declaredVersion(rtl.versionConstraint);
165
+ return version !== undefined && version !== "unsupported" && version.major === 16;
166
+ }
167
+ }
168
+ exports.AddTestingLibraryDom18 = AddTestingLibraryDom18;
169
+ function rtlLanded(rtl, rtl18, dom18) {
170
+ return new Set([...rtl, ...[...rtl18].filter(root => dom18.has(root))]);
171
+ }
172
+ function declaration(manifest, name) {
173
+ var _a, _b, _c, _d;
174
+ const resolution = (0, javascript_1.findNodeResolutionResult)(manifest);
175
+ return [...(_a = resolution === null || resolution === void 0 ? void 0 : resolution.dependencies) !== null && _a !== void 0 ? _a : [], ...(_b = resolution === null || resolution === void 0 ? void 0 : resolution.devDependencies) !== null && _b !== void 0 ? _b : [],
176
+ ...(_c = resolution === null || resolution === void 0 ? void 0 : resolution.optionalDependencies) !== null && _c !== void 0 ? _c : [], ...(_d = resolution === null || resolution === void 0 ? void 0 : resolution.peerDependencies) !== null && _d !== void 0 ? _d : []].find(dep => dep.name === name);
177
+ }
178
+ function declares(manifest, name) {
179
+ return declaration(manifest, name) !== undefined;
180
+ }
40
181
  const ADDS_RTL = (() => {
41
182
  try {
42
183
  return supportsResolvingGate(rewriteVersion(require.resolve("@openrewrite/rewrite"), require.cache));
@@ -67,30 +208,68 @@ function rewriteVersion(resolved, cache) {
67
208
  }
68
209
  return undefined;
69
210
  }
70
- function reactMajor(packages, sourcePath, addsRtl = false) {
71
- return compatibility(packages, sourcePath, addsRtl).react;
211
+ function documentAt(cursor) {
212
+ const scope = (0, javascript_1.scopeOf)(cursor);
213
+ if (!scope.declares("document", "value"))
214
+ return "document";
215
+ return scope.declares("globalThis", "value") ? undefined : "globalThis.document";
216
+ }
217
+ function formattedBy(cu, style) {
218
+ return __awaiter(this, void 0, void 0, function* () {
219
+ const detector = javascript_1.Autodetect.detector();
220
+ yield detector.sampleJavaScript(cu);
221
+ const detected = detector.getTabsAndIndentsStyle();
222
+ const useTabs = style.config.useTabs === true;
223
+ const tabWidth = typeof style.config.tabWidth === "number" ? style.config.tabWidth : 2;
224
+ return detected.useTabCharacter === useTabs && (useTabs || detected.indentSize === tabWidth);
225
+ });
226
+ }
227
+ function renderOptions(document) {
228
+ return `{container: ${document}.createElement('div')}`;
229
+ }
230
+ const ROOT_STYLES = new Map([["@ant-design/icons", ">=5.1.1"]]);
231
+ function injectsRootStyles(packages, sourcePath) {
232
+ return [...packages.entries()].some(([root, declarations]) => sourcePath.startsWith(root) && declarations.rootStyles);
233
+ }
234
+ const CONTAINER_READS = new Set(["text", "rootHtml", "snapshot"]);
235
+ const READS = {
236
+ mount: { simulate: true, html: true, props: () => true },
237
+ shallow: { simulate: false, html: false, props: enzyme_host_components_1.propsRenderHostElements }
238
+ };
239
+ function reactMajor(packages, sourcePath, landed = new Set()) {
240
+ return compatibility(packages, sourcePath, landed).react;
72
241
  }
73
- function simulatesEvents(packages, sourcePath, addsRtl = false) {
74
- const { react, rtl } = compatibility(packages, sourcePath, addsRtl);
75
- return react === 17 && rtl >= 11;
242
+ const HOVER_EVENTS = new Set(["mouseEnter", "mouseLeave", "mouseOver", "mouseOut"]);
243
+ function simulatesEvents(packages, sourcePath, landed = new Set()) {
244
+ const { react, rtl } = compatibility(packages, sourcePath, landed);
245
+ if (react >= 17 && rtl >= 11)
246
+ return { events: enzyme_wrapper_scope_1.SIMULATED_EVENTS, attached: false };
247
+ if (react === 16 && rtl >= 10)
248
+ return { events: new Set([...enzyme_wrapper_scope_1.SIMULATED_EVENTS].filter(event => !HOVER_EVENTS.has(event))), attached: true };
249
+ return { events: new Set(), attached: false };
76
250
  }
77
- function compatibility(packages, sourcePath, addsRtl) {
251
+ function compatibility(packages, sourcePath, landed) {
78
252
  var _a;
79
253
  const roots = [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
80
254
  const declared = (name, from = roots) => from.map(root => packages.get(root)[name]).find(version => version !== undefined);
81
255
  const supportedReact = (version) => typeof version === "object" &&
82
- (version.major === 17 || (version.major === 16 && version.minor !== undefined && version.minor >= 9));
256
+ (version.major === 17 || version.major === 18 || (version.major === 16 && version.minor !== undefined && version.minor >= 9));
83
257
  const react = declared("react");
84
258
  const rtl = declared("rtl");
85
259
  const enzyme = roots.findIndex(root => packages.get(root).enzyme);
86
- const added = addsRtl && rtl === undefined && enzyme >= 0 && packages.get(roots[enzyme]).lockfileRegenerated &&
87
- supportedReact(declared("react", roots.slice(enzyme))) && supportedReact(declared("reactDom", roots.slice(enzyme)));
260
+ const enzymeReact = enzyme >= 0 ? declared("react", roots.slice(enzyme)) : undefined;
261
+ const added = rtl === undefined && enzyme >= 0 && landed.has(roots[enzyme]) &&
262
+ supportedReact(enzymeReact) && supportedReact(declared("reactDom", roots.slice(enzyme)));
88
263
  const rtlRoot = added ? enzyme : roots.findIndex(root => packages.get(root).rtl !== undefined);
89
264
  const reactDom = (_a = declared("reactDom", roots.slice(Math.max(rtlRoot, 0)))) !== null && _a !== void 0 ? _a : declared("reactDom");
90
- const rtlMajor = added ? 12 : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 12 ? rtl.major : 0;
91
- const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major && rtlMajor > 0;
265
+ const rtlMajor = added ? (enzymeReact.major >= 18 ? 16 : 12) : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 16 ? rtl.major : 0;
266
+ const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major &&
267
+ rtlMajor > 0 && rtlSupports(rtlMajor, react.major);
92
268
  return { react: compatible ? react.major : 0, rtl: rtlMajor };
93
269
  }
270
+ function rtlSupports(rtl, react) {
271
+ return react <= 17 ? rtl <= 12 : rtl === 16;
272
+ }
94
273
  function declaredVersion(version) {
95
274
  var _a;
96
275
  if (version === undefined)
@@ -105,18 +284,40 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
105
284
  super(options);
106
285
  this.name = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
107
286
  this.displayName = "Migrate Enzyme to React Testing Library";
108
- this.description = "Migrates Enzyme `mount` wrappers whose every use is a supported DOM read or event (`find(selector).length`, `.exists()`, `.text()`, `.html()`, `.hasClass()`, positions through `.at(n)`, `.first()`, `.last()`, the wrapper's `text()` and `exists(selector)`, found nodes as a `toHaveLength` subject, `setProps` as a rerender of the cloned element, and on React 17 `simulate` with common mouse, keyboard, focus, form, and touch events, including `nativeEvent` mocks) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16.9+/17 with RTL 10 to 12, adding RTL 12 where it is missing. Selectors are limited to HTML or SVG tag, class, ID, and pass-through attribute compounds and their descendant combinations. Reports remaining Enzyme usages for manual review. Requires an existing DOM test environment; shared wrappers, props, and snapshots are left for review.";
287
+ this.description = "Migrates Enzyme `mount` wrappers whose every use is a supported DOM read or event (`find(selector).length`, `.exists()`, `.text()`, `.html()`, `.hasClass()`, positions through `.at(n)`, `.first()`, `.last()`, the wrapper's `text()` and `exists(selector)`, found nodes as a `toHaveLength` subject, `setProps` as a rerender of the cloned element, and `simulate` with common mouse, keyboard, focus, form, and touch events, including `nativeEvent` mocks, on React 17 and 18 and, without the hover events and in a render attached to the document, on React 16.9+) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16.9+/17 with RTL 10 to 12 or React 18 with RTL 16, adding RTL 12, or RTL 16 with its peer `@testing-library/dom` 10, where it is missing. Converts `shallow` wrappers the same way, without `simulate` or `html()`, where the component is imported from a source in the repository that creates host elements only and runs no effects, so a full render produces the DOM the shallow render does. Selectors are limited to HTML or SVG tag, class, ID, and pass-through attribute compounds and their descendant combinations. Reports remaining Enzyme usages for manual review. Requires an existing DOM test environment; shared wrappers, props, snapshots, and shallow rendering of other components are left for review.";
288
+ this.forecast = {};
289
+ this.tests = [];
290
+ this.dependencySteps = ADDS_RTL ? { rtl: new AddTestingLibraryReact(this.forecast), rtl18: new AddTestingLibraryReact18(this.forecast),
291
+ dom18: new AddTestingLibraryDom18(this.forecast) } : undefined;
292
+ this.snapshots = false;
109
293
  this.usages = new rewrite_1.DataTable(enzyme_usage_1.ENZYME_USAGE_TABLE, "Enzyme migration inventory", "Remaining Enzyme usages and migration actions. Module rows include references whose call types may be unavailable; they are not counts of test cases.", enzyme_usage_1.EnzymeUsageRow);
110
294
  }
111
295
  initialValue() {
112
- return new Map();
296
+ this.tests.length = 0;
297
+ return { packages: new Map(), components: new Map(), modules: new Map(), names: new Map() };
113
298
  }
114
- scanner(packages) {
299
+ scanner(scanned) {
115
300
  return __awaiter(this, void 0, void 0, function* () {
116
- return new class extends json_1.JsonVisitor {
301
+ const steps = this.dependencySteps;
302
+ const tests = this.tests;
303
+ let converting;
304
+ this.forecast.converting = steps && (() => converting !== null && converting !== void 0 ? converting : (converting = this.dryRun(scanned, rtlLanded(steps.rtl.candidates(), steps.rtl18.candidates(), steps.dom18.candidates()))));
305
+ const sources = new class extends javascript_1.JavaScriptVisitor {
306
+ visitJsCompilationUnit(cu) {
307
+ return __awaiter(this, void 0, void 0, function* () {
308
+ scanned.components.set(cu.sourcePath, (0, enzyme_host_components_1.hostComponentExports)(cu));
309
+ scanned.modules.set(cu.sourcePath, (0, enzyme_portals_1.moduleFacts)(cu));
310
+ scanned.names.set(cu.sourcePath, (0, enzyme_selector_names_1.selectorNames)(cu));
311
+ if ((0, module_imports_1.importBindings)(cu).some(({ module }) => module === enzyme_usage_1.ENZYME))
312
+ tests.push(cu);
313
+ return cu;
314
+ });
315
+ }
316
+ }();
317
+ const manifests = new class extends json_1.JsonVisitor {
117
318
  visitDocument(doc, ctx) {
118
319
  return __awaiter(this, void 0, void 0, function* () {
119
- var _a, _b, _c, _d;
320
+ var _a, _b, _c, _d, _e;
120
321
  if (!/(^|\/)package\.json$/.test(doc.sourcePath))
121
322
  return doc;
122
323
  const resolution = (0, javascript_1.findNodeResolutionResult)(doc);
@@ -131,53 +332,111 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
131
332
  return resolved.version;
132
333
  return (_a = dependencies.find(dep => dep.name === name)) === null || _a === void 0 ? void 0 : _a.versionConstraint;
133
334
  };
134
- packages.set(doc.sourcePath.slice(0, -"package.json".length), {
335
+ scanned.packages.set(doc.sourcePath.slice(0, -"package.json".length), {
135
336
  react: declaredVersion(version("react")),
136
337
  reactDom: declaredVersion(version("react-dom")),
137
338
  rtl: declaredVersion(version(RTL)),
138
339
  enzyme: dependencies.some(dep => dep.name === "enzyme"),
139
- lockfileRegenerated: (resolution === null || resolution === void 0 ? void 0 : resolution.packageManager) !== "Pnpm" && (resolution === null || resolution === void 0 ? void 0 : resolution.packageManager) !== "Bun"
340
+ dependencies: new Set(dependencies.map(dep => dep.name)),
341
+ rootStyles: ((_e = resolution === null || resolution === void 0 ? void 0 : resolution.resolvedDependencies) !== null && _e !== void 0 ? _e : []).some(dep => {
342
+ const range = ROOT_STYLES.get(dep.name);
343
+ return range !== undefined && (0, semver_1.valid)(dep.version) !== null && (0, semver_1.satisfies)(dep.version, range);
344
+ })
140
345
  });
141
346
  return doc;
142
347
  });
143
348
  }
144
349
  }();
350
+ const scan = new class extends rewrite_1.TreeVisitor {
351
+ isAcceptable(sourceFile) {
352
+ return __awaiter(this, void 0, void 0, function* () {
353
+ return (yield manifests.isAcceptable(sourceFile)) || (yield sources.isAcceptable(sourceFile));
354
+ });
355
+ }
356
+ visit(tree, ctx, parent) {
357
+ return __awaiter(this, void 0, void 0, function* () {
358
+ if (tree.kind === json_1.Json.Kind.Document)
359
+ return yield manifests.visit(tree, ctx, parent);
360
+ return tree.kind === javascript_1.JS.Kind.CompilationUnit ? yield sources.visit(tree, ctx, parent) : tree;
361
+ });
362
+ }
363
+ }();
364
+ return (0, rewrite_1.check)((0, rewrite_1.or)((0, java_recipe_proxy_1.treesOfType)("org.openrewrite.json.tree.Json"), (0, java_recipe_proxy_1.treesOfType)("org.openrewrite.javascript.tree.JS")), scan);
365
+ });
366
+ }
367
+ editorWithData(scanned) {
368
+ return __awaiter(this, void 0, void 0, function* () {
369
+ return this.conversionEditor(scanned);
145
370
  });
146
371
  }
147
- editorWithData(packages) {
372
+ dryRun(scanned, landed) {
373
+ return __awaiter(this, void 0, void 0, function* () {
374
+ const dry = { landed, converted: new Set() };
375
+ const editor = yield this.conversionEditor(scanned, dry);
376
+ const ctx = new rewrite_1.ExecutionContext();
377
+ for (const cu of this.tests)
378
+ yield editor.visit(cu, ctx);
379
+ this.tests.length = 0;
380
+ return dry.converted;
381
+ });
382
+ }
383
+ conversionEditor(scanned, dry) {
148
384
  return __awaiter(this, void 0, void 0, function* () {
149
385
  const jsx = (0, javascript_1.capture)({ name: "element", constraint: node => node.kind !== javascript_1.JS.Kind.Spread });
150
- const selector = (0, javascript_1.capture)({ name: "selector", constraint: node => (0, enzyme_wrapper_scope_1.selectorLiteral)(node) });
151
- const before = { lenientTypeMatching: false, context: ['import {mount} from "enzyme";'], dependencies: { "@types/enzyme": "3.10.19", "@types/react": "16.14.62" } };
386
+ const hostNames = (names) => (0, enzyme_selector_names_1.hostOnlyNames)(names, scanned.names);
387
+ const selector = (0, javascript_1.capture)({ name: "selector", constraint: node => (0, enzyme_wrapper_scope_1.selectorLiteral)(node, hostNames) });
152
388
  const after = { context: [`import {render} from "${RTL}";`], dependencies: { [RTL]: "12.1.5", "@types/react": "16.14.62" } };
153
- const lengthRule = (0, javascript_1.rewrite)(() => ({
154
- before: (0, javascript_1.pattern) `mount(${jsx}).find(${selector}).length`.configure(before),
155
- after: (0, javascript_1.template) `render(${jsx}, {container: globalThis.document.createElement('div')}).container.querySelectorAll(${selector}).length`.configure(after)
156
- }));
157
- const existsRule = (0, javascript_1.rewrite)(() => ({
158
- before: (0, javascript_1.pattern) `mount(${jsx}).find(${selector}).exists()`.configure(before),
159
- after: (0, javascript_1.template) `(render(${jsx}, {container: globalThis.document.createElement('div')}).container.querySelectorAll(${selector}).length > 0)`.configure(after)
160
- }));
161
- const existsArgumentRule = (0, javascript_1.rewrite)(() => ({
162
- before: (0, javascript_1.pattern) `mount(${jsx}).find(${selector}).exists()`.configure(before),
163
- after: (0, javascript_1.template) `render(${jsx}, {container: globalThis.document.createElement('div')}).container.querySelectorAll(${selector}).length > 0`.configure(after)
164
- }));
165
- const mountPattern = (0, javascript_1.pattern) `mount(${jsx})`.configure(before);
166
- const mountRule = (0, javascript_1.rewrite)(() => ({
167
- before: mountPattern,
168
- after: (0, javascript_1.template) `render(${jsx}, {container: globalThis.document.createElement('div')})`.configure(after)
169
- }));
389
+ const patterns = (api) => {
390
+ const before = { lenientTypeMatching: false, context: [`import {${api}} from "enzyme";`], dependencies: { "@types/enzyme": "3.10.19", "@types/react": "16.14.62" } };
391
+ return {
392
+ render: (0, javascript_1.pattern) `${(0, javascript_1.raw)(api)}(${jsx})`.configure(before),
393
+ length: (0, javascript_1.pattern) `${(0, javascript_1.raw)(api)}(${jsx}).find(${selector}).length`.configure(before),
394
+ exists: (0, javascript_1.pattern) `${(0, javascript_1.raw)(api)}(${jsx}).find(${selector}).exists()`.configure(before)
395
+ };
396
+ };
397
+ const renderPatterns = { mount: patterns("mount"), shallow: patterns("shallow") };
398
+ const renderRules = (document, api) => {
399
+ const options = (0, javascript_1.raw)(renderOptions(document));
400
+ const from = renderPatterns[api];
401
+ return {
402
+ length: (0, javascript_1.rewrite)(() => ({
403
+ before: from.length,
404
+ after: (0, javascript_1.template) `render(${jsx}, ${options}).container.querySelectorAll(${selector}).length`.configure(after)
405
+ })),
406
+ exists: (0, javascript_1.rewrite)(() => ({
407
+ before: from.exists,
408
+ after: (0, javascript_1.template) `render(${jsx}, ${options}).container.querySelectorAll(${selector}).length > 0`.configure(after)
409
+ })),
410
+ mount: (0, javascript_1.rewrite)(() => ({
411
+ before: from.render,
412
+ after: (0, javascript_1.template) `render(${jsx}, ${options})`.configure(after)
413
+ })),
414
+ attachedMount: (0, javascript_1.rewrite)(() => ({
415
+ before: from.render,
416
+ after: (0, javascript_1.template) `render(${jsx})`.configure(after)
417
+ }))
418
+ };
419
+ };
420
+ const rules = {
421
+ "document": { mount: renderRules("document", "mount"), shallow: renderRules("document", "shallow") },
422
+ "globalThis.document": { mount: renderRules("globalThis.document", "mount"), shallow: renderRules("globalThis.document", "shallow") }
423
+ };
170
424
  const usages = this.usages;
425
+ const steps = this.dependencySteps;
171
426
  const untaggedPositions = this.untaggedSelectorPositions !== false;
172
- return (0, rewrite_1.check)((0, rewrite_1.and)((0, rewrite_1.not)((0, javascript_1.isVendoredOrBundled)()), (0, javascript_1.usesMethod)("enzyme mount(..)")), new class extends javascript_1.JavaScriptVisitor {
427
+ const snapshots = this.snapshots;
428
+ return (0, rewrite_1.check)((0, rewrite_1.and)((0, rewrite_1.not)((0, javascript_1.isVendoredOrBundled)()), (0, rewrite_1.or)((0, javascript_1.usesMethod)("enzyme mount(..)"), (0, javascript_1.usesMethod)("enzyme shallow(..)"))), new class extends javascript_1.JavaScriptVisitor {
173
429
  constructor() {
174
430
  super(...arguments);
175
431
  this.enabled = false;
176
432
  this.reactMajor = 0;
177
- this.events = false;
433
+ this.events = { events: new Set(), attached: false };
434
+ this.rootStyles = false;
178
435
  this.typescript = false;
179
436
  this.sourcePath = "";
180
- this.mounts = new Set();
437
+ this.mounts = new Map();
438
+ this.imports = new Map();
439
+ this.importedNames = new Set();
181
440
  this.uses = new Map();
182
441
  this.removedStatements = new Set();
183
442
  this.unmounts = new Set();
@@ -187,6 +446,7 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
187
446
  this.hoists = new Map();
188
447
  this.hoistedMounts = new Map();
189
448
  this.names = new Set();
449
+ this.portals = new Set();
190
450
  this.rows = [];
191
451
  this.prettier = false;
192
452
  this.printWidth = 80;
@@ -203,17 +463,38 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
203
463
  this.rows.length = 0;
204
464
  this.names = (0, javascript_1.namesUsedIn)(cu);
205
465
  const prettierStyle = (0, rewrite_1.findMarker)(cu, javascript_1.StyleKind.PrettierStyle);
206
- this.prettier = prettierStyle !== undefined;
466
+ this.prettier = prettierStyle !== undefined && !prettierStyle.ignored && (yield formattedBy(cu, prettierStyle));
207
467
  this.printWidth = typeof (prettierStyle === null || prettierStyle === void 0 ? void 0 : prettierStyle.config.printWidth) === "number" ? prettierStyle.config.printWidth : 80;
208
- this.reactMajor = reactMajor(packages, cu.sourcePath, ADDS_RTL);
209
- this.events = simulatesEvents(packages, cu.sourcePath, ADDS_RTL);
210
- this.typescript = /\.[cm]?tsx?$/.test(cu.sourcePath);
468
+ const landed = dry ? dry.landed : steps ? rtlLanded(steps.rtl.landed, steps.rtl18.landed, steps.dom18.landed) : undefined;
469
+ this.reactMajor = reactMajor(scanned.packages, cu.sourcePath, landed);
470
+ this.events = simulatesEvents(scanned.packages, cu.sourcePath, landed);
471
+ this.rootStyles = injectsRootStyles(scanned.packages, cu.sourcePath);
472
+ this.typescript = (0, javascript_1.isTypeScript)(cu);
211
473
  this.enabled = this.reactMajor > 0 && (0, javascript_1.moduleBindings)(this).moduleSystem === "esm";
212
- if (!this.enabled || this.names.has("globalThis"))
474
+ if (!this.enabled)
213
475
  return cu;
214
- const visited = yield _super.visitJsCompilationUnit.call(this, cu, ctx);
215
- this.rows.forEach(row => usages.insertRow(ctx, row));
216
- return visited;
476
+ this.imports = (0, enzyme_host_components_1.relativeImports)(cu, scanned.components);
477
+ this.importedNames = (0, enzyme_host_components_1.importedNames)(cu);
478
+ const foreign = prettierStyle !== undefined && !this.prettier;
479
+ const visiting = foreign ? (0, mutative_1.create)(cu, draft => {
480
+ draft.markers.markers = draft.markers.markers.filter(marker => marker.kind !== javascript_1.StyleKind.PrettierStyle);
481
+ }) : cu;
482
+ if (foreign)
483
+ this.cursor = new rewrite_1.Cursor(visiting, this.cursor.parent);
484
+ this.cu = cu;
485
+ this.portals.clear();
486
+ const visited = yield _super.visitJsCompilationUnit.call(this, visiting, ctx);
487
+ if (dry) {
488
+ if (this.rows.some(row => row.status === "CONVERTED"))
489
+ dry.converted.add(cu.sourcePath);
490
+ }
491
+ else
492
+ this.rows.forEach(row => usages.insertRow(ctx, row));
493
+ if (!foreign || !visited)
494
+ return visited;
495
+ return visited === visiting ? cu : (0, mutative_1.create)(visited, draft => {
496
+ draft.markers.markers.push(prettierStyle);
497
+ });
217
498
  });
218
499
  }
219
500
  visitBlock(block, ctx) {
@@ -222,15 +503,28 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
222
503
  });
223
504
  return __awaiter(this, void 0, void 0, function* () {
224
505
  const planned = [];
225
- let scopes = 0;
506
+ const apis = [];
226
507
  for (const statement of block.statements) {
227
- const candidate = (0, enzyme_wrapper_scope_1.wrapperDeclaration)(statement.element);
508
+ const candidate = (0, enzyme_wrapper_scope_1.wrapperDeclaration)(statement.element, render => this.renderOf(render));
228
509
  if (!candidate)
229
510
  continue;
230
- const scope = yield (0, enzyme_wrapper_scope_1.analyzeWrapperScope)(block, candidate.declaration, candidate.name, this.events, untaggedPositions, this.cursor.parent, ctx);
231
- if (!scope || !(yield this.mountMatches(candidate.mount.id, block, ctx)))
511
+ const api = candidate.render;
512
+ const reads = READS[api];
513
+ const scope = (0, enzyme_wrapper_scope_1.analyzeWrapperScope)(this.cursor, candidate, { events: reads.simulate ? this.events.events : new Set(), html: reads.html, untaggedPositions, hostNames, snapshots,
514
+ constant: node => this.constantString(node) });
515
+ if (!scope)
516
+ continue;
517
+ if ([...scope.uses.values()].some(use => use.use === "setProps" && !reads.props(use.props, this.importedNames)))
518
+ continue;
519
+ const mount = new rewrite_1.Cursor(candidate.mount, (0, enzyme_wrapper_scope_1.variableCursor)(this.cursor, candidate.declaration));
520
+ const document = documentAt(mount);
521
+ if (!document || !(yield renderPatterns[api].render.match(candidate.mount, mount)))
522
+ continue;
523
+ const attached = this.events.attached && [...scope.uses.values()].some(use => use.use === "simulate");
524
+ if (!attached && this.rootStyles && [...scope.uses.values()].some(use => CONTAINER_READS.has(use.use)))
232
525
  continue;
233
- this.mounts.add(candidate.mount.id);
526
+ this.mounts.set(candidate.mount.id, { document, api, attached });
527
+ apis.push(api);
234
528
  this.declarations.add(candidate.declaration.id);
235
529
  scope.uses.forEach((use, id) => this.uses.set(id, use));
236
530
  scope.removedStatements.forEach(id => this.removedStatements.add(id));
@@ -244,7 +538,6 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
244
538
  this.hoistedMounts.set(candidate.mount.id, name);
245
539
  }
246
540
  planned.push(candidate.mount.id, ...scope.uses.keys());
247
- scopes++;
248
541
  }
249
542
  planned.forEach(id => this.pending.add(id));
250
543
  const queued = this.afterVisit.length;
@@ -253,12 +546,11 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
253
546
  if (planned.some(id => this.pending.has(id))) {
254
547
  this.afterVisit.length = queued;
255
548
  this.rows.length = rows;
256
- (yield (0, enzyme_wrapper_scope_1.idsWithin)(block, this.reformat, ctx)).forEach(id => this.reformat.delete(id));
257
- (yield (0, enzyme_wrapper_scope_1.idsWithin)(block, new Set([...this.mounts, ...this.uses.keys()]), ctx)).forEach(id => this.pending.add(id));
549
+ (0, enzyme_wrapper_scope_1.idsWithin)(block, this.reformat).forEach(id => this.reformat.delete(id));
550
+ (0, enzyme_wrapper_scope_1.idsWithin)(block, new Set([...this.mounts.keys(), ...this.uses.keys()])).forEach(id => this.pending.add(id));
258
551
  return block;
259
552
  }
260
- for (let i = 0; i < scopes; i++)
261
- this.converted("mount", (0, enzyme_usage_1.enclosingScope)(this.cursor), "WRAPPER_SCOPE");
553
+ apis.forEach(api => this.converted(api, (0, enzyme_usage_1.enclosingScope)(this.cursor), "WRAPPER_SCOPE"));
262
554
  const laidOut = yield this.withPrettierLayout(visited, ctx);
263
555
  const statements = [];
264
556
  for (const statement of laidOut.statements) {
@@ -307,7 +599,7 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
307
599
  const statements = [];
308
600
  let formatted = false;
309
601
  for (const statement of block.statements) {
310
- const ids = yield (0, enzyme_wrapper_scope_1.idsWithin)(statement.element, this.reformat, ctx);
602
+ const ids = (0, enzyme_wrapper_scope_1.idsWithin)(statement.element, this.reformat);
311
603
  if (ids.length === 0) {
312
604
  statements.push(statement);
313
605
  continue;
@@ -340,15 +632,8 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
340
632
  if (use)
341
633
  return (_a = yield this.apply(use, field, ctx)) !== null && _a !== void 0 ? _a : field;
342
634
  const visited = yield _super.visitFieldAccess.call(this, field, ctx);
343
- if (visited.name.element.simpleName === "length" && (0, enzyme_wrapper_scope_1.simpleChain)(visited)) {
344
- const result = yield lengthRule.tryOn(this.cursor, visited, { visitor: this });
345
- if (result) {
346
- this.converted("mount.find.length", "<inline expression>", "INLINE_DOM_QUERY");
347
- this.laidOutByPrettier(result);
348
- return (0, enzyme_wrapper_scope_1.withRenderOptionsOnElementLine)(result, ctx);
349
- }
350
- }
351
- return visited;
635
+ const lengthOf = visited.name.element.simpleName === "length" && (0, enzyme_wrapper_scope_1.simpleChain)(visited) ? this.renderOf((0, enzyme_wrapper_scope_1.innermostCall)(visited)) : undefined;
636
+ return lengthOf && (yield this.tryInline(lengthOf, "length", visited, `${lengthOf}.find.length`, "<inline expression>", "INLINE_DOM_QUERY", ctx)) || visited;
352
637
  });
353
638
  }
354
639
  visitMethodInvocation(method, ctx) {
@@ -363,56 +648,39 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
363
648
  if (this.unmounts.has(method.id))
364
649
  return (0, enzyme_wrapper_scope_1.withoutEnzymeTypes)(method, ctx);
365
650
  const visited = yield _super.visitMethodInvocation.call(this, method, ctx);
366
- if (this.mounts.has(method.id)) {
651
+ const mounted = this.mounts.get(method.id);
652
+ if (mounted) {
367
653
  const hoisted = this.hoistedMounts.get(method.id);
368
654
  const result = hoisted ?
369
- yield this.applyTemplate(javascript_1.Template.builder().code(`render(${hoisted}, {container: globalThis.document.createElement('div')})`).build().configure(after), visited) :
370
- yield mountRule.tryOn(this.cursor, visited, { visitor: this });
655
+ yield this.applyTemplate(javascript_1.Template.builder().code(mounted.attached ? `render(${hoisted})` : `render(${hoisted}, ${renderOptions(mounted.document)})`).build().configure(after), visited) :
656
+ yield rules[mounted.document][mounted.api][mounted.attached ? "attachedMount" : "mount"].tryOn(this.cursor, visited, { visitor: this });
371
657
  if (!result)
372
658
  return visited;
373
659
  this.pending.delete(method.id);
374
660
  return (0, enzyme_wrapper_scope_1.withRenderOptionsOnElementLine)(result, ctx);
375
661
  }
376
- if (visited.name.simpleName === "mount" && (0, enzyme_wrapper_scope_1.mountedElement)(visited) && (0, enzyme_wrapper_scope_1.statementPosition)(this.cursor)) {
377
- const result = yield mountRule.tryOn(this.cursor, visited, { visitor: this });
378
- if (result) {
379
- this.converted("mount", (0, enzyme_usage_1.enclosingScope)(this.cursor), "MOUNT_STATEMENT");
380
- this.laidOutByPrettier(result);
381
- return (0, enzyme_wrapper_scope_1.withRenderOptionsOnElementLine)(result, ctx);
382
- }
383
- }
384
- if (visited.name.simpleName === "exists" && (0, enzyme_wrapper_scope_1.simpleChain)(visited)) {
385
- const result = yield (this.callArgument(visited) ? existsArgumentRule : existsRule).tryOn(this.cursor, visited, { visitor: this });
386
- if (result) {
387
- this.converted("mount.find.exists", "<inline expression>", "INLINE_DOM_QUERY");
388
- this.laidOutByPrettier(result);
389
- return (0, enzyme_wrapper_scope_1.withRenderOptionsOnElementLine)(result, ctx);
390
- }
391
- }
392
- return visited;
662
+ const statementOf = (0, enzyme_wrapper_scope_1.mountedElement)(visited) && (0, enzyme_wrapper_scope_1.statementPosition)(this.cursor) && !(0, enzyme_wrapper_scope_1.passesRef)(visited) ? this.renderOf(visited, false) : undefined;
663
+ const statement = statementOf && (yield this.tryInline(statementOf, "mount", visited, statementOf, (0, enzyme_usage_1.enclosingScope)(this.cursor), "MOUNT_STATEMENT", ctx));
664
+ if (statement)
665
+ return statement;
666
+ const existsOf = visited.name.simpleName === "exists" && (0, enzyme_wrapper_scope_1.simpleChain)(visited) ? this.renderOf((0, enzyme_wrapper_scope_1.innermostCall)(visited)) : undefined;
667
+ return existsOf && (yield this.tryInline(existsOf, "exists", visited, `${existsOf}.find.exists`, "<inline expression>", "INLINE_DOM_QUERY", ctx)) || visited;
393
668
  });
394
669
  }
395
- mountMatches(mount, block, ctx) {
670
+ tryInline(render, rule, node, api, scope, reason, ctx) {
396
671
  return __awaiter(this, void 0, void 0, function* () {
397
- let mounted = false;
398
- yield new class extends javascript_1.JavaScriptVisitor {
399
- visitMethodInvocation(method, ctx) {
400
- const _super = Object.create(null, {
401
- visitMethodInvocation: { get: () => super.visitMethodInvocation }
402
- });
403
- return __awaiter(this, void 0, void 0, function* () {
404
- if (method.id === mount && (yield mountPattern.match(method, this.cursor)))
405
- mounted = true;
406
- return _super.visitMethodInvocation.call(this, method, ctx);
407
- });
408
- }
409
- }().visit(block, ctx, this.cursor.parent);
410
- return mounted;
672
+ const document = documentAt(this.cursor);
673
+ const result = document && (yield rules[document][render][rule].tryOn(this.cursor, node, { visitor: this }));
674
+ if (!result)
675
+ return undefined;
676
+ this.converted(api, scope, reason);
677
+ this.laidOutByPrettier(result);
678
+ return (0, enzyme_wrapper_scope_1.withRenderOptionsOnElementLine)(result, ctx);
411
679
  });
412
680
  }
413
681
  apply(read, node, ctx) {
414
682
  return __awaiter(this, void 0, void 0, function* () {
415
- const result = yield this.applyTemplate(this.readTemplate(read, node), node);
683
+ const result = yield this.applyTemplate(this.readTemplate(read), node);
416
684
  if (!result)
417
685
  return undefined;
418
686
  this.pending.delete(node.id);
@@ -429,7 +697,7 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
429
697
  return replacement.apply(node, this.cursor, { bindings: yield replacement.resolveBindings(this) });
430
698
  });
431
699
  }
432
- readTemplate(read, node) {
700
+ readTemplate(read) {
433
701
  const code = javascript_1.Template.builder();
434
702
  const nodes = () => code.param(read.wrapper).code(".container.querySelectorAll(").param(read.selector).code(")");
435
703
  const element = (nonNull) => {
@@ -442,35 +710,24 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
442
710
  return nodes().code("[").param(read.index).code("]");
443
711
  return code.param(read.wrapper).code(".container.querySelector(").param(read.selector).code(")" + assertion);
444
712
  };
445
- const parenthesized = (build) => {
446
- const bare = this.callArgument(node);
447
- if (!bare)
448
- code.code("(");
449
- build();
450
- return code.code(bare ? "" : ")").build();
451
- };
452
713
  const within = () => element(false).code("?.querySelectorAll(").param(read.within).code(").length ?? 0");
453
714
  switch (read.use) {
454
715
  case "length":
455
716
  if (read.within)
456
- return parenthesized(within);
717
+ return within().build();
457
718
  return nodes().code(".length").build();
458
719
  case "exists":
459
- if (read.within)
460
- return parenthesized(() => {
461
- code.code("(");
462
- within().code(") > 0");
463
- });
464
- return parenthesized(() => nodes().code(".length > 0"));
720
+ if (read.within) {
721
+ code.code("(");
722
+ return within().code(") > 0").build();
723
+ }
724
+ return nodes().code(".length > 0").build();
465
725
  case "positionExists":
466
- return parenthesized(() => {
467
- if (read.index === "first")
468
- code.param(read.wrapper).code(".container.querySelector(").param(read.selector).code(") !== null");
469
- else if (read.index === "last")
470
- nodes().code(".length > 0");
471
- else
472
- nodes().code("[").param(read.index).code("] !== undefined");
473
- });
726
+ if (read.index === "first")
727
+ return code.param(read.wrapper).code(".container.querySelector(").param(read.selector).code(") !== null").build();
728
+ if (read.index === "last")
729
+ return nodes().code(".length > 0").build();
730
+ return nodes().code("[").param(read.index).code("] !== undefined").build();
474
731
  case "nodes":
475
732
  return nodes().build();
476
733
  case "text":
@@ -481,8 +738,14 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
481
738
  return element(false).code("?.textContent").build();
482
739
  case "html":
483
740
  return element(!!read.unasserted).code(read.unasserted ? ".outerHTML" : "?.outerHTML").build();
741
+ case "rootHtml":
742
+ return code.param(read.wrapper).code(".container.innerHTML").build();
743
+ case "node":
744
+ return element(true).build();
484
745
  case "hasClass":
485
746
  return element(true).code(".classList.contains(").param(read.className).code(")").build();
747
+ case "snapshot":
748
+ return code.code("expect(").param(read.wrapper).code(".asFragment())").build();
486
749
  case "setProps":
487
750
  code.param(read.wrapper).code(`.rerender(${read.reassigned ? `(${read.element} = ` : ""}cloneElement(${read.element}, `);
488
751
  return code.param(read.props).code(read.reassigned ? ")))" : "))").build().configure({
@@ -512,11 +775,47 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
512
775
  });
513
776
  }
514
777
  }
515
- callArgument(node) {
778
+ renderOf(node, read = true) {
779
+ var _a;
780
+ if ((node === null || node === void 0 ? void 0 : node.kind) !== java_1.J.Kind.MethodInvocation)
781
+ return undefined;
782
+ const call = node;
783
+ const api = (0, enzyme_usage_1.enzymeMethod)(call);
784
+ if (api === "mount")
785
+ return read && this.rendersPortal(call) ? undefined : api;
786
+ const element = (_a = call.arguments.elements[0]) === null || _a === void 0 ? void 0 : _a.element;
787
+ return api === "shallow" && call.arguments.elements.length === 1 && (0, enzyme_host_components_1.rendersHostElements)(element, this.imports, scanned.components, this.importedNames) ? api : undefined;
788
+ }
789
+ rendersPortal(call) {
516
790
  var _a;
517
- const parent = (_a = this.cursor.parentTree()) === null || _a === void 0 ? void 0 : _a.value;
518
- return (parent === null || parent === void 0 ? void 0 : parent.kind) === java_1.J.Kind.MethodInvocation &&
519
- parent.arguments.elements.some(argument => argument.element.id === node.id);
791
+ const element = (_a = call.arguments.elements[0]) === null || _a === void 0 ? void 0 : _a.element;
792
+ const { roots, declares, resolve } = this.moduleResolution();
793
+ const portal = !!element && !!this.cu && (0, enzyme_portals_1.rendersPortal)(element, this.cu, {
794
+ sourcePath: this.sourcePath,
795
+ modules: scanned.modules,
796
+ resolve,
797
+ declares,
798
+ packagePortals: () => [...scanned.modules].some(([path, facts]) => {
799
+ var _a;
800
+ return facts.portal &&
801
+ path.startsWith((_a = roots[0]) !== null && _a !== void 0 ? _a : "") && !/(^|\/)__tests?__\/|\.(test|spec)\.[cm]?[jt]sx?$/.test(path);
802
+ })
803
+ });
804
+ if (portal && !this.portals.has(call.id)) {
805
+ this.portals.add(call.id);
806
+ this.rows.push({ sourcePath: this.sourcePath, scope: (0, enzyme_usage_1.enclosingScope)(this.cursor), api: "mount", status: "REVIEW", reason: "PORTAL",
807
+ suggestedAction: "A component it renders may render into a portal, which RTL renders outside the container: query `screen` or `baseElement` for that content." });
808
+ }
809
+ return portal;
810
+ }
811
+ moduleResolution() {
812
+ const roots = [...scanned.packages.keys()].filter(root => this.sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
813
+ const declares = (name) => roots.some(root => scanned.packages.get(root).dependencies.has(name));
814
+ return { roots, declares, resolve: (0, enzyme_portals_1.resolver)(scanned.modules, [...new Set([...roots, ""])], declares) };
815
+ }
816
+ constantString(node) {
817
+ const parts = (0, enzyme_constant_strings_1.stringParts)(node);
818
+ return parts && (0, enzyme_constant_strings_1.evaluate)(parts, this.sourcePath, scanned.modules, this.moduleResolution().resolve);
520
819
  }
521
820
  laidOutByPrettier(node) {
522
821
  if (this.prettier)
@@ -524,6 +823,8 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
524
823
  }
525
824
  converted(api, scope, reason) {
526
825
  (0, javascript_1.maybeRemoveImport)(this, enzyme_usage_1.ENZYME);
826
+ if (snapshots)
827
+ (0, javascript_1.maybeRemoveImport)(this, "enzyme-to-json");
527
828
  this.rows.push({ sourcePath: this.sourcePath, scope, api, status: "CONVERTED", reason,
528
829
  suggestedAction: "Run the migrated test and review whether an accessible RTL query would better express its intent." });
529
830
  }
@@ -532,7 +833,8 @@ class EnzymeToReactTestingLibrary extends rewrite_1.ScanningRecipe {
532
833
  }
533
834
  recipeList() {
534
835
  return __awaiter(this, void 0, void 0, function* () {
535
- return [...ADDS_RTL ? [yield (0, javascript_1.addDependency)(RTL_ADDITION)] : [], new find_enzyme_usage_1.FindEnzymeUsage()];
836
+ const steps = this.dependencySteps;
837
+ return [...steps ? [steps.rtl, steps.rtl18, steps.dom18] : [], new find_enzyme_usage_1.FindEnzymeUsage()];
536
838
  });
537
839
  }
538
840
  }
@@ -544,4 +846,14 @@ __decorate([
544
846
  required: false
545
847
  })
546
848
  ], EnzymeToReactTestingLibrary.prototype, "untaggedSelectorPositions", void 0);
849
+ class EnzymeSnapshotsToReactTestingLibrary extends EnzymeToReactTestingLibrary {
850
+ constructor() {
851
+ super(...arguments);
852
+ this.name = "org.openrewrite.react.migrate.enzyme-snapshots-to-react-testing-library";
853
+ this.displayName = "Migrate Enzyme to React Testing Library, snapshots included";
854
+ this.description = "Migrates Enzyme wrappers as `org.openrewrite.react.migrate.enzyme-to-react-testing-library` does, and also converts `expect(wrapper).toMatchSnapshot()` and `expect(toJson(wrapper)).toMatchSnapshot()` of those wrappers to `expect(wrapper.asFragment()).toMatchSnapshot()`, removing the `enzyme-to-json` import where nothing else uses it. RTL snapshots the rendered DOM where Enzyme's serializer recorded a component tree, so the stored snapshots of converted tests no longer match: run the tests with `--updateSnapshot` once and review the new snapshots. Inline snapshots and snapshots of shallow renders that are not converted are left for review.";
855
+ this.snapshots = true;
856
+ }
857
+ }
858
+ exports.EnzymeSnapshotsToReactTestingLibrary = EnzymeSnapshotsToReactTestingLibrary;
547
859
  //# sourceMappingURL=enzyme-to-react-testing-library.js.map