@openrewrite/recipes-react 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/dist/index.d.ts +1 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +27 -0
  4. package/dist/index.js.map +1 -1
  5. package/dist/mui/adapt-v4-theme.d.ts +8 -0
  6. package/dist/mui/adapt-v4-theme.d.ts.map +1 -0
  7. package/dist/mui/adapt-v4-theme.js +65 -0
  8. package/dist/mui/adapt-v4-theme.js.map +1 -0
  9. package/dist/mui/add-component-prop.d.ts +18 -0
  10. package/dist/mui/add-component-prop.d.ts.map +1 -0
  11. package/dist/mui/add-component-prop.js +53 -0
  12. package/dist/mui/add-component-prop.js.map +1 -0
  13. package/dist/mui/add-emotion-prepend.d.ts +8 -0
  14. package/dist/mui/add-emotion-prepend.d.ts.map +1 -0
  15. package/dist/mui/add-emotion-prepend.js +71 -0
  16. package/dist/mui/add-emotion-prepend.js.map +1 -0
  17. package/dist/mui/change-module-specifier.d.ts +14 -0
  18. package/dist/mui/change-module-specifier.d.ts.map +1 -0
  19. package/dist/mui/change-module-specifier.js +95 -0
  20. package/dist/mui/change-module-specifier.js.map +1 -0
  21. package/dist/mui/convert-mui-imports.d.ts +14 -0
  22. package/dist/mui/convert-mui-imports.d.ts.map +1 -0
  23. package/dist/mui/convert-mui-imports.js +195 -0
  24. package/dist/mui/convert-mui-imports.js.map +1 -0
  25. package/dist/mui/convert-prop-to-sx.d.ts +22 -0
  26. package/dist/mui/convert-prop-to-sx.d.ts.map +1 -0
  27. package/dist/mui/convert-prop-to-sx.js +99 -0
  28. package/dist/mui/convert-prop-to-sx.js.map +1 -0
  29. package/dist/mui/index.d.ts +32 -0
  30. package/dist/mui/index.d.ts.map +1 -0
  31. package/dist/mui/index.js +67 -0
  32. package/dist/mui/index.js.map +1 -0
  33. package/dist/mui/jsx-attributes.d.ts +27 -0
  34. package/dist/mui/jsx-attributes.d.ts.map +1 -0
  35. package/dist/mui/jsx-attributes.js +140 -0
  36. package/dist/mui/jsx-attributes.js.map +1 -0
  37. package/dist/mui/mark-manual-migration.d.ts +16 -0
  38. package/dist/mui/mark-manual-migration.d.ts.map +1 -0
  39. package/dist/mui/mark-manual-migration.js +73 -0
  40. package/dist/mui/mark-manual-migration.js.map +1 -0
  41. package/dist/mui/mark-palette-mode-usage.d.ts +12 -0
  42. package/dist/mui/mark-palette-mode-usage.d.ts.map +1 -0
  43. package/dist/mui/mark-palette-mode-usage.js +50 -0
  44. package/dist/mui/mark-palette-mode-usage.js.map +1 -0
  45. package/dist/mui/move-component-prop-to-slot.d.ts +22 -0
  46. package/dist/mui/move-component-prop-to-slot.d.ts.map +1 -0
  47. package/dist/mui/move-component-prop-to-slot.js +87 -0
  48. package/dist/mui/move-component-prop-to-slot.js.map +1 -0
  49. package/dist/mui/move-primary-text-to-children.d.ts +12 -0
  50. package/dist/mui/move-primary-text-to-children.d.ts.map +1 -0
  51. package/dist/mui/move-primary-text-to-children.js +52 -0
  52. package/dist/mui/move-primary-text-to-children.js.map +1 -0
  53. package/dist/mui/move-system-props-to-sx.d.ts +16 -0
  54. package/dist/mui/move-system-props-to-sx.d.ts.map +1 -0
  55. package/dist/mui/move-system-props-to-sx.js +122 -0
  56. package/dist/mui/move-system-props-to-sx.js.map +1 -0
  57. package/dist/mui/mui-components.d.ts +8 -0
  58. package/dist/mui/mui-components.d.ts.map +1 -0
  59. package/dist/mui/mui-components.js +41 -0
  60. package/dist/mui/mui-components.js.map +1 -0
  61. package/dist/mui/mui-tag-visitor.d.ts +5 -0
  62. package/dist/mui/mui-tag-visitor.d.ts.map +1 -0
  63. package/dist/mui/mui-tag-visitor.js +54 -0
  64. package/dist/mui/mui-tag-visitor.js.map +1 -0
  65. package/dist/mui/pre-v5-recipe.d.ts +14 -0
  66. package/dist/mui/pre-v5-recipe.d.ts.map +1 -0
  67. package/dist/mui/pre-v5-recipe.js +88 -0
  68. package/dist/mui/pre-v5-recipe.js.map +1 -0
  69. package/dist/mui/remove-component-prop.d.ts +18 -0
  70. package/dist/mui/remove-component-prop.d.ts.map +1 -0
  71. package/dist/mui/remove-component-prop.js +55 -0
  72. package/dist/mui/remove-component-prop.js.map +1 -0
  73. package/dist/mui/remove-root-ref.d.ts +8 -0
  74. package/dist/mui/remove-root-ref.d.ts.map +1 -0
  75. package/dist/mui/remove-root-ref.js +61 -0
  76. package/dist/mui/remove-root-ref.js.map +1 -0
  77. package/dist/mui/remove-spacing-px-suffix.d.ts +8 -0
  78. package/dist/mui/remove-spacing-px-suffix.d.ts.map +1 -0
  79. package/dist/mui/remove-spacing-px-suffix.js +62 -0
  80. package/dist/mui/remove-spacing-px-suffix.js.map +1 -0
  81. package/dist/mui/rename-component-prop.d.ts +20 -0
  82. package/dist/mui/rename-component-prop.d.ts.map +1 -0
  83. package/dist/mui/rename-component-prop.js +66 -0
  84. package/dist/mui/rename-component-prop.js.map +1 -0
  85. package/dist/mui/rename-joy-css-variables.d.ts +8 -0
  86. package/dist/mui/rename-joy-css-variables.d.ts.map +1 -0
  87. package/dist/mui/rename-joy-css-variables.js +51 -0
  88. package/dist/mui/rename-joy-css-variables.js.map +1 -0
  89. package/dist/mui/rename-theme-palette-type.d.ts +8 -0
  90. package/dist/mui/rename-theme-palette-type.d.ts.map +1 -0
  91. package/dist/mui/rename-theme-palette-type.js +61 -0
  92. package/dist/mui/rename-theme-palette-type.js.map +1 -0
  93. package/dist/mui/replace-box-border-radius.d.ts +10 -0
  94. package/dist/mui/replace-box-border-radius.d.ts.map +1 -0
  95. package/dist/mui/replace-box-border-radius.js +50 -0
  96. package/dist/mui/replace-box-border-radius.js.map +1 -0
  97. package/dist/mui/replace-breakpoints-width.d.ts +8 -0
  98. package/dist/mui/replace-breakpoints-width.d.ts.map +1 -0
  99. package/dist/mui/replace-breakpoints-width.js +46 -0
  100. package/dist/mui/replace-breakpoints-width.js.map +1 -0
  101. package/dist/mui/replace-component-class.d.ts +18 -0
  102. package/dist/mui/replace-component-class.d.ts.map +1 -0
  103. package/dist/mui/replace-component-class.js +126 -0
  104. package/dist/mui/replace-component-class.js.map +1 -0
  105. package/dist/mui/replace-components-with-slots.d.ts +14 -0
  106. package/dist/mui/replace-components-with-slots.d.ts.map +1 -0
  107. package/dist/mui/replace-components-with-slots.js +69 -0
  108. package/dist/mui/replace-components-with-slots.js.map +1 -0
  109. package/dist/mui/replace-import-paths.d.ts +14 -0
  110. package/dist/mui/replace-import-paths.d.ts.map +1 -0
  111. package/dist/mui/replace-import-paths.js +101 -0
  112. package/dist/mui/replace-import-paths.js.map +1 -0
  113. package/dist/mui/replace-in-string-literals.d.ts +15 -0
  114. package/dist/mui/replace-in-string-literals.d.ts.map +1 -0
  115. package/dist/mui/replace-in-string-literals.js +62 -0
  116. package/dist/mui/replace-in-string-literals.js.map +1 -0
  117. package/dist/mui/replace-list-item-button-prop.d.ts +12 -0
  118. package/dist/mui/replace-list-item-button-prop.d.ts.map +1 -0
  119. package/dist/mui/replace-list-item-button-prop.js +80 -0
  120. package/dist/mui/replace-list-item-button-prop.js.map +1 -0
  121. package/dist/mui/replace-tabs-scroll-buttons.d.ts +8 -0
  122. package/dist/mui/replace-tabs-scroll-buttons.d.ts.map +1 -0
  123. package/dist/mui/replace-tabs-scroll-buttons.js +41 -0
  124. package/dist/mui/replace-tabs-scroll-buttons.js.map +1 -0
  125. package/dist/mui/replace-theme-color-functions.d.ts +8 -0
  126. package/dist/mui/replace-theme-color-functions.d.ts.map +1 -0
  127. package/dist/mui/replace-theme-color-functions.js +72 -0
  128. package/dist/mui/replace-theme-color-functions.js.map +1 -0
  129. package/dist/mui/replace-theme-spacing-unit.d.ts +8 -0
  130. package/dist/mui/replace-theme-spacing-unit.d.ts.map +1 -0
  131. package/dist/mui/replace-theme-spacing-unit.js +77 -0
  132. package/dist/mui/replace-theme-spacing-unit.js.map +1 -0
  133. package/dist/mui/replace-typography-round.d.ts +8 -0
  134. package/dist/mui/replace-typography-round.d.ts.map +1 -0
  135. package/dist/mui/replace-typography-round.js +44 -0
  136. package/dist/mui/replace-typography-round.js.map +1 -0
  137. package/dist/mui/shift-hidden-down-props.d.ts +10 -0
  138. package/dist/mui/shift-hidden-down-props.d.ts.map +1 -0
  139. package/dist/mui/shift-hidden-down-props.js +49 -0
  140. package/dist/mui/shift-hidden-down-props.js.map +1 -0
  141. package/dist/mui/theme-access.d.ts +5 -0
  142. package/dist/mui/theme-access.d.ts.map +1 -0
  143. package/dist/mui/theme-access.js +21 -0
  144. package/dist/mui/theme-access.js.map +1 -0
  145. package/dist/mui/update-theme-breakpoints.d.ts +10 -0
  146. package/dist/mui/update-theme-breakpoints.d.ts.map +1 -0
  147. package/dist/mui/update-theme-breakpoints.js +58 -0
  148. package/dist/mui/update-theme-breakpoints.js.map +1 -0
  149. package/dist/mui/upgrade-grid-props.d.ts +16 -0
  150. package/dist/mui/upgrade-grid-props.d.ts.map +1 -0
  151. package/dist/mui/upgrade-grid-props.js +90 -0
  152. package/dist/mui/upgrade-grid-props.js.map +1 -0
  153. package/dist/search/find-enzyme-usage.d.ts +4 -0
  154. package/dist/search/find-enzyme-usage.d.ts.map +1 -1
  155. package/dist/search/find-enzyme-usage.js +91 -7
  156. package/dist/search/find-enzyme-usage.js.map +1 -1
  157. package/dist/testing/enzyme-host-components.d.ts +12 -0
  158. package/dist/testing/enzyme-host-components.d.ts.map +1 -1
  159. package/dist/testing/enzyme-host-components.js +100 -0
  160. package/dist/testing/enzyme-host-components.js.map +1 -1
  161. package/dist/testing/enzyme-render-blockers.d.ts +13 -4
  162. package/dist/testing/enzyme-render-blockers.d.ts.map +1 -1
  163. package/dist/testing/enzyme-render-blockers.js +162 -6
  164. package/dist/testing/enzyme-render-blockers.js.map +1 -1
  165. package/dist/testing/enzyme-to-react-testing-library.d.ts +9 -2
  166. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  167. package/dist/testing/enzyme-to-react-testing-library.js +163 -16
  168. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  169. package/dist/testing/enzyme-usage.d.ts +7 -0
  170. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  171. package/dist/testing/enzyme-usage.js +8 -1
  172. package/dist/testing/enzyme-usage.js.map +1 -1
  173. package/dist/testing/enzyme-wrapper-scope.d.ts +8 -5
  174. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  175. package/dist/testing/enzyme-wrapper-scope.js +16 -4
  176. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  177. package/dist/zustand/redux-stores.d.ts +2 -0
  178. package/dist/zustand/redux-stores.d.ts.map +1 -1
  179. package/dist/zustand/redux-stores.js +120 -6
  180. package/dist/zustand/redux-stores.js.map +1 -1
  181. package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
  182. package/dist/zustand/redux-to-zustand.js +10 -4
  183. package/dist/zustand/redux-to-zustand.js.map +1 -1
  184. package/dist/zustand/zustand-plan.d.ts +7 -0
  185. package/dist/zustand/zustand-plan.d.ts.map +1 -1
  186. package/dist/zustand/zustand-plan.js +141 -21
  187. package/dist/zustand/zustand-plan.js.map +1 -1
  188. package/package.json +1 -1
  189. package/src/index.ts +10 -0
  190. package/src/mui/adapt-v4-theme.ts +43 -0
  191. package/src/mui/add-component-prop.ts +43 -0
  192. package/src/mui/add-emotion-prepend.ts +48 -0
  193. package/src/mui/change-module-specifier.ts +71 -0
  194. package/src/mui/convert-mui-imports.ts +184 -0
  195. package/src/mui/convert-prop-to-sx.ts +89 -0
  196. package/src/mui/index.ts +31 -0
  197. package/src/mui/jsx-attributes.ts +133 -0
  198. package/src/mui/mark-manual-migration.ts +53 -0
  199. package/src/mui/mark-palette-mode-usage.ts +36 -0
  200. package/src/mui/move-component-prop-to-slot.ts +84 -0
  201. package/src/mui/move-primary-text-to-children.ts +41 -0
  202. package/src/mui/move-system-props-to-sx.ts +118 -0
  203. package/src/mui/mui-components.ts +40 -0
  204. package/src/mui/mui-tag-visitor.ts +36 -0
  205. package/src/mui/pre-v5-recipe.ts +82 -0
  206. package/src/mui/remove-component-prop.ts +43 -0
  207. package/src/mui/remove-root-ref.ts +41 -0
  208. package/src/mui/remove-spacing-px-suffix.ts +43 -0
  209. package/src/mui/rename-component-prop.ts +55 -0
  210. package/src/mui/rename-joy-css-variables.ts +41 -0
  211. package/src/mui/rename-theme-palette-type.ts +42 -0
  212. package/src/mui/replace-box-border-radius.ts +42 -0
  213. package/src/mui/replace-breakpoints-width.ts +28 -0
  214. package/src/mui/replace-component-class.ts +97 -0
  215. package/src/mui/replace-components-with-slots.ts +61 -0
  216. package/src/mui/replace-import-paths.ts +100 -0
  217. package/src/mui/replace-in-string-literals.ts +44 -0
  218. package/src/mui/replace-list-item-button-prop.ts +59 -0
  219. package/src/mui/replace-tabs-scroll-buttons.ts +31 -0
  220. package/src/mui/replace-theme-color-functions.ts +55 -0
  221. package/src/mui/replace-theme-spacing-unit.ts +59 -0
  222. package/src/mui/replace-typography-round.ts +29 -0
  223. package/src/mui/shift-hidden-down-props.ts +44 -0
  224. package/src/mui/theme-access.ts +18 -0
  225. package/src/mui/update-theme-breakpoints.ts +47 -0
  226. package/src/mui/upgrade-grid-props.ts +82 -0
  227. package/src/search/find-enzyme-usage.ts +80 -7
  228. package/src/testing/enzyme-host-components.ts +110 -0
  229. package/src/testing/enzyme-render-blockers.ts +174 -9
  230. package/src/testing/enzyme-to-react-testing-library.ts +159 -25
  231. package/src/testing/enzyme-usage.ts +13 -0
  232. package/src/testing/enzyme-wrapper-scope.ts +27 -6
  233. package/src/zustand/redux-stores.ts +119 -5
  234. package/src/zustand/redux-to-zustand.ts +12 -5
  235. package/src/zustand/zustand-plan.ts +159 -18
@@ -1,7 +1,7 @@
1
- import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, randomId, RecipeRef, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
1
+ import {and, check, Cursor, DataTable, ExecutionContext, findMarker, MarkersKind, MarkupWarn, not, Option, or, randomId, RecipeRef, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
2
2
  import {isPlainText} from "@openrewrite/rewrite/text";
3
- import {AddDependencyOptions, autoFormat, Autodetect, capture, PrettierStyle, deconflict, findNodeResolutionResult, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeAddImport, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, raw, rewrite, scopeOf, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
4
- import {Expression, J} from "@openrewrite/rewrite/java";
3
+ import {AddDependencyOptions, autoFormat, Autodetect, capture, PrettierStyle, deconflict, findNodeResolutionResult, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeAddImport, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, walk, raw, rewrite, scopeOf, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
4
+ import {Expression, isIdentifier, J, Type, TypedTree} from "@openrewrite/rewrite/java";
5
5
  import {create} from "mutative";
6
6
  import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
7
7
  import {readFileSync} from "fs";
@@ -10,9 +10,9 @@ import {satisfies, valid, validRange} from "semver";
10
10
  import {FindEnzymeUsage} from "../search/find-enzyme-usage";
11
11
  import {JavaDependencyRecipe, treesOfType} from "../util/java-recipe-proxy";
12
12
  import {importBindings} from "../util/module-imports";
13
- import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, enzymeMethod, EnzymeUsageRow, FILE_BLOCKER, RENDER_BLOCKERS} from "./enzyme-usage";
14
- import {blockedByFile, blockedByGate, blockedByUses, FileGate} from "./enzyme-render-blockers";
15
- import {HostComponents, hostComponentExports, hostComponentsDeclared, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
13
+ import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, enzymeMethod, EnzymeUsageRow, FILE_BLOCKER, RENDER_BLOCKERS, SELECTOR_VALUES, SelectorRead} from "./enzyme-usage";
14
+ import {blockedByFile, blockedByGate, blockedByShape, blockedByShared, blockedByPackage, blockedByShallow, blockedByUses, FileGate, NotAdded} from "./enzyme-render-blockers";
15
+ import {compositeFacts, Composites, HostComponents, hostComponentExports, shallowMiss, hostComponentsDeclared, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
16
16
  import {moduleFacts, Modules, rendersPortal, resolver} from "./enzyme-portals";
17
17
  import {evaluate, stringParts} from "./enzyme-constant-strings";
18
18
  import {hostOnlyNames, selectorNames, SelectorNames} from "./enzyme-selector-names";
@@ -82,6 +82,9 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
82
82
  /** The package roots whose edit `AddDependency` declined, such as for a lockfile it could not regenerate. Mutated in place too. */
83
83
  readonly declined = new Set<string>();
84
84
 
85
+ /** Why the dependency didn't land in each package root declaring Enzyme that it didn't land in. Mutated in place too. */
86
+ readonly outcomes = new Map<string, NotAdded>();
87
+
85
88
  private readonly manifests: Json.Document[] = [];
86
89
 
87
90
  /** The manifests the step admits, which reach the Java recipe only in `generate`, once the forecast is known. */
@@ -94,6 +97,7 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
94
97
  override initialValue(): number {
95
98
  this.landed.clear();
96
99
  this.declined.clear();
100
+ this.outcomes.clear();
97
101
  this.manifests.length = 0;
98
102
  this.held.length = 0;
99
103
  return super.initialValue();
@@ -126,10 +130,16 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
126
130
  // Without a forecast, as when the step runs alone, every admitted manifest goes on as before
127
131
  const converting = await this.forecast.converting?.();
128
132
  const scopes = lockfileScopes(this.held);
129
- const forwarded = new Set(this.held.filter(manifest => {
133
+ const withheld = (manifest: Json.Document): NotAdded | undefined => {
130
134
  const scope = scopes.get(manifest.sourcePath) ?? packageRoot(manifest.sourcePath);
131
- return (!converting || [...converting].some(source => source.startsWith(scope))) && !this.withholds(scope);
132
- }));
135
+ if (converting && ![...converting].some(source => source.startsWith(scope))) return {kind: "withheld"};
136
+ return this.withholds(scope) ? {kind: "peer"} : undefined;
137
+ };
138
+ const forwarded = new Set(this.held.filter(manifest => !withheld(manifest)));
139
+ for (const manifest of this.manifests) {
140
+ const why = forwarded.has(manifest) ? undefined : withheld(manifest);
141
+ if (why) this.outcomes.set(packageRoot(manifest.sourcePath), why);
142
+ }
133
143
  const scanner = await this.java.scanner(acc);
134
144
  for (const manifest of forwarded) await scanner.visit(manifest, ctx);
135
145
  const kept = this.manifests.filter(manifest => forwarded.has(manifest));
@@ -141,7 +151,12 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
141
151
  const edited = await editor.visit<Json.Document>(manifest, ctx);
142
152
  const root = manifest.sourcePath.slice(0, -"package.json".length);
143
153
  if (edited && edited !== manifest && declares(edited, this.addition.packageName)) this.landed.add(root);
144
- else if (!declares(manifest, this.addition.packageName) && this.resolvesGate(manifest)) this.declined.add(root);
154
+ else if (!declares(manifest, this.addition.packageName) && this.resolvesGate(manifest)) {
155
+ this.declined.add(root);
156
+ // NOTE: `AddDependency` leaves why it declined as a warning on the manifest it returns
157
+ const warning = (edited ?? manifest).markers.markers.find(marker => marker.kind === MarkersKind.MarkupWarn) as MarkupWarn | undefined;
158
+ this.outcomes.set(root, {kind: "declined", warning: warning && [warning.message, warning.detail].filter(Boolean).join("\n")});
159
+ } else if (!declares(manifest, this.addition.packageName)) this.outcomes.set(root, {kind: "gate"});
145
160
  }
146
161
  return generated;
147
162
  }
@@ -363,6 +378,8 @@ type Packages = Map<string, PackageDeclarations>;
363
378
  interface Scanned {
364
379
  packages: Packages;
365
380
  components: HostComponents;
381
+ /** What the components of each source render that `shallow` leaves out, for a review row's action. */
382
+ composites: Composites;
366
383
  modules: Modules;
367
384
  /** The words of each source's strings, for the selectors whose ancestor compounds name no tag. */
368
385
  names: Map<string, SelectorNames>;
@@ -442,8 +459,17 @@ export function simulatesEvents(packages: Packages, sourcePath: string, landed:
442
459
  return {events: new Set(), attached: false};
443
460
  }
444
461
 
462
+ /**
463
+ * The package root a source's RTL goes to, that of the package declaring Enzyme, and whether its React is 18, which
464
+ * decides the dependency step that adds it. Undefined where no package of the source declares or provides Enzyme.
465
+ */
466
+ export function rtlTarget(packages: Packages, sourcePath: string): {root: string, react18: boolean} | undefined {
467
+ const {enzymeRoot, enzymeReact} = compatibility(packages, sourcePath, new Set());
468
+ return enzymeRoot === undefined ? undefined : {root: enzymeRoot, react18: enzymeReact === 18};
469
+ }
470
+
445
471
  /** The React major as {@link reactMajor} reads it, and the major of the RTL the tests run with. */
446
- function compatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string>): {react: number, rtl: number, why?: FileGate} {
472
+ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string>): {react: number, rtl: number, why?: FileGate, enzymeRoot?: string, enzymeReact?: number} {
447
473
  const roots = [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
448
474
  const declared = (name: "react" | "reactDom" | "rtl", from = roots) =>
449
475
  from.map(root => packages.get(root)![name]).find(version => version !== undefined);
@@ -464,10 +490,11 @@ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlyS
464
490
  const rtlMajor = added ? ((enzymeReact as DeclaredVersion).major >= 18 ? 16 : 12) : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 16 ? rtl.major : 0;
465
491
  const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major &&
466
492
  rtlMajor > 0 && rtlSupports(rtlMajor, react.major);
467
- if (compatible) return {react: react.major, rtl: rtlMajor};
493
+ const target = {enzymeRoot: enzymeRoots[0], enzymeReact: supportedReact(enzymeReact) ? enzymeReact.major : undefined};
494
+ if (compatible) return {react: react.major, rtl: rtlMajor, ...target};
468
495
  const why: FileGate = !supportedReact(react) || !supportedReact(reactDom) || react.major !== reactDom.major ? "react" :
469
496
  rtl === undefined && !added ? "rtlMissing" : "rtl";
470
- return {react: 0, rtl: rtlMajor, why};
497
+ return {react: 0, rtl: rtlMajor, why, ...target};
471
498
  }
472
499
 
473
500
  /**
@@ -573,7 +600,7 @@ function withoutStatements(block: J.Block, removed: ReadonlySet<string>): J.Bloc
573
600
  export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
574
601
  readonly name: string = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
575
602
  readonly displayName: string = "Migrate Enzyme to React Testing Library";
576
- readonly description: string = "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 15.5 and 16) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16 or 17 with RTL 10 to 12, React 15.5+ with RTL 12, or React 18 with RTL 16, adding RTL 12, or RTL 16 with its peer `@testing-library/dom` 10, where it is missing. On React 15, whose markup differs, `html()` and DOM nodes are left for review. 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.";
603
+ readonly description: string = "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 15.5 and 16) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16 or 17 with RTL 10 to 12, React 15.5+ with RTL 12, or React 18 with RTL 16, adding RTL 12, or RTL 16 with its peer `@testing-library/dom` 10, where it is missing. This includes a shared `let` wrapper that each test assigns first, or that the last statement of a `beforeEach` assigns, where every test of it converts. On React 15, whose markup differs, `html()` and DOM nodes are left for review. 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; props, snapshots, and shallow rendering of other components are left for review.";
577
604
 
578
605
  @Option({
579
606
  displayName: "Convert positions into untagged selector matches",
@@ -588,6 +615,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
588
615
  // PERF: the sources that import Enzyme, kept from the scan to the forecast in `generate`, as the dependency steps keep
589
616
  // their manifests. Not in the accumulator, which the host keeps until the cycle ends; cleared once the forecast is made.
590
617
  private readonly tests: JS.CompilationUnit[] = [];
618
+ // What kept each render on Enzyme in the forecast, where RTL is taken to land, for the sources of a package it withholds RTL from
619
+ private readonly forecastBlockers = new Map<string, ReadonlyMap<string, string>>();
591
620
  private readonly dependencySteps = ADDS_RTL ? dependencySteps(this.forecast) : undefined;
592
621
 
593
622
  constructor(options?: {untaggedSelectorPositions?: boolean}) {
@@ -605,7 +634,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
605
634
 
606
635
  initialValue(): Scanned {
607
636
  this.tests.length = 0;
608
- return {packages: new Map(), components: new Map(), modules: new Map(), names: new Map(), nullSnapshots: new Set()};
637
+ this.forecastBlockers.clear();
638
+ return {packages: new Map(), components: new Map(), composites: new Map(), modules: new Map(), names: new Map(), nullSnapshots: new Set()};
609
639
  }
610
640
 
611
641
  // The host may prepare the visitors before there is an accumulator, so it is read only while visiting
@@ -618,6 +648,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
618
648
  const sources = new class extends JavaScriptVisitor<ExecutionContext> {
619
649
  override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
620
650
  scanned.components.set(cu.sourcePath, hostComponentExports(cu));
651
+ const composite = compositeFacts(cu);
652
+ if (composite) scanned.composites.set(cu.sourcePath, composite);
621
653
  scanned.modules.set(cu.sourcePath, moduleFacts(cu));
622
654
  scanned.names.set(cu.sourcePath, selectorNames(cu));
623
655
  if (importBindings(cu).some(({module}) => module === ENZYME)) tests.push(cu);
@@ -740,6 +772,18 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
740
772
  };
741
773
  const usages = this.usages;
742
774
  const steps = this.dependencySteps;
775
+ const forecastBlockers = this.forecastBlockers;
776
+ // Why the run added no RTL for a source, from the step that adds the RTL its package's React takes. Where the
777
+ // forecast withheld it, what kept each render on Enzyme in the forecast is what to resolve first.
778
+ const notAdded = (sourcePath: string): ReadonlyMap<string, string> => {
779
+ const target = rtlTarget(scanned.packages, sourcePath);
780
+ if (!target) return new Map([[FILE_BLOCKER, blockedByFile("rtlMissing")]]);
781
+ const outcome = !steps ? undefined : target.react18 ?
782
+ steps.dom18.outcomes.get(target.root) ?? steps.rtl18.outcomes.get(target.root) : steps.rtl.outcomes.get(target.root);
783
+ const blockers = new Map([[FILE_BLOCKER, blockedByPackage(target.root, outcome)]]);
784
+ if (outcome?.kind === "withheld") forecastBlockers.get(sourcePath)?.forEach((why, id) => blockers.set(id, why));
785
+ return blockers;
786
+ };
743
787
  const untaggedPositions = this.untaggedSelectorPositions !== false;
744
788
  const snapshots = this.snapshots;
745
789
  return check(and(not(isVendoredOrBundled()), or(usesMethod("enzyme mount(..)"), usesMethod("enzyme shallow(..)"))), new class extends JavaScriptVisitor<ExecutionContext> {
@@ -754,12 +798,15 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
754
798
  private readonly mounts = new Map<string, ConvertedRender>();
755
799
  private imports: ReadonlyMap<string, ImportedExport> = new Map();
756
800
  private importedNames: ReadonlySet<string> = new Set();
801
+ private bindings: ReturnType<typeof importBindings> = [];
757
802
  private declaredHost: ReadonlySet<string> = new Set();
758
803
  private readonly uses = new Map<string, WrapperRead>();
759
804
  private readonly removedStatements = new Set<string>();
760
805
  private readonly unmounts = new Set<string>();
761
806
  private readonly declarations = new Set<string>();
762
807
  private readonly pending = new Set<string>();
808
+ // The renders of shared wrappers, whose shape the recipe converts, so blockShapes leaves them alone
809
+ private readonly sharedRenders = new Set<string>();
763
810
  private readonly reformat = new Set<string>();
764
811
  private readonly hoists = new Map<string, HoistedElement>();
765
812
  private readonly hoistedMounts = new Map<string, string>();
@@ -774,12 +821,13 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
774
821
 
775
822
  override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
776
823
  this.sourcePath = cu.sourcePath;
777
- [this.mounts, this.uses, this.removedStatements, this.unmounts, this.declarations, this.pending, this.reformat].forEach(ids => ids.clear());
824
+ [this.mounts, this.uses, this.removedStatements, this.unmounts, this.declarations, this.pending, this.reformat, this.sharedRenders].forEach(ids => ids.clear());
778
825
  this.hoists.clear();
779
826
  this.hoistedMounts.clear();
780
827
  this.rows.length = 0;
781
828
  this.blockers.clear();
782
829
  if (!dry) RENDER_BLOCKERS.delete(cu.sourcePath);
830
+ if (!dry) await this.readSelectors(cu);
783
831
  this.names = namesUsedIn(cu);
784
832
  const prettierStyle = findMarker<PrettierStyle>(cu, StyleKind.PrettierStyle);
785
833
  this.prettier = prettierStyle !== undefined && !prettierStyle.ignored && await formattedBy(cu, prettierStyle);
@@ -795,10 +843,12 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
795
843
  if (!this.enabled) {
796
844
  // Every render of the file stays on Enzyme for the same reason
797
845
  const why = this.reactMajor === 0 ? incompatibility(scanned.packages, cu.sourcePath, landed) : "commonjs";
798
- if (!dry && why) RENDER_BLOCKERS.set(cu.sourcePath, new Map([[FILE_BLOCKER, blockedByFile(why)]]));
846
+ if (dry && why && why !== "rtlMissing") forecastBlockers.set(cu.sourcePath, new Map([[FILE_BLOCKER, blockedByFile(why)]]));
847
+ if (!dry && why) RENDER_BLOCKERS.set(cu.sourcePath, why === "rtlMissing" ? notAdded(cu.sourcePath) : new Map([[FILE_BLOCKER, blockedByFile(why)]]));
799
848
  return cu;
800
849
  }
801
850
  this.imports = relativeImports(cu, scanned.components);
851
+ this.bindings = importBindings(cu);
802
852
  this.importedNames = importedNames(cu);
803
853
  this.declaredHost = hostComponentsDeclared(cu);
804
854
  // Templates lay out what they insert with the source's Prettier style, which a source its config does not lay out keeps out of
@@ -813,8 +863,10 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
813
863
  const visited = await super.visitJsCompilationUnit(visiting, ctx);
814
864
  if (dry) {
815
865
  if (this.rows.some(row => row.status === "CONVERTED")) dry.converted.add(cu.sourcePath);
866
+ if (this.blockers.size > 0) forecastBlockers.set(cu.sourcePath, new Map(this.blockers));
816
867
  } else {
817
868
  this.rows.forEach(row => usages.insertRow(ctx, row));
869
+ await this.blockShapes(cu, ctx);
818
870
  if (this.blockers.size > 0) RENDER_BLOCKERS.set(cu.sourcePath, new Map(this.blockers));
819
871
  }
820
872
  if (!foreign || !visited) return visited;
@@ -834,9 +886,23 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
834
886
  const converted = await this.convertBlock(candidate, ctx);
835
887
  this.cursor = original;
836
888
  // Each test's wrapper converts, or the shared wrapper and every test keep Enzyme
837
- if (mounts.every(id => this.mounts.has(id) && !this.pending.has(id))) return this.renderedInHooks(converted as J.Block, block, shared, ctx);
889
+ if (mounts.every(({id}) => this.mounts.has(id) && !this.pending.has(id))) return this.renderedInHooks(converted as J.Block, block, shared, ctx);
890
+ // What kept each test's copy of the render on Enzyme is what keeps the shared render there
891
+ const kept = new Map<string, string>();
892
+ for (const {id, from} of mounts) {
893
+ const why = this.blockers.get(id);
894
+ if (why && !kept.has(from)) kept.set(from, why);
895
+ }
896
+ for (const {id, from, name} of mounts) {
897
+ if (!kept.has(from) && this.mounts.has(id) && !this.pending.has(id)) kept.set(from, blockedByShared(name));
898
+ }
838
899
  this.restoreState(saved);
839
- return this.convertBlock(block, ctx);
900
+ const plain = await this.convertBlock(block, ctx);
901
+ mounts.forEach(({from}) => this.sharedRenders.add(from));
902
+ kept.forEach((why, id) => {
903
+ if (!this.blockers.has(id)) this.blockers.set(id, why);
904
+ });
905
+ return plain;
840
906
  }
841
907
 
842
908
  /**
@@ -947,7 +1013,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
947
1013
  * cleanup in `afterEach`, or the tests clearing it. An unmount that `afterEach` does before other statements
948
1014
  * becomes RTL's `cleanup()`, which keeps the order, and one after them is dropped, as RTL unmounts after them too.
949
1015
  */
950
- private async mountedInEachTest(block: J.Block, shared: SharedWrapper[], ctx: ExecutionContext): Promise<{candidate: J.Block, mounts: string[]}> {
1016
+ private async mountedInEachTest(block: J.Block, shared: SharedWrapper[], ctx: ExecutionContext): Promise<{candidate: J.Block, mounts: {id: string, from: string, name: string}[]}> {
951
1017
  const names = new Map<string, string>();
952
1018
  shared.forEach(wrapper => wrapper.assignments.forEach(id => names.set(id, wrapper.name)));
953
1019
  const cleanup = new Set(shared.flatMap(wrapper => [...wrapper.cleanup]));
@@ -961,7 +1027,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
961
1027
  };
962
1028
  const removed = new Set(shared.flatMap(wrapper => [wrapper.declaration.id, ...wrapper.afterEach && whole(wrapper.afterEach) ? [wrapper.afterEach.id] : []]));
963
1029
  const trimmed = withoutStatements(block, removed);
964
- const mounts: string[] = [];
1030
+ const mounts: {id: string, from: string, name: string}[] = [];
965
1031
  const outer = this;
966
1032
  const candidate = await new class extends JavaScriptVisitor<ExecutionContext> {
967
1033
  override async visitBlock(inner: J.Block, p: ExecutionContext): Promise<J | undefined> {
@@ -1003,7 +1069,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
1003
1069
  const declare = Template.builder().code(`const ${name} = `).param(assignment.assignment.element).build();
1004
1070
  const declared = await declare.apply(statement.element, cursor) as J.VariableDeclarations | undefined;
1005
1071
  if (!declared) throw new Error(`Cannot declare ${name}`);
1006
- mounts.push(declared.variables[0].element.initializer!.element.id);
1072
+ mounts.push({id: declared.variables[0].element.initializer!.element.id, from: assignment.assignment.element.id, name});
1007
1073
  statements.push({...statement, element: {...declared, prefix: statement.element.prefix}});
1008
1074
  }
1009
1075
  return withoutStatements(create(visited, draft => {
@@ -1021,7 +1087,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
1021
1087
  const declare = Template.builder().code(`const ${hooked.name} = `).param(withNewIds(hooked.mount)).build();
1022
1088
  const declared = await declare.apply(first.element, cursor) as J.VariableDeclarations | undefined;
1023
1089
  if (!declared) throw new Error(`Cannot declare ${hooked.name}`);
1024
- mounts.push(declared.variables[0].element.initializer!.element.id);
1090
+ mounts.push({id: declared.variables[0].element.initializer!.element.id, from: hooked.mount.id, name: hooked.name});
1025
1091
  const semicolon = test.statements.some(padded => padded.markers.markers.some(marker => marker.kind === J.Markers.Semicolon));
1026
1092
  const padded = {...first, element: {...declared, prefix: first.element.prefix},
1027
1093
  markers: {...first.markers, markers: semicolon ? [{kind: J.Markers.Semicolon, id: randomId()}] : []}};
@@ -1072,7 +1138,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
1072
1138
  // React 15 marks its markup with `data-reactroot` and empty renders with comments, which Enzyme's html() leaves out
1073
1139
  const markup = this.reactMajor >= 16;
1074
1140
  let blocking: Parameters<typeof blockedByUses>[0] | undefined;
1075
- const scope = analyzeWrapperScope(this.cursor, candidate, {events: reads.simulate ? this.events.events : new Set(), html: reads.html && markup, untaggedPositions, hostNames, snapshots: snapshots && markup, optionalChaining: this.optionalChaining,
1141
+ const scope = analyzeWrapperScope(this.cursor, candidate, {events: reads.simulate ? this.events.events : new Set(), html: reads.html && markup, untaggedPositions, hostNames, snapshots: snapshots && markup, optInSnapshots: !snapshots && markup, optionalChaining: this.optionalChaining,
1076
1142
  constant: node => this.constantString(node), blocked: references => blocking = references});
1077
1143
  if (!scope) {
1078
1144
  if (blocking) this.blockers.set(candidate.mount.id, await blockedByUses(blocking));
@@ -1345,7 +1411,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
1345
1411
  if (api !== "shallow" || call.arguments.elements.length !== 1) return undefined;
1346
1412
  const element = call.arguments.elements[0]?.element;
1347
1413
  if (rendersHostElements(element, this.imports, scanned.components, this.importedNames, this.declaredHost)) return api;
1348
- this.blockers.set(call.id, blockedByGate("shallow"));
1414
+ this.blockers.set(call.id, blockedByShallow(shallowMiss(element, this.imports, scanned.components, scanned.composites, this.bindings)));
1349
1415
  return undefined;
1350
1416
  }
1351
1417
 
@@ -1380,6 +1446,74 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
1380
1446
  return {roots, declares, resolve: resolver(scanned.modules, [...new Set([...roots, ""])], declares)};
1381
1447
  }
1382
1448
 
1449
+ /** Records what each `find` selector of `cu` written as other than a literal holds, for its review row. */
1450
+ /** Names the shape that kept each render the conversion didn't analyze, where the shape says why. */
1451
+ private async blockShapes(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<void> {
1452
+ const blockers = this.blockers;
1453
+ const mounts = this.mounts;
1454
+ const sharedRenders = this.sharedRenders;
1455
+ await new class extends JavaScriptVisitor<ExecutionContext> {
1456
+ override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
1457
+ const api = enzymeMethod(method);
1458
+ if ((api === "mount" || api === "shallow") && !blockers.has(method.id) && !mounts.has(method.id) && !sharedRenders.has(method.id)) {
1459
+ const why = blockedByShape(this.cursor);
1460
+ if (why) blockers.set(method.id, why);
1461
+ }
1462
+ return super.visitMethodInvocation(method, ctx);
1463
+ }
1464
+ }().visit(cu, ctx);
1465
+ }
1466
+
1467
+ private async readSelectors(cu: JS.CompilationUnit): Promise<void> {
1468
+ SELECTOR_VALUES.delete(cu.sourcePath);
1469
+ const finds: J.MethodInvocation[] = [];
1470
+ walk(cu, tree => {
1471
+ if (tree.kind === J.Kind.MethodInvocation && enzymeMethod(tree as J.MethodInvocation) === "find" &&
1472
+ (tree as J.MethodInvocation).arguments.elements.length === 1) finds.push(tree as J.MethodInvocation);
1473
+ return true;
1474
+ });
1475
+ const topLevel = new Set(cu.statements.map(({element}) =>
1476
+ element.kind === JS.Kind.ExportDeclaration ? (element as JS.ExportDeclaration).exportClause?.id : element.id));
1477
+ // The resolver reads only top-level constants, so a name a nested `const` declares may hold a string after all
1478
+ const nested = new Set<string>();
1479
+ walk(cu, tree => {
1480
+ if (tree.kind !== J.Kind.VariableDeclarations || topLevel.has(tree.id)) return true;
1481
+ const variables = tree as J.VariableDeclarations;
1482
+ if (!variables.modifiers.some(modifier => modifier.keyword === "const")) return true;
1483
+ for (const {element: variable} of variables.variables) {
1484
+ if (isIdentifier(variable.name) && variable.initializer && stringParts(variable.initializer.element)) nested.add(variable.name.simpleName);
1485
+ }
1486
+ return true;
1487
+ });
1488
+ const reads = new Map<string, SelectorRead>();
1489
+ for (const find of finds) {
1490
+ const read = await this.selectorRead(find.arguments.elements[0].element, nested);
1491
+ if (read) reads.set(find.id, read);
1492
+ }
1493
+ if (reads.size > 0) SELECTOR_VALUES.set(cu.sourcePath, reads);
1494
+ }
1495
+
1496
+ /** What a selector holds that is a template or a string-typed name, or the first part of it that isn't a constant string. */
1497
+ private async selectorRead(selector: J, nested: ReadonlySet<string>): Promise<SelectorRead | undefined> {
1498
+ const named = (name: string) => evaluate([{name}], this.sourcePath, scanned.modules, this.moduleResolution().resolve);
1499
+ const printed = async (node: J) => (await TreePrinters.printer(JS.Kind.CompilationUnit).print(node)).trim().replace(/\s+/g, " ");
1500
+ if (selector.kind === JS.Kind.TemplateExpression) {
1501
+ const value = this.constantString(selector);
1502
+ if (value !== undefined) return {value};
1503
+ for (const {element: span} of (selector as JS.TemplateExpression).spans) {
1504
+ const part = span.expression;
1505
+ if (isIdentifier(part) && nested.has(part.simpleName)) return undefined;
1506
+ if (!isIdentifier(part) || named(part.simpleName) === undefined) return {unread: await printed(part)};
1507
+ }
1508
+ return undefined;
1509
+ }
1510
+ const value = isIdentifier(selector) ? named(selector.simpleName) : undefined;
1511
+ if (value !== undefined) return {value};
1512
+ // A name that isn't a constant string may hold a component or props, which only its type tells apart
1513
+ if (TypedTree.getType(selector) !== Type.Primitive.String || isIdentifier(selector) && nested.has(selector.simpleName)) return undefined;
1514
+ return isIdentifier(selector) || selector.kind === J.Kind.FieldAccess ? {unread: await printed(selector)} : undefined;
1515
+ }
1516
+
1383
1517
  /** The string a template of `const` strings holds, from the test or the modules it imports them from. */
1384
1518
  private constantString(node: J): string | undefined {
1385
1519
  const parts = stringParts(node);
@@ -35,6 +35,19 @@ export const RENDER_BLOCKERS = new Map<string, ReadonlyMap<string, string>>();
35
35
  /** The key of {@link RENDER_BLOCKERS} for what keeps every render of a source on Enzyme. */
36
36
  export const FILE_BLOCKER = "*";
37
37
 
38
+ /** What the converter read of a `find` selector written as other than a literal: the string it holds, or the part it can't read. */
39
+ export type SelectorRead = {value: string} | {unread: string};
40
+
41
+ /** Each {@link SelectorRead} of a source, by the `find` call, for the review row `FindEnzymeUsage` writes after the converter. */
42
+ export const SELECTOR_VALUES = new Map<string, ReadonlyMap<string, SelectorRead>>();
43
+
44
+ /** The suggested action for a `find` whose selector is a string the recipe can't read, built from `unread`. */
45
+ export function unreadSelector(unread: string): string {
46
+ return `The recipe can't read this selector as a string: \`${unread}\` isn't a \`const\` string, or a template of \`const\` strings, that the recipe finds in this test or in a module it imports by a relative path or \`baseUrl\`. ` +
47
+ "Where the selector is a tag, class, id or attribute selector, write `container.querySelectorAll` with the same expression by hand. " +
48
+ "Enzyme also counts components given that class, id or attribute, so compare the counts.";
49
+ }
50
+
38
51
  export function enzymeModule(value: unknown): value is string {
39
52
  return typeof value === "string" && (value === ENZYME || value.startsWith("enzyme/") ||
40
53
  (value === "enzyme-to-json" || value.startsWith("enzyme-to-json/")) || /^(?:@[^/]+\/)?enzyme-adapter-/.test(value));
@@ -401,10 +401,19 @@ export function wrapperDeclaration<R>(statement: J | undefined, classify: (rende
401
401
  * admits `expect(wrapper).toMatchSnapshot()` and `expect(toJson(wrapper)).toMatchSnapshot()`, whose
402
402
  * snapshot RTL records as the DOM rather than Enzyme's tree. `hostNames` decides the selectors {@link selectorLiteral} accepts.
403
403
  */
404
+ /** A reference that keeps a wrapper on Enzyme, with the `toMatchSnapshot` call where it is a snapshot assertion the snapshot recipe converts. */
405
+ export interface BlockingReference {
406
+ cursor: Cursor;
407
+ unmounted: boolean;
408
+ snapshot?: J.MethodInvocation;
409
+ }
410
+
404
411
  export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperDeclaration,
405
- {events, html, untaggedPositions, hostNames, snapshots = false, optionalChaining = true, constant = () => undefined, blocked}: {events: ReadonlySet<string>, html: boolean, untaggedPositions: boolean, hostNames: HostNames, snapshots?: boolean, optionalChaining?: boolean, constant?: (node: J) => string | undefined,
406
- /** Told every reference that rejects the scope, and whether it comes after an unmount. */
407
- blocked?: (references: {cursor: Cursor, unmounted: boolean}[]) => void}): WrapperScope | undefined {
412
+ {events, html, untaggedPositions, hostNames, snapshots = false, optInSnapshots = false, optionalChaining = true, constant = () => undefined, blocked}: {events: ReadonlySet<string>, html: boolean, untaggedPositions: boolean, hostNames: HostNames, snapshots?: boolean,
413
+ /** Whether the snapshot recipe would convert the snapshot assertions this analysis rejects. */
414
+ optInSnapshots?: boolean, optionalChaining?: boolean, constant?: (node: J) => string | undefined,
415
+ /** Told every reference that rejects the scope, whether it comes after an unmount, and the snapshot assertion it is the subject of. */
416
+ blocked?: (references: BlockingReference[]) => void}): WrapperScope | undefined {
408
417
  let serializers: ReadonlySet<string> | undefined;
409
418
  const uses = new Map<string, WrapperRead>();
410
419
  const removedStatements = new Set<string>();
@@ -438,9 +447,14 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
438
447
  return undefined;
439
448
  };
440
449
 
441
- const use = (identifier: J.Identifier, reference: Cursor): boolean => {
450
+ const ancestorsOf = (reference: Cursor): Cursor[] => {
442
451
  const ancestors: Cursor[] = [];
443
452
  for (let c: Cursor | undefined = reference.parentTree(); c && ancestors.length < 5; c = c.parentTree()) ancestors.push(c);
453
+ return ancestors;
454
+ };
455
+
456
+ const use = (identifier: J.Identifier, reference: Cursor): boolean => {
457
+ const ancestors = ancestorsOf(reference);
444
458
  const first = ancestors[0]?.value as J | undefined;
445
459
  if (snapshots) {
446
460
  serializers ??= snapshotSerializers(block);
@@ -545,13 +559,20 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
545
559
  const declared = new Cursor(variable.name, variableCursor(block, declaration));
546
560
  const references = referencesOf(declared, name, "value");
547
561
  if (!references.some(reference => reference.identifier === variable.name)) return undefined;
548
- const rejected: {cursor: Cursor, unmounted: boolean}[] = [];
562
+ const rejected: BlockingReference[] = [];
549
563
  for (const reference of references) {
550
564
  if (reference.identifier === variable.name) continue;
551
565
  const after = unmounted;
552
566
  if (reference.declares || after || !use(reference.identifier, reference.cursor)) {
553
567
  if (!blocked) return undefined;
554
- rejected.push({cursor: reference.cursor, unmounted: after});
568
+ let snapshot: J.MethodInvocation | undefined;
569
+ if (optInSnapshots && !after && !reference.declares) {
570
+ serializers ??= snapshotSerializers(block);
571
+ const ancestors = ancestorsOf(reference.cursor);
572
+ const expectCall = snapshotAssertion(reference.identifier, ancestors, serializers);
573
+ snapshot = expectCall && ancestors.find(c => c.value.kind === J.Kind.MethodInvocation && (c.value as J.MethodInvocation).select?.element === expectCall)?.value;
574
+ }
575
+ rejected.push({cursor: reference.cursor, unmounted: after, snapshot});
555
576
  }
556
577
  }
557
578
  if (rejected.length > 0) {
@@ -570,14 +570,20 @@ export function storeFindings(call: J.MethodInvocation, cu: JS.CompilationUnit,
570
570
  const options = objectProperties(call.arguments.elements[0]?.element);
571
571
  if (!options) return {api, findings: [{reason: "OPTIONS_NOT_LITERAL", detail: ""}], slices};
572
572
  const findings: Finding[] = [];
573
- for (const key of options.keys()) {
574
- if (key !== "reducer") findings.push({reason: BLOCKING_OPTIONS[key] ?? "UNKNOWN_OPTION", detail: key});
573
+ for (const [key, value] of options) {
574
+ if (key === "reducer") continue;
575
+ const action = optionAction(key, value, options.get("reducer"), cu);
576
+ findings.push({reason: BLOCKING_OPTIONS[key] ?? "UNKNOWN_OPTION", detail: key, ...action ? {action} : {}});
575
577
  }
576
- // A store of its `reducer` alone can also move to zustand whole, driven by that reducer
578
+ // A store of its `reducer` alone can also move to zustand whole, driven by that reducer, as can one whose other
579
+ // options only change what development builds check, which a plain `configureStore` checks and the move drops too
577
580
  const reducer = options.get("reducer");
578
- const reducerStore = options.size !== 1 || !reducer ? undefined : reducer.kind === J.Kind.NewClass && !(reducer as J.NewClass).class ? "combined" : "reducer";
581
+ const reducerStore = !reducer || [...options].some(([key, value]) => key !== "reducer" && !developmentOnly(key, value)) ? undefined : reducer.kind === J.Kind.NewClass && !(reducer as J.NewClass).class ? "combined" : "reducer";
579
582
  const reducers = objectProperties(options.get("reducer"));
580
- if (!reducers) return {api, findings: [...findings, {reason: "ROOT_REDUCER", detail: ""}], slices, reducerStore};
583
+ if (!reducers) {
584
+ const action = rootReducerAction(reducer, reducerStore !== undefined, cu);
585
+ return {api, findings: [...findings, {reason: "ROOT_REDUCER", detail: "", ...action ? {action} : {}}], slices, reducerStore};
586
+ }
581
587
  const local = localSlices(cu);
582
588
  for (const [key, value] of reducers) {
583
589
  const slice = resolveSliceReducer(value, cu, local, modules, resolve);
@@ -588,6 +594,114 @@ export function storeFindings(call: J.MethodInvocation, cu: JS.CompilationUnit,
588
594
  return {api, findings, slices, reducerStore};
589
595
  }
590
596
 
597
+ /** What to do about the `configureStore` option `key: value`, where it says more than the option's reason does. */
598
+ function optionAction(key: string, value: J, reducer: J | undefined, cu: JS.CompilationUnit): string | undefined {
599
+ if (developmentOnly(key, value)) return key === "devTools" ?
600
+ "`devTools` only connects the Redux DevTools extension, which a store that moves whole drops, as it drops a plain `configureStore`'s: remove what the store's other rows name, and it moves whole, where `wholeStores` is on." :
601
+ "`middleware` only sets the development checks of the default middleware, which a store that moves whole drops, as it drops a plain `configureStore`'s: remove what the store's other rows name, and it moves whole, where `wholeStores` is on.";
602
+ if (key !== "middleware") return undefined;
603
+ const actions: string[] = [];
604
+ // An RTK Query API adds its middleware and its reducer, the latter under `[api.reducerPath]`
605
+ const apis = new Set<string>();
606
+ walk(value, tree => {
607
+ const access = tree as J.FieldAccess;
608
+ if (tree.kind === J.Kind.FieldAccess && access.name.element.simpleName === "middleware" && isIdentifier(access.target)) apis.add(access.target.simpleName);
609
+ return true;
610
+ });
611
+ const reducedApis = new Set<string>();
612
+ if (reducer) walk(reducer, tree => {
613
+ const access = tree as J.FieldAccess;
614
+ if (tree.kind === J.Kind.FieldAccess && ["reducer", "reducerPath"].includes(access.name.element.simpleName) && isIdentifier(access.target) && apis.has(access.target.simpleName)) reducedApis.add(access.target.simpleName);
615
+ return true;
616
+ });
617
+ const made = madeBy(cu);
618
+ const read = namesReferencedWithin(value);
619
+ const by = (module: string, ...names: string[]) => {
620
+ const locals = importedAs(cu, module, ...names);
621
+ return [...read].some(name => locals.has(name) || locals.has(made.get(name)?.name.simpleName ?? ""));
622
+ };
623
+ if (reducedApis.size > 0) actions.push(`\`${[...reducedApis][0]}.middleware\` is RTK Query's, which has no zustand equivalent: keep this store in Redux, or move its queries to a data-fetching library, such as TanStack Query, by hand.`);
624
+ if (by("redux-saga", "default")) actions.push("redux-saga runs its sagas on the actions the store dispatches, which zustand has no middleware for: rewrite the sagas as functions that call the store, or keep this store in Redux.");
625
+ if ([...apis].some(api => importedAs(cu, RTK, "createListenerMiddleware").has(made.get(api)?.name.simpleName ?? ""))) actions.push("RTK's listener middleware runs its effects on the actions the store dispatches: rewrite them with the zustand store's `subscribe`, or keep this store in Redux.");
626
+ if (by("redux-logger", "default", "logger", "createLogger")) actions.push("redux-logger logs each action the store dispatches: remove it, or use zustand's `devtools` middleware to watch the store, and convert by hand.");
627
+ return actions.length > 0 ? actions.join(" ") : undefined;
628
+ }
629
+
630
+ /** The function each top-level `const` of `cu` is the result of calling, such as `createSagaMiddleware` for `const saga = createSagaMiddleware()`. */
631
+ function madeBy(cu: JS.CompilationUnit): Map<string, J.MethodInvocation> {
632
+ const made = new Map<string, J.MethodInvocation>();
633
+ for (const {element} of cu.statements) {
634
+ if (element.kind !== J.Kind.VariableDeclarations) continue;
635
+ for (const {element: variable} of (element as J.VariableDeclarations).variables) {
636
+ const initializer = variable.initializer?.element;
637
+ if (isIdentifier(variable.name) && initializer?.kind === J.Kind.MethodInvocation && !(initializer as J.MethodInvocation).select) {
638
+ made.set(variable.name.simpleName, initializer as J.MethodInvocation);
639
+ }
640
+ }
641
+ }
642
+ return made;
643
+ }
644
+
645
+ /**
646
+ * What to do about a `configureStore`'s `reducer` that isn't an object of reducers, where that is known: `whole` when
647
+ * nothing else in the call keeps the store from moving whole, driven by that reducer.
648
+ */
649
+ function rootReducerAction(reducer: J | undefined, whole: boolean, cu: JS.CompilationUnit): string | undefined {
650
+ if (!reducer) return undefined;
651
+ const call = reducer.kind === J.Kind.MethodInvocation && !(reducer as J.MethodInvocation).select ? reducer as J.MethodInvocation :
652
+ isIdentifier(reducer) ? madeBy(cu).get(reducer.simpleName) : undefined;
653
+ const by = (module: string, name: string) => call !== undefined && importedAs(cu, module, name).has(call.name.simpleName);
654
+ if (by("redux-persist", "persistReducer")) return "`reducer` is redux-persist's `persistReducer`, and redux-persist persists a Redux store: convert the store by hand, with zustand's `persist` middleware in place of redux-persist.";
655
+ if (whole) return "A store of a single root reducer moves whole, as one zustand store that the reducer drives: remove what the store's other rows name, and it moves whole, where `wholeStores` is on.";
656
+ if ((by(REDUX, "combineReducers") || by(RTK, "combineReducers")) && objectProperties(call!.arguments.elements[0]?.element)) {
657
+ const name = isIdentifier(reducer) ? `\`${reducer.simpleName}\`` : "`reducer`";
658
+ return `${name} is \`combineReducers\` of an object of reducers: pass that object as \`reducer\` instead, which \`configureStore\` combines the same way, and the store's slices are read.`;
659
+ }
660
+ return undefined;
661
+ }
662
+
663
+ /** The checks of Redux Toolkit's default middleware, which it runs only in development. */
664
+ const DEVELOPMENT_CHECKS = new Set(["serializableCheck", "immutableCheck", "actionCreatorCheck"]);
665
+
666
+ /**
667
+ * Whether the `configureStore` option `key: value` changes only what a development build checks or shows: `devTools`
668
+ * of any value without effects, or `middleware` of `getDefaultMiddleware => getDefaultMiddleware({...})` that sets
669
+ * only its checks, so that the store's middleware is still the default thunk.
670
+ */
671
+ export function developmentOnly(key: string, value: J): boolean {
672
+ if (key === "devTools") return withoutEffects(value);
673
+ if (key !== "middleware") return false;
674
+ const lambda = lambdaOf(value);
675
+ const parameters = lambda ? parametersOf(lambda) : [];
676
+ const name = parameters.length === 1 ? plainParameter(parameters[0]) : undefined;
677
+ if (!lambda || !name) return false;
678
+ let body: J | undefined = lambda.body;
679
+ if (body.kind === J.Kind.Block) {
680
+ const statements = (body as J.Block).statements;
681
+ body = statements.length === 1 && statements[0].element.kind === J.Kind.Return ? (statements[0].element as J.Return).expression : undefined;
682
+ }
683
+ if (body?.kind !== J.Kind.MethodInvocation) return false;
684
+ const call = body as J.MethodInvocation;
685
+ if (call.select || call.name.simpleName !== name) return false;
686
+ const args = call.arguments.elements.map(e => e.element).filter(e => e.kind !== J.Kind.Empty);
687
+ if (args.length === 0) return true;
688
+ const checks = args.length === 1 ? objectProperties(args[0]) : undefined;
689
+ // NOTE: `objectProperties` reads only `key: value` and shorthand properties, so a spread leaves it undefined
690
+ return checks !== undefined && [...checks].every(([check, setting]) => DEVELOPMENT_CHECKS.has(check) && withoutEffects(setting));
691
+ }
692
+
693
+ /** Whether evaluating `node` can do nothing but compute a value: it calls, constructs, assigns and awaits nothing. */
694
+ export function withoutEffects(node: J): boolean {
695
+ let effects = false;
696
+ walk(node, tree => {
697
+ // An object literal is a `NewClass` of no class
698
+ if (tree.kind === J.Kind.MethodInvocation || tree.kind === J.Kind.NewClass && (tree as J.NewClass).class || tree.kind === J.Kind.Assignment ||
699
+ tree.kind === J.Kind.AssignmentOperation || tree.kind === JS.Kind.Await || tree.kind === J.Kind.Lambda || tree.kind === JS.Kind.ArrowFunction) effects = true;
700
+ return !effects;
701
+ });
702
+ return !effects;
703
+ }
704
+
591
705
  /** The variable or function a store is created in, such as `store` in `export const store = configureStore(...)`. */
592
706
  export function storeName(cursor: Cursor): string {
593
707
  for (let c: Cursor | undefined = cursor.parent; c; c = c.parent) {