@openrewrite/recipes-react 0.20.0 → 0.21.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 (86) hide show
  1. package/dist/i18n/translate-hard-coded-strings.d.ts +67 -0
  2. package/dist/i18n/translate-hard-coded-strings.d.ts.map +1 -0
  3. package/dist/i18n/translate-hard-coded-strings.js +439 -0
  4. package/dist/i18n/translate-hard-coded-strings.js.map +1 -0
  5. package/dist/index.d.ts +2 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +10 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/search/find-enzyme-usage.d.ts +4 -0
  10. package/dist/search/find-enzyme-usage.d.ts.map +1 -1
  11. package/dist/search/find-enzyme-usage.js +30 -3
  12. package/dist/search/find-enzyme-usage.js.map +1 -1
  13. package/dist/search/find-hard-coded-strings.d.ts +110 -0
  14. package/dist/search/find-hard-coded-strings.d.ts.map +1 -0
  15. package/dist/search/find-hard-coded-strings.js +987 -0
  16. package/dist/search/find-hard-coded-strings.js.map +1 -0
  17. package/dist/search/find-missing-use-client-directive.d.ts +2 -0
  18. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -1
  19. package/dist/search/find-missing-use-client-directive.js +1 -0
  20. package/dist/search/find-missing-use-client-directive.js.map +1 -1
  21. package/dist/testing/enzyme-portals.d.ts +3 -5
  22. package/dist/testing/enzyme-portals.d.ts.map +1 -1
  23. package/dist/testing/enzyme-portals.js +8 -39
  24. package/dist/testing/enzyme-portals.js.map +1 -1
  25. package/dist/testing/enzyme-render-blockers.d.ts +10 -0
  26. package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
  27. package/dist/testing/enzyme-render-blockers.js +119 -0
  28. package/dist/testing/enzyme-render-blockers.js.map +1 -0
  29. package/dist/testing/enzyme-to-react-testing-library.d.ts +9 -2
  30. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  31. package/dist/testing/enzyme-to-react-testing-library.js +80 -17
  32. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  33. package/dist/testing/enzyme-usage.d.ts +2 -0
  34. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  35. package/dist/testing/enzyme-usage.js +29 -3
  36. package/dist/testing/enzyme-usage.js.map +1 -1
  37. package/dist/testing/enzyme-wrapper-scope.d.ts +5 -1
  38. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  39. package/dist/testing/enzyme-wrapper-scope.js +12 -3
  40. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  41. package/dist/util/json-and-javascript.d.ts +4 -0
  42. package/dist/util/json-and-javascript.d.ts.map +1 -0
  43. package/dist/util/json-and-javascript.js +37 -0
  44. package/dist/util/json-and-javascript.js.map +1 -0
  45. package/dist/util/module-imports.d.ts +36 -0
  46. package/dist/util/module-imports.d.ts.map +1 -1
  47. package/dist/util/module-imports.js +216 -0
  48. package/dist/util/module-imports.js.map +1 -1
  49. package/dist/util/test-source.d.ts +2 -0
  50. package/dist/util/test-source.d.ts.map +1 -0
  51. package/dist/util/test-source.js +5 -0
  52. package/dist/util/test-source.js.map +1 -0
  53. package/dist/zustand/entry-store.d.ts +9 -0
  54. package/dist/zustand/entry-store.d.ts.map +1 -0
  55. package/dist/zustand/entry-store.js +136 -0
  56. package/dist/zustand/entry-store.js.map +1 -0
  57. package/dist/zustand/redux-stores.d.ts +5 -4
  58. package/dist/zustand/redux-stores.d.ts.map +1 -1
  59. package/dist/zustand/redux-stores.js +8 -5
  60. package/dist/zustand/redux-stores.js.map +1 -1
  61. package/dist/zustand/redux-to-zustand.d.ts +11 -2
  62. package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
  63. package/dist/zustand/redux-to-zustand.js +137 -42
  64. package/dist/zustand/redux-to-zustand.js.map +1 -1
  65. package/dist/zustand/zustand-plan.d.ts +7 -5
  66. package/dist/zustand/zustand-plan.d.ts.map +1 -1
  67. package/dist/zustand/zustand-plan.js +87 -33
  68. package/dist/zustand/zustand-plan.js.map +1 -1
  69. package/package.json +1 -1
  70. package/src/i18n/translate-hard-coded-strings.ts +442 -0
  71. package/src/index.ts +7 -0
  72. package/src/search/find-enzyme-usage.ts +30 -6
  73. package/src/search/find-hard-coded-strings.ts +1006 -0
  74. package/src/search/find-missing-use-client-directive.ts +1 -1
  75. package/src/testing/enzyme-portals.ts +4 -44
  76. package/src/testing/enzyme-render-blockers.ts +113 -0
  77. package/src/testing/enzyme-to-react-testing-library.ts +90 -18
  78. package/src/testing/enzyme-usage.ts +35 -2
  79. package/src/testing/enzyme-wrapper-scope.ts +13 -2
  80. package/src/util/json-and-javascript.ts +26 -0
  81. package/src/util/module-imports.ts +223 -0
  82. package/src/util/test-source.ts +2 -0
  83. package/src/zustand/entry-store.ts +131 -0
  84. package/src/zustand/redux-stores.ts +12 -7
  85. package/src/zustand/redux-to-zustand.ts +168 -48
  86. package/src/zustand/zustand-plan.ts +98 -32
@@ -19,7 +19,7 @@ const CLIENT_HOOKS = new Set([
19
19
  const BROWSER_GLOBALS = new Set(['window', 'document', 'localStorage', 'sessionStorage', 'navigator']);
20
20
 
21
21
  /** Directives are the string-literal statements at the top of a file. */
22
- function hasDirective(cu: JS.CompilationUnit, directive: string): boolean {
22
+ export function hasDirective(cu: JS.CompilationUnit, directive: string): boolean {
23
23
  for (const statement of cu.statements) {
24
24
  let node: any = statement.element;
25
25
  if (node.kind === JS.Kind.ExpressionStatement) node = node.expression;
@@ -1,7 +1,10 @@
1
1
  import {JS, JSX, moduleNameOf, walk} from "@openrewrite/rewrite/javascript";
2
2
  import {isIdentifier, J} from "@openrewrite/rewrite/java";
3
3
  import {posix} from "path";
4
- import {importBindings, isRelativeSpecifier, resolveRelative} from "../util/module-imports";
4
+ import {exportedNames, importBindings, isRelativeSpecifier, packageName, Resolver} from "../util/module-imports";
5
+
6
+ export {packageName, resolver} from "../util/module-imports";
7
+ export type {Resolver} from "../util/module-imports";
5
8
  import {ConstantParts, constantStrings} from "./enzyme-constant-strings";
6
9
 
7
10
  /** An import a source renders: the module, and the export of it that a JSX tag in the source names. */
@@ -74,27 +77,6 @@ export function moduleFacts(cu: JS.CompilationUnit): ModuleFacts {
74
77
  return {portal: callsCreatePortal(cu), rendered, reExports, declares, forwards, imports: imported, strings: constantStrings(cu)};
75
78
  }
76
79
 
77
- /** Each name a named export clause exports, to the name it has in the module it comes from. */
78
- function exportedNames(clause: JS.NamedExports): Map<string, string> {
79
- const names = new Map<string, string>();
80
- for (const {element: exported} of clause.elements.elements) {
81
- if (exported.kind !== JS.Kind.ExportSpecifier) continue;
82
- const named = (exported as JS.ExportSpecifier).specifier;
83
- if (isIdentifier(named)) names.set(named.simpleName, named.simpleName);
84
- if (named.kind === JS.Kind.Alias && isIdentifier((named as JS.Alias).alias)) {
85
- const property = (named as JS.Alias).propertyName.element;
86
- names.set(((named as JS.Alias).alias as J.Identifier).simpleName,
87
- isIdentifier(property) ? property.simpleName : String((property as J.Literal).value));
88
- }
89
- }
90
- return names;
91
- }
92
-
93
- /** Where module specifiers of a source resolve: relative ones as Node resolves them, bare ones through a `baseUrl` alias. */
94
- export interface Resolver {
95
- (from: string, specifier: string): string | undefined;
96
- }
97
-
98
80
  /**
99
81
  * Whether the export `name` of the source at `path` may render into a portal: the source calls
100
82
  * `createPortal`, renders a component imported from a source whose export may, or re-exports `name`
@@ -162,28 +144,6 @@ export function packagePortal(module: string, name: string): boolean {
162
144
  return exports.has(subpath !== "" && name === "default" ? subpath.split("/")[0] : name);
163
145
  }
164
146
 
165
- /** The package a bare module specifier names, such as `@scope/name` for `@scope/name/sub`. */
166
- export function packageName(specifier: string): string {
167
- const parts = specifier.split("/");
168
- return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
169
- }
170
-
171
- /**
172
- * Resolves relative specifiers among the scanned sources, and a bare one that no enclosing package
173
- * declares from each of `roots`, the way a `baseUrl` of the package or the repository resolves it.
174
- */
175
- export function resolver(modules: Modules, roots: readonly string[], declares: (name: string) => boolean): Resolver {
176
- return (from, specifier) => {
177
- const relative = resolveRelative(from, specifier, modules);
178
- if (relative || isRelativeSpecifier(specifier) || specifier.startsWith("node:") || declares(packageName(specifier))) return relative;
179
- for (const root of roots) {
180
- const aliased = resolveRelative(posix.join(root || ".", "_"), `./${specifier}`, modules);
181
- if (aliased) return aliased;
182
- }
183
- return undefined;
184
- };
185
- }
186
-
187
147
  export interface PortalContext {
188
148
  /** The test source. */
189
149
  sourcePath: string;
@@ -0,0 +1,113 @@
1
+ import {Cursor, TreePrinters} from "@openrewrite/rewrite";
2
+ import {JS} from "@openrewrite/rewrite/javascript";
3
+ import {J} from "@openrewrite/rewrite/java";
4
+ import {eventKind, selectorKind} from "../search/find-enzyme-usage";
5
+ import {migrationReason} from "./enzyme-usage";
6
+
7
+ /** Why the converter kept a render it analyzed on Enzyme, other than a use of its wrapper. */
8
+ export type RenderGate = "setProps" | "rootStyles" | "shallow" | "portal";
9
+
10
+ // The methods of Enzyme's wrappers, past which a chain reads what one returned, such as a DOM node
11
+ const ENZYME_WRAPPER_METHODS = new Set(["at", "childAt", "children", "closest", "contains", "containsAllMatchingElements",
12
+ "containsAnyMatchingElements", "containsMatchingElement", "context", "debug", "dive", "every", "everyWhere", "exists", "filter",
13
+ "filterWhere", "find", "findWhere", "first", "forEach", "get", "getDOMNode", "getElement", "getElements", "getNode", "getNodes",
14
+ "hasClass", "hostNodes", "html", "instance", "invoke", "is", "isEmptyRender", "key", "last", "map", "matchesElement", "name",
15
+ "not", "parent", "parents", "prop", "props", "reduce", "reduceRight", "ref", "render", "renderProp", "root", "setContext",
16
+ "setProps", "setState", "shallow", "simulate", "simulateError", "slice", "some", "someWhere", "state", "tap", "text", "type",
17
+ "unmount", "update"]);
18
+
19
+ // Calls that return another wrapper, which a variable then holds as Enzyme found it
20
+ const WRAPPER_RESULTS = new Set(["find", "at", "first", "last", "children", "childAt", "filter", "filterWhere", "findWhere",
21
+ "hostNodes", "closest", "parent", "parents", "dive", "not", "slice", "getElements", "getNodes"]);
22
+
23
+ const PASSED = "Blocked by a wrapper passed on: the recipe converts a wrapper only where each use is a read in the test itself. " +
24
+ "Inline what the helper reads here, or change the helper to take the element RTL queried, such as `container.querySelector(selector)`.";
25
+ const STORED = "Blocked by a stored find: Enzyme's found wrapper keeps the render as it was, while an RTL element is live. " +
26
+ "Query the element where each assertion reads it, such as `container.querySelector(selector)`, rather than keeping the found wrapper in a variable.";
27
+ const UNMOUNTED = "Blocked by a read after unmount: RTL's container is empty once the render unmounts. " +
28
+ "Assert before calling `unmount()`, or render again for what comes after.";
29
+ const FIND_HERE = "Blocked by `find`: Enzyme and the DOM can match different elements for this selector where it stands, " +
30
+ "as positions into matches of a selector without a tag in each part, or a part a component's props can match. " +
31
+ "Name the tag in each part of the selector, or call `hostNodes()` before taking a position.";
32
+ const SIMULATE_HERE = "Blocked by `simulate`: `fireEvent` doesn't dispatch this event as Enzyme does here, " +
33
+ "because React 15 and 16 need a render attached to the document, a click runs a link's or form control's default action, " +
34
+ "or the call isn't a statement of its own. Fire it as a statement on the element, or with `userEvent` where the default action is wanted.";
35
+ const GATES: Readonly<Record<RenderGate, string>> = {
36
+ setProps: "Blocked by `setProps`: the recipe writes `rerender` only for props it can merge into the element as written. " +
37
+ "Call `rerender` with the whole element and its new props.",
38
+ shallow: "Blocked by shallow rendering: the component renders other components or runs effects, which `shallow` leaves out and RTL's `render` runs. " +
39
+ "Render it with `render` and assert on what the whole tree renders. Where a test relies on a child not rendering, `jest.mock` that child's module with a stub.",
40
+ portal: "Blocked by a portal: a component it renders may render into a portal, which RTL renders outside the container. " +
41
+ "Query `screen` or `baseElement` for that content instead of the wrapper.",
42
+ rootStyles: "Blocked by root styles: a component of this package adds its `<style>` to the document root, which RTL's detached container lacks. " +
43
+ "Render without the `container` option, so the render is attached to the document, before reading text or markup."
44
+ };
45
+
46
+ /** Why the converter leaves every render of a source on Enzyme. */
47
+ export type FileGate = "react" | "rtl" | "rtlMissing" | "commonjs";
48
+
49
+ const FILES: Readonly<Record<FileGate, string>> = {
50
+ react: "Blocked for this file by its React: the recipe converts packages on React and React DOM 15.5 to 18, of the same major. " +
51
+ "On React 19, migrate the file by hand to RTL 16's `render`, `screen` and `fireEvent`, following the file's other rows.",
52
+ rtl: "Blocked for this file by its React Testing Library: the recipe converts with RTL 12 on React 15.5 to 17, or RTL 16 on React 18. " +
53
+ "Move `@testing-library/react` to that version, then run the recipe again.",
54
+ rtlMissing: "Blocked for this file: the run added no React Testing Library to its package, as the package manager declined the edit, " +
55
+ "or no package of the file declares Enzyme. Add `@testing-library/react` to the package that declares Enzyme, then run the recipe again.",
56
+ commonjs: "Blocked for this file by `require`: the recipe converts ES modules only. Load the file's modules with `import`, then run the recipe again."
57
+ };
58
+
59
+ export function blockedByFile(gate: FileGate): string {
60
+ return FILES[gate];
61
+ }
62
+
63
+ /** The suggested action for a render that the uses at `references` keep on Enzyme, naming the first of them. */
64
+ export async function blockedByUses(references: {cursor: Cursor, unmounted: boolean}[]): Promise<string> {
65
+ const [first] = references;
66
+ const {top, calls} = chainOf(first.cursor);
67
+ const action = first.unmounted ? UNMOUNTED : actionFor(top, calls, first.cursor);
68
+ const printed = (await TreePrinters.printer(JS.Kind.CompilationUnit).print(top)).trim().replace(/\s+/g, " ");
69
+ const snippet = printed.length > 80 ? `${printed.slice(0, 77)}...` : printed;
70
+ return `${action} ${references.length > 1 ? `First of ${references.length} uses that keep it on Enzyme` : "The use"}: \`${snippet}\``;
71
+ }
72
+
73
+ export function blockedByGate(gate: RenderGate): string {
74
+ return GATES[gate];
75
+ }
76
+
77
+ /** The calls and accesses on the wrapper at `reference`, outermost last. */
78
+ function chainOf(reference: Cursor): {top: J, calls: J.MethodInvocation[]} {
79
+ let top = reference.value as J;
80
+ const calls: J.MethodInvocation[] = [];
81
+ for (let c = reference.parentTree(); c; c = c.parentTree()) {
82
+ const node = c.value as J;
83
+ if (node.kind === J.Kind.MethodInvocation && (node as J.MethodInvocation).select?.element === top) calls.push(node as J.MethodInvocation);
84
+ else if (!(node.kind === J.Kind.FieldAccess && (node as J.FieldAccess).target === top) &&
85
+ !(node.kind === J.Kind.ArrayAccess && (node as J.ArrayAccess).indexed === top)) break;
86
+ top = node;
87
+ }
88
+ return {top, calls};
89
+ }
90
+
91
+ function actionFor(top: J, calls: J.MethodInvocation[], reference: Cursor): string {
92
+ if (calls.length === 0) return PASSED;
93
+ let parent = reference.parentTree();
94
+ while (parent && parent.value !== top) parent = parent.parentTree();
95
+ const holder = parent?.parentTree()?.value as J | undefined;
96
+ // A component selector has no DOM query, whatever reads its matches
97
+ const component = calls.find(call => call.name.simpleName === "find" && selectorKind("find", call.arguments.elements[0]?.element) === "component");
98
+ const enzymeCalls = calls.filter(call => ENZYME_WRAPPER_METHODS.has(call.name.simpleName));
99
+ const last = enzymeCalls[enzymeCalls.length - 1] ?? calls[calls.length - 1];
100
+ if (!component && WRAPPER_RESULTS.has(last.name.simpleName)) {
101
+ if (holder?.kind === J.Kind.NamedVariable || holder?.kind === J.Kind.Assignment) return STORED;
102
+ if (last.name.simpleName !== "find") return PASSED;
103
+ }
104
+ const blocking = component ?? last;
105
+ const api = blocking.name.simpleName;
106
+ const args = blocking.arguments.elements.map(argument => argument.element);
107
+ const selector = selectorKind(api, args[0]);
108
+ const event = eventKind(api, args);
109
+ // Read on its own, a DOM selector or a plain event converts, so here it is where it stands that keeps it
110
+ if (selector === "dom") return FIND_HERE;
111
+ if (event === "event") return SIMULATE_HERE;
112
+ return `Blocked by \`${api}\`: ${migrationReason(api, selector, event).suggestedAction}`;
113
+ }
@@ -10,7 +10,8 @@ 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} from "./enzyme-usage";
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";
14
15
  import {HostComponents, hostComponentExports, hostComponentsDeclared, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
15
16
  import {moduleFacts, Modules, rendersPortal, resolver} from "./enzyme-portals";
16
17
  import {evaluate, stringParts} from "./enzyme-constant-strings";
@@ -78,6 +79,9 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
78
79
  */
79
80
  readonly landed = new Set<string>();
80
81
 
82
+ /** The package roots whose edit `AddDependency` declined, such as for a lockfile it could not regenerate. Mutated in place too. */
83
+ readonly declined = new Set<string>();
84
+
81
85
  private readonly manifests: Json.Document[] = [];
82
86
 
83
87
  /** The manifests the step admits, which reach the Java recipe only in `generate`, once the forecast is known. */
@@ -89,6 +93,7 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
89
93
 
90
94
  override initialValue(): number {
91
95
  this.landed.clear();
96
+ this.declined.clear();
92
97
  this.manifests.length = 0;
93
98
  this.held.length = 0;
94
99
  return super.initialValue();
@@ -123,7 +128,7 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
123
128
  const scopes = lockfileScopes(this.held);
124
129
  const forwarded = new Set(this.held.filter(manifest => {
125
130
  const scope = scopes.get(manifest.sourcePath) ?? packageRoot(manifest.sourcePath);
126
- return !converting || [...converting].some(source => source.startsWith(scope));
131
+ return (!converting || [...converting].some(source => source.startsWith(scope))) && !this.withholds(scope);
127
132
  }));
128
133
  const scanner = await this.java.scanner(acc);
129
134
  for (const manifest of forwarded) await scanner.visit(manifest, ctx);
@@ -134,10 +139,33 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
134
139
  const editor = await this.java.editorWithData(acc);
135
140
  for (const manifest of this.manifests) {
136
141
  const edited = await editor.visit<Json.Document>(manifest, ctx);
137
- if (edited && edited !== manifest && declares(edited, this.addition.packageName)) this.landed.add(manifest.sourcePath.slice(0, -"package.json".length));
142
+ const root = manifest.sourcePath.slice(0, -"package.json".length);
143
+ 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);
138
145
  }
139
146
  return generated;
140
147
  }
148
+
149
+ /** Whether the package resolves what `onlyIfResolving` asks, as `AddDependency` checks before it edits. */
150
+ private resolvesGate(manifest: Json.Document): boolean {
151
+ const resolved = findNodeResolutionResult(manifest)?.resolvedDependencies ?? [];
152
+ return (this.addition.onlyIfResolving ?? []).every(gate => {
153
+ const at = gate.lastIndexOf("@");
154
+ const name = gate.slice(0, at);
155
+ return resolved.some(dep => dep.name === name && valid(dep.version) !== null && satisfies(dep.version, gate.slice(at + 1)));
156
+ });
157
+ }
158
+
159
+ /** Whether to keep the manifests of a lockfile scope, such as `packages/ui/` or the root's `""`, from the Java recipe. */
160
+ protected withholds(_scope: string): boolean {
161
+ return false;
162
+ }
163
+ }
164
+
165
+ function dependencySteps(forecast: ConversionForecast) {
166
+ const rtl = new AddTestingLibraryReact(forecast);
167
+ const dom18 = new AddTestingLibraryDom18(forecast);
168
+ return {rtl, dom18, rtl18: new AddTestingLibraryReact18(forecast, dom18)};
141
169
  }
142
170
 
143
171
  /** Adds {@link RTL_ADDITION}. */
@@ -157,9 +185,15 @@ export class AddTestingLibraryReact18 extends EnzymeTestDependency {
157
185
  readonly displayName = "Add `@testing-library/react` 16 where Enzyme tests on React 18 are migrated";
158
186
  readonly description = "Adds `@testing-library/react` 16 as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 18.";
159
187
 
160
- constructor(forecast: ConversionForecast = {}) {
188
+ constructor(forecast: ConversionForecast = {}, private readonly peer?: AddTestingLibraryDom18) {
161
189
  super(RTL_18_ADDITION, forecast);
162
190
  }
191
+
192
+ // NOTE: RTL 16 needs its peer `@testing-library/dom`, whose step runs first. Where that step's edit was declined,
193
+ // as when a registry timeout fails its lockfile, this step adds nothing in the same lockfile either.
194
+ protected override withholds(scope: string): boolean {
195
+ return !!this.peer && [...this.peer.declined].some(root => root.startsWith(scope));
196
+ }
163
197
  }
164
198
 
165
199
  /** Adds {@link DOM_18_ADDITION}, the peer of {@link RTL_18_ADDITION}. */
@@ -379,6 +413,11 @@ export function reactMajor(packages: Packages, sourcePath: string, landed: Reado
379
413
  return compatibility(packages, sourcePath, landed).react;
380
414
  }
381
415
 
416
+ /** Why {@link reactMajor} is 0 for a source file, as far as its package's declarations say. */
417
+ export function incompatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string> = new Set()): FileGate | undefined {
418
+ return compatibility(packages, sourcePath, landed).why;
419
+ }
420
+
382
421
  /** The events `simulate` can dispatch as `fireEvent` in a source file, and whether its render must be attached to the document for them. */
383
422
  export interface SimulatedEvents {
384
423
  events: ReadonlySet<string>;
@@ -404,7 +443,7 @@ export function simulatesEvents(packages: Packages, sourcePath: string, landed:
404
443
  }
405
444
 
406
445
  /** The React major as {@link reactMajor} reads it, and the major of the RTL the tests run with. */
407
- function compatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string>): {react: number, rtl: number} {
446
+ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string>): {react: number, rtl: number, why?: FileGate} {
408
447
  const roots = [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
409
448
  const declared = (name: "react" | "reactDom" | "rtl", from = roots) =>
410
449
  from.map(root => packages.get(root)![name]).find(version => version !== undefined);
@@ -425,7 +464,10 @@ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlyS
425
464
  const rtlMajor = added ? ((enzymeReact as DeclaredVersion).major >= 18 ? 16 : 12) : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 16 ? rtl.major : 0;
426
465
  const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major &&
427
466
  rtlMajor > 0 && rtlSupports(rtlMajor, react.major);
428
- return {react: compatible ? react.major : 0, rtl: rtlMajor};
467
+ if (compatible) return {react: react.major, rtl: rtlMajor};
468
+ const why: FileGate = !supportedReact(react) || !supportedReact(reactDom) || react.major !== reactDom.major ? "react" :
469
+ rtl === undefined && !added ? "rtlMissing" : "rtl";
470
+ return {react: 0, rtl: rtlMajor, why};
429
471
  }
430
472
 
431
473
  /**
@@ -546,8 +588,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
546
588
  // PERF: the sources that import Enzyme, kept from the scan to the forecast in `generate`, as the dependency steps keep
547
589
  // their manifests. Not in the accumulator, which the host keeps until the cycle ends; cleared once the forecast is made.
548
590
  private readonly tests: JS.CompilationUnit[] = [];
549
- private readonly dependencySteps = ADDS_RTL ? {rtl: new AddTestingLibraryReact(this.forecast), rtl18: new AddTestingLibraryReact18(this.forecast),
550
- dom18: new AddTestingLibraryDom18(this.forecast)} : undefined;
591
+ private readonly dependencySteps = ADDS_RTL ? dependencySteps(this.forecast) : undefined;
551
592
 
552
593
  constructor(options?: {untaggedSelectorPositions?: boolean}) {
553
594
  super(options);
@@ -726,6 +767,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
726
767
  private cu?: JS.CompilationUnit;
727
768
  private readonly portals = new Set<string>();
728
769
  private readonly rows: EnzymeUsageRow[] = [];
770
+ // What kept each mount analyzed in this source on Enzyme
771
+ private readonly blockers = new Map<string, string>();
729
772
  private prettier = false;
730
773
  private printWidth = 80;
731
774
 
@@ -735,6 +778,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
735
778
  this.hoists.clear();
736
779
  this.hoistedMounts.clear();
737
780
  this.rows.length = 0;
781
+ this.blockers.clear();
782
+ if (!dry) RENDER_BLOCKERS.delete(cu.sourcePath);
738
783
  this.names = namesUsedIn(cu);
739
784
  const prettierStyle = findMarker<PrettierStyle>(cu, StyleKind.PrettierStyle);
740
785
  this.prettier = prettierStyle !== undefined && !prettierStyle.ignored && await formattedBy(cu, prettierStyle);
@@ -747,7 +792,12 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
747
792
  this.typescript = isTypeScript(cu);
748
793
  this.optionalChaining = parsesOptionalChaining(scanned.packages, cu.sourcePath, this.typescript);
749
794
  this.enabled = this.reactMajor > 0 && moduleBindings(this).moduleSystem === "esm";
750
- if (!this.enabled) return cu;
795
+ if (!this.enabled) {
796
+ // Every render of the file stays on Enzyme for the same reason
797
+ 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)]]));
799
+ return cu;
800
+ }
751
801
  this.imports = relativeImports(cu, scanned.components);
752
802
  this.importedNames = importedNames(cu);
753
803
  this.declaredHost = hostComponentsDeclared(cu);
@@ -763,7 +813,10 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
763
813
  const visited = await super.visitJsCompilationUnit(visiting, ctx);
764
814
  if (dry) {
765
815
  if (this.rows.some(row => row.status === "CONVERTED")) dry.converted.add(cu.sourcePath);
766
- } else this.rows.forEach(row => usages.insertRow(ctx, row));
816
+ } else {
817
+ this.rows.forEach(row => usages.insertRow(ctx, row));
818
+ if (this.blockers.size > 0) RENDER_BLOCKERS.set(cu.sourcePath, new Map(this.blockers));
819
+ }
767
820
  if (!foreign || !visited) return visited;
768
821
  return visited === visiting ? cu : create(visited as JS.CompilationUnit, draft => {
769
822
  draft.markers.markers.push(prettierStyle as any);
@@ -984,7 +1037,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
984
1037
  return {mounts: new Map(this.mounts), uses: new Map(this.uses), removedStatements: new Set(this.removedStatements),
985
1038
  unmounts: new Set(this.unmounts), declarations: new Set(this.declarations), pending: new Set(this.pending),
986
1039
  reformat: new Set(this.reformat), hoists: new Map(this.hoists), hoistedMounts: new Map(this.hoistedMounts),
987
- portals: new Set(this.portals), rows: this.rows.length, afterVisit: this.afterVisit.length};
1040
+ portals: new Set(this.portals), rows: this.rows.length, afterVisit: this.afterVisit.length, blockers: new Map(this.blockers)};
988
1041
  }
989
1042
 
990
1043
  private restoreState(saved: ReturnType<typeof this.saveState>): void {
@@ -1000,6 +1053,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
1000
1053
  remap(this.uses, saved.uses);
1001
1054
  remap(this.hoists, saved.hoists);
1002
1055
  remap(this.hoistedMounts, saved.hoistedMounts);
1056
+ remap(this.blockers, saved.blockers);
1003
1057
  [[this.removedStatements, saved.removedStatements], [this.unmounts, saved.unmounts], [this.declarations, saved.declarations],
1004
1058
  [this.pending, saved.pending], [this.reformat, saved.reformat], [this.portals, saved.portals]]
1005
1059
  .forEach(([target, from]) => refill(target, from));
@@ -1017,15 +1071,25 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
1017
1071
  const reads = READS[api];
1018
1072
  // React 15 marks its markup with `data-reactroot` and empty renders with comments, which Enzyme's html() leaves out
1019
1073
  const markup = this.reactMajor >= 16;
1074
+ let blocking: Parameters<typeof blockedByUses>[0] | undefined;
1020
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,
1021
- constant: node => this.constantString(node)});
1022
- if (!scope) continue;
1023
- if ([...scope.uses.values()].some(use => use.use === "setProps" && !reads.props(use.props!, this.importedNames))) continue;
1076
+ constant: node => this.constantString(node), blocked: references => blocking = references});
1077
+ if (!scope) {
1078
+ if (blocking) this.blockers.set(candidate.mount.id, await blockedByUses(blocking));
1079
+ continue;
1080
+ }
1081
+ if ([...scope.uses.values()].some(use => use.use === "setProps" && !reads.props(use.props!, this.importedNames))) {
1082
+ this.blockers.set(candidate.mount.id, blockedByGate("setProps"));
1083
+ continue;
1084
+ }
1024
1085
  const mount = new Cursor(candidate.mount, variableCursor(this.cursor, candidate.declaration));
1025
1086
  const document = documentAt(mount);
1026
1087
  if (!document || !await renderPatterns[api].render.match(candidate.mount, mount)) continue;
1027
1088
  const attached = this.events.attached && [...scope.uses.values()].some(use => use.use === "simulate");
1028
- if (!attached && this.rootStyles && [...scope.uses.values()].some(use => CONTAINER_READS.has(use.use))) continue;
1089
+ if (!attached && this.rootStyles && [...scope.uses.values()].some(use => CONTAINER_READS.has(use.use))) {
1090
+ this.blockers.set(candidate.mount.id, blockedByGate("rootStyles"));
1091
+ continue;
1092
+ }
1029
1093
  this.mounts.set(candidate.mount.id, {document, api, attached});
1030
1094
  apis.push(api);
1031
1095
  this.declarations.add(candidate.declaration.id);
@@ -1273,9 +1337,16 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
1273
1337
  if (node?.kind !== J.Kind.MethodInvocation) return undefined;
1274
1338
  const call = node as J.MethodInvocation;
1275
1339
  const api = enzymeMethod(call);
1276
- if (api === "mount") return read && this.rendersPortal(call) ? undefined : api;
1340
+ if (api === "mount") {
1341
+ if (!read || !this.rendersPortal(call)) return api;
1342
+ this.blockers.set(call.id, blockedByGate("portal"));
1343
+ return undefined;
1344
+ }
1345
+ if (api !== "shallow" || call.arguments.elements.length !== 1) return undefined;
1277
1346
  const element = call.arguments.elements[0]?.element;
1278
- return api === "shallow" && call.arguments.elements.length === 1 && rendersHostElements(element, this.imports, scanned.components, this.importedNames, this.declaredHost) ? api : undefined;
1347
+ if (rendersHostElements(element, this.imports, scanned.components, this.importedNames, this.declaredHost)) return api;
1348
+ this.blockers.set(call.id, blockedByGate("shallow"));
1349
+ return undefined;
1279
1350
  }
1280
1351
 
1281
1352
  /**
@@ -1330,7 +1401,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
1330
1401
 
1331
1402
  async recipeList() {
1332
1403
  const steps = this.dependencySteps;
1333
- return [...steps ? [steps.rtl, steps.rtl18, steps.dom18] : [], new FindEnzymeUsage()];
1404
+ // The peer `@testing-library/dom` goes first, so RTL 16 lands only where it did
1405
+ return [...steps ? [steps.rtl, steps.dom18, steps.rtl18] : [], new FindEnzymeUsage()];
1334
1406
  }
1335
1407
  }
1336
1408
 
@@ -26,6 +26,15 @@ export class EnzymeUsageRow {
26
26
  suggestedAction!: string;
27
27
  }
28
28
 
29
+ /**
30
+ * What kept each render the converter analyzed on Enzyme, by source and then mount, for the review row of the mount that
31
+ * `FindEnzymeUsage` writes after it. Both run in the same RPC worker, which edits a source with each recipe in turn.
32
+ */
33
+ export const RENDER_BLOCKERS = new Map<string, ReadonlyMap<string, string>>();
34
+
35
+ /** The key of {@link RENDER_BLOCKERS} for what keeps every render of a source on Enzyme. */
36
+ export const FILE_BLOCKER = "*";
37
+
29
38
  export function enzymeModule(value: unknown): value is string {
30
39
  return typeof value === "string" && (value === ENZYME || value.startsWith("enzyme/") ||
31
40
  (value === "enzyme-to-json" || value.startsWith("enzyme-to-json/")) || /^(?:@[^/]+\/)?enzyme-adapter-/.test(value));
@@ -50,7 +59,11 @@ export type SelectorKind = "component" | "dom" | "enzyme" | "props" | "predicate
50
59
  export type EventKind = "event" | "hover" | "change" | "mock" | "other";
51
60
 
52
61
  export function migrationReason(api: string, selector?: SelectorKind, event?: EventKind): {reason: string, suggestedAction: string} {
53
- if (api === "shallow" || api === "dive") {
62
+ if (api === "dive") {
63
+ return {reason: "SHALLOW_RENDERING", suggestedAction: "Remove the `dive()`: RTL's `render` renders every level, so query what the child component renders directly. " +
64
+ "Where the test relied on the levels below not rendering, `jest.mock` those components' modules with stubs."};
65
+ }
66
+ if (api === "shallow") {
54
67
  return {reason: "SHALLOW_RENDERING", suggestedAction: "Review child rendering and effects before replacing shallow rendering with RTL render."};
55
68
  }
56
69
  const internal = INTERNAL_STATE_ACTIONS[api];
@@ -114,7 +127,27 @@ const WRAPPER_API_ACTIONS: Readonly<Record<string, string>> = {
114
127
  hasClass: "Use `element.classList.contains`, or `toHaveClass` from `@testing-library/jest-dom`.",
115
128
  getDOMNode: "Query the element directly with `screen.getBy*` or `container.querySelector`; RTL already returns DOM nodes.",
116
129
  update: "Remove it: RTL renders the latest state on every query. Await `findBy*` or `waitFor` where the change is asynchronous.",
117
- unmount: "Call the `unmount` that RTL's `render` returns, or rely on RTL's automatic cleanup after each test."
130
+ unmount: "Call the `unmount` that RTL's `render` returns, or rely on RTL's automatic cleanup after each test.",
131
+ hostNodes: "Remove it: `querySelectorAll` and the `getBy*` queries return DOM elements only, which is what `hostNodes()` keeps.",
132
+ childAt: "Read the queried element's `children[index]`, or query the child with `within(element)`.",
133
+ get: "Index the `querySelectorAll` or `getAllBy*` result; it already holds DOM elements, which `get` returns a React element in place of.",
134
+ forEach: "Loop over `Array.from(container.querySelectorAll(selector))` or the `getAllBy*` result, reading each element's DOM properties.",
135
+ map: "Map over `Array.from(container.querySelectorAll(selector))` or the `getAllBy*` result, reading each element's DOM properties.",
136
+ reduce: "Reduce over `Array.from(container.querySelectorAll(selector))` or the `getAllBy*` result, reading each element's DOM properties.",
137
+ filter: "Filter `Array.from(container.querySelectorAll(selector))` by a DOM property, or narrow the selector so the query returns only those elements.",
138
+ contains: "Assert the element is in the DOM: `screen.getByText` or `getByRole` for what the React element renders, or `toContainElement` from `@testing-library/jest-dom`.",
139
+ containsMatchingElement: "Assert what the element renders is in the DOM, with `screen.getByText` or `getByRole`; RTL doesn't compare React elements.",
140
+ is: "Use `element.matches(selector)` on the queried element.",
141
+ type: "Read the element's `tagName` for a DOM element. A component's type has no DOM equivalent: assert on what it renders.",
142
+ name: "Read the element's `tagName` for a DOM element. A component's name has no DOM equivalent: assert on what it renders.",
143
+ parent: "Read the queried element's `parentElement`.",
144
+ closest: "Use `element.closest(selector)` on the queried element.",
145
+ isEmptyRender: "Assert `container` is empty, with `expect(container).toBeEmptyDOMElement()` from `@testing-library/jest-dom` or `container.innerHTML === ''`.",
146
+ debug: "Use `screen.debug()` or `prettyDOM(element)`, or remove it once the test passes.",
147
+ getElement: "Assert on what the element renders in the DOM; RTL has no React element tree to compare.",
148
+ renderProp: "Render what the render prop returns by rendering the component with that prop, and query the result in the DOM.",
149
+ detach: "Remove it: RTL unmounts and removes each render's container after each test.",
150
+ key: "A React key has no DOM equivalent: assert on the order or content of the rendered elements instead."
118
151
  };
119
152
 
120
153
  export function enclosingScope(start: Cursor): string {
@@ -402,7 +402,9 @@ export function wrapperDeclaration<R>(statement: J | undefined, classify: (rende
402
402
  * snapshot RTL records as the DOM rather than Enzyme's tree. `hostNames` decides the selectors {@link selectorLiteral} accepts.
403
403
  */
404
404
  export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperDeclaration,
405
- {events, html, untaggedPositions, hostNames, snapshots = false, optionalChaining = true, constant = () => undefined}: {events: ReadonlySet<string>, html: boolean, untaggedPositions: boolean, hostNames: HostNames, snapshots?: boolean, optionalChaining?: boolean, constant?: (node: J) => string | undefined}): WrapperScope | undefined {
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 {
406
408
  let serializers: ReadonlySet<string> | undefined;
407
409
  const uses = new Map<string, WrapperRead>();
408
410
  const removedStatements = new Set<string>();
@@ -543,9 +545,18 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
543
545
  const declared = new Cursor(variable.name, variableCursor(block, declaration));
544
546
  const references = referencesOf(declared, name, "value");
545
547
  if (!references.some(reference => reference.identifier === variable.name)) return undefined;
548
+ const rejected: {cursor: Cursor, unmounted: boolean}[] = [];
546
549
  for (const reference of references) {
547
550
  if (reference.identifier === variable.name) continue;
548
- if (reference.declares || unmounted || !use(reference.identifier, reference.cursor)) return undefined;
551
+ const after = unmounted;
552
+ if (reference.declares || after || !use(reference.identifier, reference.cursor)) {
553
+ if (!blocked) return undefined;
554
+ rejected.push({cursor: reference.cursor, unmounted: after});
555
+ }
556
+ }
557
+ if (rejected.length > 0) {
558
+ blocked!(rejected);
559
+ return undefined;
549
560
  }
550
561
  return {declaration, name, uses, removedStatements, unmounts};
551
562
  }
@@ -0,0 +1,26 @@
1
+ import {check, Cursor, ExecutionContext, or, SourceFile, Tree, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {JS} from "@openrewrite/rewrite/javascript";
3
+ import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
4
+ import {treesOfType} from "./java-recipe-proxy";
5
+
6
+ /**
7
+ * One visitor of JSON documents and JavaScript sources, such as `package.json` files and the code they
8
+ * describe. With `discard`, the JavaScript visitor only gathers: the sources stay as they were.
9
+ */
10
+ export function jsonAndJavaScript(json: JsonVisitor<ExecutionContext>, javascript: TreeVisitor<any, ExecutionContext>, discard = false): Promise<TreeVisitor<any, ExecutionContext>> {
11
+ const visitor = new class extends TreeVisitor<any, ExecutionContext> {
12
+ override async isAcceptable(sourceFile: SourceFile, ctx: ExecutionContext): Promise<boolean> {
13
+ return await json.isAcceptable(sourceFile) || await javascript.isAcceptable(sourceFile, ctx);
14
+ }
15
+
16
+ override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
17
+ if (tree.kind === Json.Kind.Document) return await json.visit(tree, ctx, parent) as R | undefined;
18
+ if (tree.kind !== JS.Kind.CompilationUnit) return tree as R;
19
+ const visited = await javascript.visit(tree, ctx, parent) as R | undefined;
20
+ return discard ? tree as R : visited;
21
+ }
22
+ }();
23
+ // The host infers which trees to send only from a JsonVisitor or JavaScriptVisitor, and sends a plain
24
+ // TreeVisitor every tree, including ones the TypeScript side has no codec for
25
+ return check(or(treesOfType("org.openrewrite.json.tree.Json"), treesOfType("org.openrewrite.javascript.tree.JS")), visitor);
26
+ }