@openrewrite/recipes-react 0.14.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +12 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +70 -17
- package/dist/index.js.map +1 -1
- package/dist/migration/cra-to-vite/add-vite-config.d.ts +9 -0
- package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/add-vite-config.js +49 -0
- package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-blockers-table.d.ts +10 -0
- package/dist/migration/cra-to-vite/cra-blockers-table.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-blockers-table.js +31 -0
- package/dist/migration/cra-to-vite/cra-blockers-table.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-to-vite.d.ts +14 -0
- package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-to-vite.js +73 -0
- package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts +14 -0
- package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js +177 -0
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-env-file-blockers.d.ts +10 -0
- package/dist/migration/cra-to-vite/find-cra-env-file-blockers.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-env-file-blockers.js +67 -0
- package/dist/migration/cra-to-vite/find-cra-env-file-blockers.js.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-source-blockers.d.ts +10 -0
- package/dist/migration/cra-to-vite/find-cra-source-blockers.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-source-blockers.js +168 -0
- package/dist/migration/cra-to-vite/find-cra-source-blockers.js.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.d.ts +8 -0
- package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.js +31 -0
- package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.js.map +1 -0
- package/dist/migration/cra-to-vite/index.d.ts +16 -0
- package/dist/migration/cra-to-vite/index.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/index.js +35 -0
- package/dist/migration/cra-to-vite/index.js.map +1 -0
- package/dist/migration/cra-to-vite/move-public-index-html.d.ts +11 -0
- package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/move-public-index-html.js +124 -0
- package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -0
- package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts +9 -0
- package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/rename-process-env-react-app.js +92 -0
- package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -0
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.d.ts +9 -0
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +65 -0
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -0
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +14 -0
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +78 -0
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +21 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.js +87 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -0
- package/dist/migration/cra-to-vite/shared.d.ts +24 -0
- package/dist/migration/cra-to-vite/shared.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/shared.js +105 -0
- package/dist/migration/cra-to-vite/shared.js.map +1 -0
- package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts +9 -0
- package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/update-react-app-env-types.js +47 -0
- package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -0
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +9 -0
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +62 -0
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -0
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts +10 -0
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js +44 -0
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js.map +1 -0
- package/dist/react17/migrate-deprecated-lifecycles.d.ts +8 -0
- package/dist/react17/migrate-deprecated-lifecycles.d.ts.map +1 -0
- package/dist/react17/migrate-deprecated-lifecycles.js +258 -0
- package/dist/react17/migrate-deprecated-lifecycles.js.map +1 -0
- package/dist/react17/use-new-jsx-transform.d.ts +8 -0
- package/dist/react17/use-new-jsx-transform.d.ts.map +1 -0
- package/dist/react17/use-new-jsx-transform.js +121 -0
- package/dist/react17/use-new-jsx-transform.js.map +1 -0
- package/dist/react18/add-children-to-props.d.ts +8 -0
- package/dist/react18/add-children-to-props.d.ts.map +1 -0
- package/dist/react18/add-children-to-props.js +277 -0
- package/dist/react18/add-children-to-props.js.map +1 -0
- package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
- package/dist/react18/replace-reactdom-render.js +109 -12
- package/dist/react18/replace-reactdom-render.js.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.js +62 -20
- package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
- package/dist/react19/replace-default-props.d.ts.map +1 -1
- package/dist/react19/replace-default-props.js +10 -13
- package/dist/react19/replace-default-props.js.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.js +1 -6
- package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
- package/dist/refactoring/class-to-functional.d.ts.map +1 -1
- package/dist/refactoring/class-to-functional.js +81 -7
- package/dist/refactoring/class-to-functional.js.map +1 -1
- package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
- package/dist/refactoring/create-class-to-es6.js +4 -7
- package/dist/refactoring/create-class-to-es6.js.map +1 -1
- package/dist/refactoring/create-element-to-jsx.d.ts.map +1 -1
- package/dist/refactoring/create-element-to-jsx.js +3 -4
- package/dist/refactoring/create-element-to-jsx.js.map +1 -1
- package/dist/refactoring/fix-async-effect.d.ts +8 -0
- package/dist/refactoring/fix-async-effect.d.ts.map +1 -0
- package/dist/refactoring/fix-async-effect.js +71 -0
- package/dist/refactoring/fix-async-effect.js.map +1 -0
- package/dist/refactoring/prop-types-to-typescript.d.ts +8 -0
- package/dist/refactoring/prop-types-to-typescript.d.ts.map +1 -0
- package/dist/refactoring/prop-types-to-typescript.js +341 -0
- package/dist/refactoring/prop-types-to-typescript.js.map +1 -0
- package/dist/refactoring/pure-render-mixin.d.ts.map +1 -1
- package/dist/refactoring/pure-render-mixin.js +3 -6
- package/dist/refactoring/pure-render-mixin.js.map +1 -1
- package/dist/search/find-deprecated-lifecycles.d.ts +12 -0
- package/dist/search/find-deprecated-lifecycles.d.ts.map +1 -0
- package/dist/search/find-deprecated-lifecycles.js +86 -0
- package/dist/search/find-deprecated-lifecycles.js.map +1 -0
- package/dist/search/find-effects-without-cleanup.d.ts +9 -0
- package/dist/search/find-effects-without-cleanup.d.ts.map +1 -0
- package/dist/search/find-effects-without-cleanup.js +133 -0
- package/dist/search/find-effects-without-cleanup.js.map +1 -0
- package/dist/search/find-enzyme-usage.d.ts +9 -0
- package/dist/search/find-enzyme-usage.d.ts.map +1 -0
- package/dist/search/find-enzyme-usage.js +155 -0
- package/dist/search/find-enzyme-usage.js.map +1 -0
- package/dist/search/find-function-component-default-props.d.ts +11 -0
- package/dist/search/find-function-component-default-props.d.ts.map +1 -0
- package/dist/search/find-function-component-default-props.js +96 -0
- package/dist/search/find-function-component-default-props.js.map +1 -0
- package/dist/search/find-legacy-react-apis.d.ts +8 -0
- package/dist/search/find-legacy-react-apis.d.ts.map +1 -0
- package/dist/search/find-legacy-react-apis.js +41 -0
- package/dist/search/find-legacy-react-apis.js.map +1 -0
- package/dist/search/find-missing-use-client-directive.d.ts +9 -0
- package/dist/search/find-missing-use-client-directive.d.ts.map +1 -0
- package/dist/search/find-missing-use-client-directive.js +127 -0
- package/dist/search/find-missing-use-client-directive.js.map +1 -0
- package/dist/search/find-reactdom-root-apis.d.ts +14 -0
- package/dist/search/find-reactdom-root-apis.d.ts.map +1 -0
- package/dist/search/find-reactdom-root-apis.js +122 -0
- package/dist/search/find-reactdom-root-apis.js.map +1 -0
- package/dist/testing/enzyme-host-components.d.ts +14 -0
- package/dist/testing/enzyme-host-components.d.ts.map +1 -0
- package/dist/testing/enzyme-host-components.js +245 -0
- package/dist/testing/enzyme-host-components.js.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts +41 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.js +572 -0
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -0
- package/dist/testing/enzyme-usage.d.ts +22 -0
- package/dist/testing/enzyme-usage.d.ts.map +1 -0
- package/dist/testing/enzyme-usage.js +107 -0
- package/dist/testing/enzyme-usage.js.map +1 -0
- package/dist/testing/enzyme-wrapper-scope.d.ts +51 -0
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -0
- package/dist/testing/enzyme-wrapper-scope.js +420 -0
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -0
- package/dist/util/module-imports.d.ts +12 -0
- package/dist/util/module-imports.d.ts.map +1 -0
- package/dist/util/module-imports.js +56 -0
- package/dist/util/module-imports.js.map +1 -0
- package/dist/util/react-class.d.ts +7 -0
- package/dist/util/react-class.d.ts.map +1 -0
- package/dist/util/react-class.js +42 -0
- package/dist/util/react-class.js.map +1 -0
- package/dist/util/tree-search.d.ts +6 -0
- package/dist/util/tree-search.d.ts.map +1 -0
- package/dist/util/tree-search.js +51 -0
- package/dist/util/tree-search.js.map +1 -0
- package/package.json +7 -4
- package/src/index.ts +53 -12
- package/src/migration/cra-to-vite/add-vite-config.ts +47 -0
- package/src/migration/cra-to-vite/cra-blockers-table.ts +27 -0
- package/src/migration/cra-to-vite/cra-to-vite.ts +76 -0
- package/src/migration/cra-to-vite/find-cra-config-blockers.ts +173 -0
- package/src/migration/cra-to-vite/find-cra-env-file-blockers.ts +60 -0
- package/src/migration/cra-to-vite/find-cra-source-blockers.ts +138 -0
- package/src/migration/cra-to-vite/find-cra-to-vite-blockers.ts +21 -0
- package/src/migration/cra-to-vite/index.ts +26 -0
- package/src/migration/cra-to-vite/move-public-index-html.ts +132 -0
- package/src/migration/cra-to-vite/rename-process-env-react-app.ts +93 -0
- package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +61 -0
- package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +71 -0
- package/src/migration/cra-to-vite/scan-cra-projects.ts +86 -0
- package/src/migration/cra-to-vite/shared.ts +123 -0
- package/src/migration/cra-to-vite/update-react-app-env-types.ts +40 -0
- package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +64 -0
- package/src/migration/cra-to-vite/update-tsconfig-for-vite.ts +40 -0
- package/src/react17/migrate-deprecated-lifecycles.ts +265 -0
- package/src/react17/use-new-jsx-transform.ts +108 -0
- package/src/react18/add-children-to-props.ts +235 -0
- package/src/react18/replace-reactdom-render.ts +109 -20
- package/src/react18/replace-unmount-component-at-node.ts +78 -32
- package/src/react19/replace-default-props.ts +11 -15
- package/src/react19/replace-react-shallow-renderer.ts +2 -7
- package/src/refactoring/class-to-functional.ts +101 -13
- package/src/refactoring/create-class-to-es6.ts +6 -9
- package/src/refactoring/create-element-to-jsx.ts +4 -6
- package/src/refactoring/fix-async-effect.ts +88 -0
- package/src/refactoring/prop-types-to-typescript.ts +341 -0
- package/src/refactoring/pure-render-mixin.ts +4 -7
- package/src/search/find-deprecated-lifecycles.ts +64 -0
- package/src/search/find-effects-without-cleanup.ts +109 -0
- package/src/search/find-enzyme-usage.ts +117 -0
- package/src/search/find-function-component-default-props.ts +68 -0
- package/src/search/find-legacy-react-apis.ts +41 -0
- package/src/search/find-missing-use-client-directive.ts +99 -0
- package/src/search/find-reactdom-root-apis.ts +99 -0
- package/src/testing/enzyme-host-components.ts +283 -0
- package/src/testing/enzyme-to-react-testing-library.ts +622 -0
- package/src/testing/enzyme-usage.ts +94 -0
- package/src/testing/enzyme-wrapper-scope.ts +456 -0
- package/src/util/module-imports.ts +55 -0
- package/src/util/react-class.ts +35 -0
- package/src/util/tree-search.ts +32 -0
- package/dist/react16/upgrade-to-react-16.d.ts +0 -12
- package/dist/react16/upgrade-to-react-16.d.ts.map +0 -1
- package/dist/react16/upgrade-to-react-16.js +0 -66
- package/dist/react16/upgrade-to-react-16.js.map +0 -1
- package/dist/react17/upgrade-to-react-17.d.ts +0 -12
- package/dist/react17/upgrade-to-react-17.d.ts.map +0 -1
- package/dist/react17/upgrade-to-react-17.js +0 -62
- package/dist/react17/upgrade-to-react-17.js.map +0 -1
- package/dist/react18/upgrade-to-react-18.d.ts +0 -12
- package/dist/react18/upgrade-to-react-18.d.ts.map +0 -1
- package/dist/react18/upgrade-to-react-18.js +0 -64
- package/dist/react18/upgrade-to-react-18.js.map +0 -1
- package/dist/react19/upgrade-to-react-19.d.ts +0 -8
- package/dist/react19/upgrade-to-react-19.d.ts.map +0 -1
- package/dist/react19/upgrade-to-react-19.js +0 -68
- package/dist/react19/upgrade-to-react-19.js.map +0 -1
- package/src/react16/upgrade-to-react-16.ts +0 -59
- package/src/react17/upgrade-to-react-17.ts +0 -52
- package/src/react18/upgrade-to-react-18.ts +0 -55
- package/src/react19/upgrade-to-react-19.ts +0 -75
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, ScanningRecipe, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {addDependency, AddDependencyOptions, autoFormat, capture, PrettierStyle, deconflict, findNodeResolutionResult, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, raw, rewrite, scopeOf, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {Expression, J} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {create} from "mutative";
|
|
5
|
+
import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
|
|
6
|
+
import {readFileSync} from "fs";
|
|
7
|
+
import {dirname, join} from "path";
|
|
8
|
+
import {satisfies, validRange} from "semver";
|
|
9
|
+
import {FindEnzymeUsage} from "../search/find-enzyme-usage";
|
|
10
|
+
import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, enzymeMethod, EnzymeUsageRow} from "./enzyme-usage";
|
|
11
|
+
import {HostComponents, hostComponentExports, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
|
|
12
|
+
import {analyzeWrapperScope, idsWithin, innermostCall, mountedElement, selectorLiteral, simpleChain, statementPosition, variableCursor, withoutEnzymeTypes, withRenderOptionsOnElementLine, wrapperDeclaration, WrapperRead} from "./enzyme-wrapper-scope";
|
|
13
|
+
|
|
14
|
+
const RTL = "@testing-library/react";
|
|
15
|
+
|
|
16
|
+
const REACT_RANGE = ">=16.9.0 <18";
|
|
17
|
+
|
|
18
|
+
/** RTL 12 supports React 16.9 to 17, so it goes where Enzyme is used with those. */
|
|
19
|
+
const RTL_ADDITION: AddDependencyOptions = {
|
|
20
|
+
packageName: RTL, version: "^12.1.5", scope: "devDependencies",
|
|
21
|
+
onlyIfDeclaring: ["enzyme"], onlyIfResolving: [`react@${REACT_RANGE}`, `react-dom@${REACT_RANGE}`]
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Older hosts drop the `onlyIfResolving` option they do not know, which would add RTL to every
|
|
26
|
+
* package declaring Enzyme, so RTL is only added where the host has it.
|
|
27
|
+
*/
|
|
28
|
+
const ADDS_RTL = (() => {
|
|
29
|
+
try {
|
|
30
|
+
return supportsResolvingGate(rewriteVersion(require.resolve("@openrewrite/rewrite"), require.cache));
|
|
31
|
+
} catch {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
})();
|
|
35
|
+
|
|
36
|
+
export function supportsResolvingGate(version: string | undefined): boolean {
|
|
37
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(-)?/.exec(version ?? "");
|
|
38
|
+
if (!match) return false;
|
|
39
|
+
const [major, minor, patch] = match.slice(1, 4).map(Number);
|
|
40
|
+
const order = major - 8 || minor - 97 || patch - 2;
|
|
41
|
+
return order > 0 || order === 0 && !match[4];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The version of the `@openrewrite/rewrite` package that `resolved` runs as. A host sharing its own
|
|
46
|
+
* copy with a recipe package maps the package's module paths to the host's modules in the require
|
|
47
|
+
* cache, so the module's own file name says which copy that is.
|
|
48
|
+
*/
|
|
49
|
+
export function rewriteVersion(resolved: string, cache: Record<string, {filename: string} | undefined>): string | undefined {
|
|
50
|
+
for (let dir = dirname(cache[resolved]?.filename ?? resolved); dirname(dir) !== dir; dir = dirname(dir)) {
|
|
51
|
+
try {
|
|
52
|
+
const manifest = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
|
|
53
|
+
if (manifest.name === "@openrewrite/rewrite") return manifest.version;
|
|
54
|
+
} catch {
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
type DocumentReference = "document" | "globalThis.document";
|
|
62
|
+
|
|
63
|
+
/** How a render at `cursor` reaches the global `document` without a local binding capturing it. */
|
|
64
|
+
function documentAt(cursor: Cursor): DocumentReference | undefined {
|
|
65
|
+
const scope = scopeOf(cursor);
|
|
66
|
+
if (!scope.declares("document", "value")) return "document";
|
|
67
|
+
return scope.declares("globalThis", "value") ? undefined : "globalThis.document";
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function renderOptions(document: DocumentReference): string {
|
|
71
|
+
return `{container: ${document}.createElement('div')}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A wrapper's rendered element, declared ahead of the wrapper for `setProps` to clone. */
|
|
75
|
+
interface HoistedElement {
|
|
76
|
+
name: string;
|
|
77
|
+
element: J;
|
|
78
|
+
reassigned: boolean;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A declared version within one major, with its minor version where the declaration fixes one. */
|
|
82
|
+
interface DeclaredVersion {
|
|
83
|
+
major: number;
|
|
84
|
+
minor?: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A package's declaration of each dependency the migration needs: absent, unsupported, or within a major. */
|
|
88
|
+
type Declaration = DeclaredVersion | "unsupported" | undefined;
|
|
89
|
+
|
|
90
|
+
interface PackageDeclarations {
|
|
91
|
+
react: Declaration;
|
|
92
|
+
reactDom: Declaration;
|
|
93
|
+
rtl: Declaration;
|
|
94
|
+
enzyme: boolean;
|
|
95
|
+
/**
|
|
96
|
+
* `addDependency` leaves a package unchanged when it cannot regenerate its lockfile, as for pnpm
|
|
97
|
+
* versions it does not reproduce, so only npm and Yarn packages are counted on to receive RTL.
|
|
98
|
+
*/
|
|
99
|
+
lockfileRegenerated: boolean;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Package roots, such as `packages/ui/`, mapped to their declarations. */
|
|
103
|
+
type Packages = Map<string, PackageDeclarations>;
|
|
104
|
+
|
|
105
|
+
interface Scanned {
|
|
106
|
+
packages: Packages;
|
|
107
|
+
components: HostComponents;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The Enzyme render a converted wrapper comes from. */
|
|
111
|
+
type Render = "mount" | "shallow";
|
|
112
|
+
|
|
113
|
+
/** A render that a converted wrapper is created by, and how its container reaches `document`. */
|
|
114
|
+
interface ConvertedRender {
|
|
115
|
+
document: DocumentReference;
|
|
116
|
+
api: Render;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* What a converted wrapper of each Enzyme render may do. A shallow render calls a handler without
|
|
121
|
+
* bubbling or a DOM event, prints a found node as static markup, and shows a component element that
|
|
122
|
+
* `setProps` passes as a placeholder, where a full render shows its DOM.
|
|
123
|
+
*/
|
|
124
|
+
const READS: Record<Render, {simulate: boolean, html: boolean, props: (props: Expression, testImports: ReadonlySet<string>) => boolean}> = {
|
|
125
|
+
mount: {simulate: true, html: true, props: () => true},
|
|
126
|
+
shallow: {simulate: false, html: false, props: propsRenderHostElements}
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The React major version the tests of a source file run with, or 0 where they cannot migrate. A
|
|
131
|
+
* dependency the owning package does not declare comes from the nearest enclosing package that
|
|
132
|
+
* does, where Node resolves it from. Where the run adds RTL, as {@link RTL_ADDITION} does, it is
|
|
133
|
+
* there for every package within the nearest package declaring Enzyme.
|
|
134
|
+
*/
|
|
135
|
+
export function reactMajor(packages: Packages, sourcePath: string, addsRtl = false): number {
|
|
136
|
+
return compatibility(packages, sourcePath, addsRtl).react;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Whether `simulate` can become `fireEvent` for a source file: on React 17, with an RTL whose
|
|
141
|
+
* `fireEvent.focus`, `blur`, `mouseEnter`, and `mouseLeave` also dispatch the events React 17
|
|
142
|
+
* listens to, which RTL 10 does only from 10.4.9.
|
|
143
|
+
*/
|
|
144
|
+
export function simulatesEvents(packages: Packages, sourcePath: string, addsRtl = false): boolean {
|
|
145
|
+
const {react, rtl} = compatibility(packages, sourcePath, addsRtl);
|
|
146
|
+
return react === 17 && rtl >= 11;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The React major as {@link reactMajor} reads it, and the major of the RTL the tests run with. */
|
|
150
|
+
function compatibility(packages: Packages, sourcePath: string, addsRtl: boolean): {react: number, rtl: number} {
|
|
151
|
+
const roots = [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
|
|
152
|
+
const declared = (name: "react" | "reactDom" | "rtl", from = roots) =>
|
|
153
|
+
from.map(root => packages.get(root)![name]).find(version => version !== undefined);
|
|
154
|
+
const supportedReact = (version: Declaration): version is DeclaredVersion => typeof version === "object" &&
|
|
155
|
+
(version.major === 17 || (version.major === 16 && version.minor !== undefined && version.minor >= 9));
|
|
156
|
+
const react = declared("react");
|
|
157
|
+
const rtl = declared("rtl");
|
|
158
|
+
const enzyme = roots.findIndex(root => packages.get(root)!.enzyme);
|
|
159
|
+
const added = addsRtl && rtl === undefined && enzyme >= 0 && packages.get(roots[enzyme])!.lockfileRegenerated &&
|
|
160
|
+
supportedReact(declared("react", roots.slice(enzyme))) && supportedReact(declared("reactDom", roots.slice(enzyme)));
|
|
161
|
+
// RTL renders with the React DOM it resolves from its own package
|
|
162
|
+
const rtlRoot = added ? enzyme : roots.findIndex(root => packages.get(root)!.rtl !== undefined);
|
|
163
|
+
const reactDom = declared("reactDom", roots.slice(Math.max(rtlRoot, 0))) ?? declared("reactDom");
|
|
164
|
+
// `render` with a container, `rerender`, `unmount`, and `fireEvent` are all there since RTL 10
|
|
165
|
+
const rtlMajor = added ? 12 : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 12 ? rtl.major : 0;
|
|
166
|
+
const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major && rtlMajor > 0;
|
|
167
|
+
return {react: compatible ? react.major : 0, rtl: rtlMajor};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* A version or a range within a single major: `16.14.0`, `^16.14`, `~16.9.0`, `16.9.x`, or `^17`,
|
|
172
|
+
* whose minor version is known only where it is a lower bound.
|
|
173
|
+
*/
|
|
174
|
+
function declaredVersion(version: string | undefined): Declaration {
|
|
175
|
+
if (version === undefined) return undefined;
|
|
176
|
+
const match = /^([\^~]?)(\d+)(?:\.(\d+|x|\*)(?:\.(\d+|x|\*))?)?$/.exec(version.trim());
|
|
177
|
+
if (!match) return "unsupported";
|
|
178
|
+
return {major: Number(match[2]), minor: /^\d+$/.test(match[3] ?? "") ? Number(match[3]) : undefined};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Converts an Enzyme `mount` wrapper only when all of its uses can be converted together, so no
|
|
183
|
+
* partially migrated wrapper can escape. Inline expressions such as
|
|
184
|
+
* `mount(<Button />).find('button').length` and `const wrapper = mount(<Button />)` declarations
|
|
185
|
+
* whose every reference is a supported DOM read become RTL renders into a detached container.
|
|
186
|
+
*
|
|
187
|
+
* A `shallow` wrapper converts the same way where the full render cannot differ from the shallow
|
|
188
|
+
* one: its component, scanned from the source it is imported from, creates host elements only and
|
|
189
|
+
* runs no effects, and receives no component element from the test. `simulate` and `html()` stay
|
|
190
|
+
* excluded there, since a shallow render calls a handler without bubbling and prints static markup.
|
|
191
|
+
*
|
|
192
|
+
* ```tsx
|
|
193
|
+
* // before, where `Label` renders `<ul><li>{text}</li></ul>`
|
|
194
|
+
* const wrapper = shallow(<Label text="a" />);
|
|
195
|
+
* expect(wrapper.find('li').length).toBe(1);
|
|
196
|
+
* // after
|
|
197
|
+
* const wrapper = render(<Label text="a" />, {container: document.createElement('div')});
|
|
198
|
+
* expect(wrapper.container.querySelectorAll('li').length).toBe(1);
|
|
199
|
+
* ```
|
|
200
|
+
*
|
|
201
|
+
* Existing compatible RTL installation and DOM test setup are prerequisites. More complex
|
|
202
|
+
* wrapper flows remain in the inventory rather than being guessed at.
|
|
203
|
+
*
|
|
204
|
+
* @see https://testing-library.com/docs/react-testing-library/migrate-from-enzyme/#how-to-migrate-from-enzyme-to-react-testing-library
|
|
205
|
+
*/
|
|
206
|
+
|
|
207
|
+
export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
208
|
+
readonly name = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
|
|
209
|
+
readonly displayName = "Migrate Enzyme to React Testing Library";
|
|
210
|
+
readonly description = "Migrates Enzyme `mount` wrappers whose every use is a supported DOM read or event (`find(selector).length`, `.exists()`, `.text()`, `.html()`, `.hasClass()`, positions through `.at(n)`, `.first()`, `.last()`, the wrapper's `text()` and `exists(selector)`, found nodes as a `toHaveLength` subject, `setProps` as a rerender of the cloned element, and on React 17 `simulate` with common mouse, keyboard, focus, form, and touch events, including `nativeEvent` mocks) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16.9+/17 with RTL 10 to 12, adding RTL 12 where it is missing. 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.";
|
|
211
|
+
|
|
212
|
+
@Option({
|
|
213
|
+
displayName: "Convert positions into untagged selector matches",
|
|
214
|
+
description: "Whether a position into the matches of a selector with a compound that names no tag, such as `find('.slice').at(1)`, is converted. Enzyme also matches a component that receives the class, ID, or attribute as a prop, which shifts the positions of the elements after it; converting assumes that no component in the rendered tree receives it. Defaults to `true`; set it to `false` to convert only positions into tag-qualified matches.",
|
|
215
|
+
required: false
|
|
216
|
+
})
|
|
217
|
+
untaggedSelectorPositions?: boolean;
|
|
218
|
+
|
|
219
|
+
constructor(options?: {untaggedSelectorPositions?: boolean}) {
|
|
220
|
+
super(options);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
private readonly usages = new DataTable<EnzymeUsageRow>(
|
|
224
|
+
ENZYME_USAGE_TABLE, "Enzyme migration inventory",
|
|
225
|
+
"Remaining Enzyme usages and migration actions. Module rows include references whose call types may be unavailable; they are not counts of test cases.",
|
|
226
|
+
EnzymeUsageRow
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
initialValue(): Scanned {
|
|
230
|
+
return {packages: new Map(), components: new Map()};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// The host may prepare the visitors before there is an accumulator, so it is read only while visiting
|
|
234
|
+
async scanner(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
235
|
+
const sources = new class extends JavaScriptVisitor<ExecutionContext> {
|
|
236
|
+
override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
|
|
237
|
+
scanned.components.set(cu.sourcePath, hostComponentExports(cu));
|
|
238
|
+
return cu;
|
|
239
|
+
}
|
|
240
|
+
}();
|
|
241
|
+
const manifests = new class extends JsonVisitor<ExecutionContext> {
|
|
242
|
+
override async visitDocument(doc: Json.Document, ctx: ExecutionContext): Promise<Json | undefined> {
|
|
243
|
+
if (!/(^|\/)package\.json$/.test(doc.sourcePath)) return doc;
|
|
244
|
+
const resolution = findNodeResolutionResult(doc);
|
|
245
|
+
// In the order the dependency gate of `addDependency` reads them
|
|
246
|
+
const dependencies = [...resolution?.dependencies ?? [], ...resolution?.devDependencies ?? [],
|
|
247
|
+
...resolution?.optionalDependencies ?? [], ...resolution?.peerDependencies ?? []];
|
|
248
|
+
// The lockfile's resolved version is what the tests run against, unless it is outside the
|
|
249
|
+
// declared semver range, as a hoisted Yarn workspace resolution can be. Without one, accept only
|
|
250
|
+
// ranges within a single major; catalogs, aliases, and cross-major ranges stay unsupported.
|
|
251
|
+
const version = (name: string) => {
|
|
252
|
+
const dependency = dependencies.find(dep => dep.name === name && dep.resolved);
|
|
253
|
+
const resolved = dependency?.resolved;
|
|
254
|
+
if (resolved?.name === name && /^\d+\.\d+\.\d+$/.test(resolved.version) &&
|
|
255
|
+
(!validRange(dependency!.versionConstraint) || satisfies(resolved.version, dependency!.versionConstraint))) return resolved.version;
|
|
256
|
+
return dependencies.find(dep => dep.name === name)?.versionConstraint;
|
|
257
|
+
};
|
|
258
|
+
scanned.packages.set(doc.sourcePath.slice(0, -"package.json".length), {
|
|
259
|
+
react: declaredVersion(version("react")),
|
|
260
|
+
reactDom: declaredVersion(version("react-dom")),
|
|
261
|
+
rtl: declaredVersion(version(RTL)),
|
|
262
|
+
enzyme: dependencies.some(dep => dep.name === "enzyme"),
|
|
263
|
+
lockfileRegenerated: resolution?.packageManager !== "Pnpm" && resolution?.packageManager !== "Bun"
|
|
264
|
+
});
|
|
265
|
+
return doc;
|
|
266
|
+
}
|
|
267
|
+
}();
|
|
268
|
+
return new class extends TreeVisitor<any, ExecutionContext> {
|
|
269
|
+
override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
|
|
270
|
+
if (tree.kind === Json.Kind.Document) return await manifests.visit(tree, ctx, parent) as R | undefined;
|
|
271
|
+
return tree.kind === JS.Kind.CompilationUnit ? await sources.visit(tree, ctx, parent) as R | undefined : tree as R;
|
|
272
|
+
}
|
|
273
|
+
}();
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async editorWithData(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
277
|
+
const jsx = capture<Expression>({name: "element", constraint: node => node.kind !== JS.Kind.Spread});
|
|
278
|
+
const selector = capture<J.Literal>({name: "selector", constraint: node => selectorLiteral(node)});
|
|
279
|
+
const after = {context: [`import {render} from "${RTL}";`], dependencies: {[RTL]: "12.1.5", "@types/react": "16.14.62"}};
|
|
280
|
+
const patterns = (api: Render) => {
|
|
281
|
+
const before = {lenientTypeMatching: false, context: [`import {${api}} from "enzyme";`], dependencies: {"@types/enzyme": "3.10.19", "@types/react": "16.14.62"}};
|
|
282
|
+
return {
|
|
283
|
+
render: pattern`${raw(api)}(${jsx})`.configure(before),
|
|
284
|
+
length: pattern`${raw(api)}(${jsx}).find(${selector}).length`.configure(before),
|
|
285
|
+
exists: pattern`${raw(api)}(${jsx}).find(${selector}).exists()`.configure(before)
|
|
286
|
+
};
|
|
287
|
+
};
|
|
288
|
+
const renderPatterns = {mount: patterns("mount"), shallow: patterns("shallow")};
|
|
289
|
+
const renderRules = (document: DocumentReference, api: Render) => {
|
|
290
|
+
const options = raw(renderOptions(document));
|
|
291
|
+
const from = renderPatterns[api];
|
|
292
|
+
return {
|
|
293
|
+
length: rewrite(() => ({
|
|
294
|
+
before: from.length,
|
|
295
|
+
after: template`render(${jsx}, ${options}).container.querySelectorAll(${selector}).length`.configure(after)
|
|
296
|
+
})),
|
|
297
|
+
exists: rewrite(() => ({
|
|
298
|
+
before: from.exists,
|
|
299
|
+
after: template`render(${jsx}, ${options}).container.querySelectorAll(${selector}).length > 0`.configure(after)
|
|
300
|
+
})),
|
|
301
|
+
mount: rewrite(() => ({
|
|
302
|
+
before: from.render,
|
|
303
|
+
after: template`render(${jsx}, ${options})`.configure(after)
|
|
304
|
+
}))
|
|
305
|
+
};
|
|
306
|
+
};
|
|
307
|
+
const rules = {
|
|
308
|
+
"document": {mount: renderRules("document", "mount"), shallow: renderRules("document", "shallow")},
|
|
309
|
+
"globalThis.document": {mount: renderRules("globalThis.document", "mount"), shallow: renderRules("globalThis.document", "shallow")}
|
|
310
|
+
};
|
|
311
|
+
const usages = this.usages;
|
|
312
|
+
const untaggedPositions = this.untaggedSelectorPositions !== false;
|
|
313
|
+
return check(and(not(isVendoredOrBundled()), or(usesMethod("enzyme mount(..)"), usesMethod("enzyme shallow(..)"))), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
314
|
+
private enabled = false;
|
|
315
|
+
private reactMajor = 0;
|
|
316
|
+
private events = false;
|
|
317
|
+
private typescript = false;
|
|
318
|
+
private sourcePath = "";
|
|
319
|
+
private readonly mounts = new Map<string, ConvertedRender>();
|
|
320
|
+
private imports: ReadonlyMap<string, ImportedExport> = new Map();
|
|
321
|
+
private importedNames: ReadonlySet<string> = new Set();
|
|
322
|
+
private readonly uses = new Map<string, WrapperRead>();
|
|
323
|
+
private readonly removedStatements = new Set<string>();
|
|
324
|
+
private readonly unmounts = new Set<string>();
|
|
325
|
+
private readonly declarations = new Set<string>();
|
|
326
|
+
private readonly pending = new Set<string>();
|
|
327
|
+
private readonly reformat = new Set<string>();
|
|
328
|
+
private readonly hoists = new Map<string, HoistedElement>();
|
|
329
|
+
private readonly hoistedMounts = new Map<string, string>();
|
|
330
|
+
private names: ReadonlySet<string> = new Set();
|
|
331
|
+
private readonly rows: EnzymeUsageRow[] = [];
|
|
332
|
+
private prettier = false;
|
|
333
|
+
private printWidth = 80;
|
|
334
|
+
|
|
335
|
+
override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
336
|
+
this.sourcePath = cu.sourcePath;
|
|
337
|
+
[this.mounts, this.uses, this.removedStatements, this.unmounts, this.declarations, this.pending, this.reformat].forEach(ids => ids.clear());
|
|
338
|
+
this.hoists.clear();
|
|
339
|
+
this.hoistedMounts.clear();
|
|
340
|
+
this.rows.length = 0;
|
|
341
|
+
this.names = namesUsedIn(cu);
|
|
342
|
+
const prettierStyle = findMarker<PrettierStyle>(cu, StyleKind.PrettierStyle);
|
|
343
|
+
this.prettier = prettierStyle !== undefined;
|
|
344
|
+
this.printWidth = typeof prettierStyle?.config.printWidth === "number" ? prettierStyle.config.printWidth : 80;
|
|
345
|
+
this.reactMajor = reactMajor(scanned.packages, cu.sourcePath, ADDS_RTL);
|
|
346
|
+
this.events = simulatesEvents(scanned.packages, cu.sourcePath, ADDS_RTL);
|
|
347
|
+
this.typescript = isTypeScript(cu);
|
|
348
|
+
this.enabled = this.reactMajor > 0 && moduleBindings(this).moduleSystem === "esm";
|
|
349
|
+
if (!this.enabled) return cu;
|
|
350
|
+
this.imports = relativeImports(cu, scanned.components);
|
|
351
|
+
this.importedNames = importedNames(cu);
|
|
352
|
+
const visited = await super.visitJsCompilationUnit(cu, ctx);
|
|
353
|
+
this.rows.forEach(row => usages.insertRow(ctx, row));
|
|
354
|
+
return visited;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
override async visitBlock(block: J.Block, ctx: ExecutionContext): Promise<J | undefined> {
|
|
358
|
+
const planned: string[] = [];
|
|
359
|
+
const apis: Render[] = [];
|
|
360
|
+
for (const statement of block.statements) {
|
|
361
|
+
const candidate = wrapperDeclaration(statement.element, render => this.renderOf(render));
|
|
362
|
+
if (!candidate) continue;
|
|
363
|
+
const api = candidate.render;
|
|
364
|
+
const reads = READS[api];
|
|
365
|
+
const scope = analyzeWrapperScope(this.cursor, candidate, {events: this.events && reads.simulate, html: reads.html, untaggedPositions});
|
|
366
|
+
if (!scope) continue;
|
|
367
|
+
if ([...scope.uses.values()].some(use => use.use === "setProps" && !reads.props(use.props!, this.importedNames))) continue;
|
|
368
|
+
const mount = new Cursor(candidate.mount, variableCursor(this.cursor, candidate.declaration));
|
|
369
|
+
const document = documentAt(mount);
|
|
370
|
+
if (!document || !await renderPatterns[api].render.match(candidate.mount, mount)) continue;
|
|
371
|
+
this.mounts.set(candidate.mount.id, {document, api});
|
|
372
|
+
apis.push(api);
|
|
373
|
+
this.declarations.add(candidate.declaration.id);
|
|
374
|
+
scope.uses.forEach((use, id) => this.uses.set(id, use));
|
|
375
|
+
scope.removedStatements.forEach(id => this.removedStatements.add(id));
|
|
376
|
+
scope.unmounts.forEach(id => this.unmounts.add(id));
|
|
377
|
+
const setProps = [...scope.uses.values()].filter(read => read.use === "setProps");
|
|
378
|
+
if (setProps.length > 0) {
|
|
379
|
+
const name = deconflict(`${candidate.name}Element`, name => this.names.has(name));
|
|
380
|
+
const reassigned = setProps.length > 1;
|
|
381
|
+
setProps.forEach(read => Object.assign(read, {element: name, reassigned}));
|
|
382
|
+
this.hoists.set(candidate.declaration.id, {name, element: candidate.mount.arguments.elements[0].element, reassigned});
|
|
383
|
+
this.hoistedMounts.set(candidate.mount.id, name);
|
|
384
|
+
}
|
|
385
|
+
planned.push(candidate.mount.id, ...scope.uses.keys());
|
|
386
|
+
}
|
|
387
|
+
planned.forEach(id => this.pending.add(id));
|
|
388
|
+
const queued = this.afterVisit.length;
|
|
389
|
+
const rows = this.rows.length;
|
|
390
|
+
const visited = await super.visitBlock(block, ctx) as J.Block;
|
|
391
|
+
// Every use was matched before planning, so this only guards against a template
|
|
392
|
+
// failing to apply: never leave a wrapper half converted.
|
|
393
|
+
if (planned.some(id => this.pending.has(id))) {
|
|
394
|
+
this.afterVisit.length = queued;
|
|
395
|
+
this.rows.length = rows;
|
|
396
|
+
idsWithin(block, this.reformat).forEach(id => this.reformat.delete(id));
|
|
397
|
+
// Uses of a wrapper declared further out are rolled back too, which its block has to see
|
|
398
|
+
idsWithin(block, new Set([...this.mounts.keys(), ...this.uses.keys()])).forEach(id => this.pending.add(id));
|
|
399
|
+
return block;
|
|
400
|
+
}
|
|
401
|
+
apis.forEach(api => this.converted(api, enclosingScope(this.cursor), "WRAPPER_SCOPE"));
|
|
402
|
+
// Prettier lays out statements by their position in the block as it was parsed, before any is added or removed
|
|
403
|
+
const laidOut = await this.withPrettierLayout(visited, ctx);
|
|
404
|
+
const statements: J.Block["statements"][number][] = [];
|
|
405
|
+
for (const statement of laidOut.statements) {
|
|
406
|
+
const element = statement.element as J;
|
|
407
|
+
const expression = element.kind === JS.Kind.ExpressionStatement ? (element as JS.ExpressionStatement).expression : element;
|
|
408
|
+
if (this.removedStatements.has(expression.id)) continue;
|
|
409
|
+
const hoist = this.hoists.get(element.id);
|
|
410
|
+
if (hoist) statements.push(...await this.withHoistedElement(hoist, statement, laidOut));
|
|
411
|
+
else statements.push(statement);
|
|
412
|
+
}
|
|
413
|
+
if (statements.length === laidOut.statements.length && statements.every((statement, i) => statement === laidOut.statements[i])) return laidOut;
|
|
414
|
+
return create(laidOut, draft => {
|
|
415
|
+
draft.statements = statements as any;
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Declares the element ahead of the wrapper, which keeps any comments only on the first. */
|
|
420
|
+
private async withHoistedElement(hoist: HoistedElement, statement: J.Block["statements"][number],
|
|
421
|
+
block: J.Block): Promise<J.Block["statements"][number][]> {
|
|
422
|
+
const declaration = statement.element;
|
|
423
|
+
const prefix = declaration.prefix;
|
|
424
|
+
const indent = prefix.comments.length > 0 ? prefix.comments[prefix.comments.length - 1].suffix : prefix.whitespace;
|
|
425
|
+
const declarator = `${hoist.reassigned ? "let" : "const"} ${hoist.name} = `;
|
|
426
|
+
// Multi-line JSX is parenthesized, as Prettier does, which breaks JSX that does not fit on its line
|
|
427
|
+
const element = (await TreePrinters.printer(JS.Kind.CompilationUnit).print(hoist.element)).trim();
|
|
428
|
+
const parenthesized = hoist.element.kind === JS.Kind.JsxTag && (element.includes("\n") ||
|
|
429
|
+
this.prettier && indent.length - indent.lastIndexOf("\n") - 1 + declarator.length + element.length + 1 > this.printWidth);
|
|
430
|
+
const elementDeclaration = Template.builder().code(declarator + (parenthesized ? "(" : "")).param(hoist.element)
|
|
431
|
+
.code((parenthesized ? ")" : "") + ";").build();
|
|
432
|
+
const hoisted = await elementDeclaration.apply(declaration, new Cursor(declaration, new Cursor(statement, new Cursor(block, this.cursor.parent))));
|
|
433
|
+
if (!hoisted) throw new Error(`Cannot declare ${hoist.name}`);
|
|
434
|
+
return [
|
|
435
|
+
{...statement, element: {...hoisted, prefix} as typeof declaration},
|
|
436
|
+
{...statement, element: {...declaration, prefix: {...prefix, whitespace: indent, comments: []}}}
|
|
437
|
+
];
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// Prettier lays out only the replaced expression, while its line breaks often belong to the
|
|
441
|
+
// enclosing call, as in `expect(\n converted\n).toBe(0)`; lay out the whole statement instead.
|
|
442
|
+
private async withPrettierLayout(block: J.Block, ctx: ExecutionContext): Promise<J.Block> {
|
|
443
|
+
if (this.reformat.size === 0) return block;
|
|
444
|
+
const parent = new Cursor(block, this.cursor.parent);
|
|
445
|
+
const statements: J.Block["statements"][number][] = [];
|
|
446
|
+
let formatted = false;
|
|
447
|
+
for (const statement of block.statements) {
|
|
448
|
+
const ids = idsWithin(statement.element, this.reformat);
|
|
449
|
+
if (ids.length === 0) {
|
|
450
|
+
statements.push(statement);
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
ids.forEach(id => this.reformat.delete(id));
|
|
454
|
+
statements.push({...statement, element: await autoFormat(statement.element, ctx, undefined, new Cursor(statement, parent))});
|
|
455
|
+
formatted = true;
|
|
456
|
+
}
|
|
457
|
+
return formatted ? create(block, draft => {
|
|
458
|
+
draft.statements = statements as any;
|
|
459
|
+
}) : block;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
override async visitVariableDeclarations(declarations: J.VariableDeclarations, ctx: ExecutionContext): Promise<J | undefined> {
|
|
463
|
+
const visited = await super.visitVariableDeclarations(declarations, ctx) as J.VariableDeclarations;
|
|
464
|
+
return this.declarations.has(declarations.id) ? withoutEnzymeTypes(visited, ctx) : visited;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
override async visitFieldAccess(field: J.FieldAccess, ctx: ExecutionContext): Promise<J | undefined> {
|
|
468
|
+
const use = this.uses.get(field.id);
|
|
469
|
+
if (use) return await this.apply(use, field, ctx) ?? field;
|
|
470
|
+
const visited = await super.visitFieldAccess(field, ctx) as J.FieldAccess;
|
|
471
|
+
const lengthOf = visited.name.element.simpleName === "length" && simpleChain(visited) ? this.renderOf(innermostCall(visited)) : undefined;
|
|
472
|
+
return lengthOf && await this.tryInline(lengthOf, "length", visited, `${lengthOf}.find.length`, "<inline expression>", "INLINE_DOM_QUERY", ctx) || visited;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
|
|
476
|
+
const use = this.uses.get(method.id);
|
|
477
|
+
if (use) return await this.apply(use, method, ctx) ?? method;
|
|
478
|
+
if (this.unmounts.has(method.id)) return withoutEnzymeTypes(method, ctx);
|
|
479
|
+
const visited = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
|
|
480
|
+
const mounted = this.mounts.get(method.id);
|
|
481
|
+
if (mounted) {
|
|
482
|
+
const hoisted = this.hoistedMounts.get(method.id);
|
|
483
|
+
const result = hoisted ?
|
|
484
|
+
await this.applyTemplate(Template.builder().code(`render(${hoisted}, ${renderOptions(mounted.document)})`).build().configure(after), visited) :
|
|
485
|
+
await rules[mounted.document][mounted.api].mount.tryOn(this.cursor, visited, {visitor: this});
|
|
486
|
+
if (!result) return visited;
|
|
487
|
+
this.pending.delete(method.id);
|
|
488
|
+
return withRenderOptionsOnElementLine(result, ctx);
|
|
489
|
+
}
|
|
490
|
+
const statementOf = mountedElement(visited) && statementPosition(this.cursor) ? this.renderOf(visited) : undefined;
|
|
491
|
+
const statement = statementOf && await this.tryInline(statementOf, "mount", visited, statementOf, enclosingScope(this.cursor), "MOUNT_STATEMENT", ctx);
|
|
492
|
+
if (statement) return statement;
|
|
493
|
+
const existsOf = visited.name.simpleName === "exists" && simpleChain(visited) ? this.renderOf(innermostCall(visited)) : undefined;
|
|
494
|
+
return existsOf && await this.tryInline(existsOf, "exists", visited, `${existsOf}.find.exists`, "<inline expression>", "INLINE_DOM_QUERY", ctx) || visited;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** Converts an inline render, read, or bare render statement with one of the rules, recording it as `api` in `scope`. */
|
|
498
|
+
private async tryInline(render: Render, rule: "length" | "exists" | "mount", node: J, api: string, scope: string, reason: string,
|
|
499
|
+
ctx: ExecutionContext): Promise<J | undefined> {
|
|
500
|
+
const document = documentAt(this.cursor);
|
|
501
|
+
const result = document && await rules[document][render][rule].tryOn(this.cursor, node, {visitor: this});
|
|
502
|
+
if (!result) return undefined;
|
|
503
|
+
this.converted(api, scope, reason);
|
|
504
|
+
this.laidOutByPrettier(result);
|
|
505
|
+
return withRenderOptionsOnElementLine(result, ctx);
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
private async apply(read: WrapperRead, node: J, ctx: ExecutionContext): Promise<J | undefined> {
|
|
509
|
+
const result = await this.applyTemplate(this.readTemplate(read), node);
|
|
510
|
+
if (!result) return undefined;
|
|
511
|
+
this.pending.delete(node.id);
|
|
512
|
+
this.laidOutByPrettier(result);
|
|
513
|
+
if (read.vacuous) {
|
|
514
|
+
this.rows.push({sourcePath: this.sourcePath, scope: enclosingScope(this.cursor), api: "find", status: "REVIEW", reason: "VACUOUS_ASSERTION",
|
|
515
|
+
suggestedAction: "The assertion holds for any Enzyme wrapper and any node list; assert the expected number of elements instead."});
|
|
516
|
+
}
|
|
517
|
+
return withoutEnzymeTypes(result, ctx);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
private async applyTemplate(replacement: Template, node: J): Promise<J | undefined> {
|
|
521
|
+
return replacement.apply(node, this.cursor, {bindings: await replacement.resolveBindings(this)});
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
private readTemplate(read: WrapperRead): Template {
|
|
525
|
+
const code = Template.builder();
|
|
526
|
+
const nodes = () => code.param(read.wrapper).code(".container.querySelectorAll(").param(read.selector!).code(")");
|
|
527
|
+
// Enzyme throws where a single-node method finds no node; so does a non-null element here
|
|
528
|
+
const element = (nonNull: boolean) => {
|
|
529
|
+
const assertion = nonNull && this.typescript ? "!" : "";
|
|
530
|
+
if (read.index === "last") {
|
|
531
|
+
code.code("Array.from(");
|
|
532
|
+
return nodes().code(").pop()" + assertion);
|
|
533
|
+
}
|
|
534
|
+
if (read.index !== undefined && read.index !== "first") return nodes().code("[").param(read.index).code("]");
|
|
535
|
+
return code.param(read.wrapper).code(".container.querySelector(").param(read.selector!).code(")" + assertion);
|
|
536
|
+
};
|
|
537
|
+
// Enzyme finds nothing within a position it has no element at
|
|
538
|
+
const within = () => element(false).code("?.querySelectorAll(").param(read.within!).code(").length ?? 0");
|
|
539
|
+
switch (read.use) {
|
|
540
|
+
case "length":
|
|
541
|
+
if (read.within) return within().build();
|
|
542
|
+
return nodes().code(".length").build();
|
|
543
|
+
case "exists":
|
|
544
|
+
if (read.within) {
|
|
545
|
+
code.code("(");
|
|
546
|
+
return within().code(") > 0").build();
|
|
547
|
+
}
|
|
548
|
+
return nodes().code(".length > 0").build();
|
|
549
|
+
case "positionExists":
|
|
550
|
+
if (read.index === "first") return code.param(read.wrapper).code(".container.querySelector(").param(read.selector!).code(") !== null").build();
|
|
551
|
+
if (read.index === "last") return nodes().code(".length > 0").build();
|
|
552
|
+
return nodes().code("[").param(read.index!).code("] !== undefined").build();
|
|
553
|
+
case "nodes":
|
|
554
|
+
return nodes().build();
|
|
555
|
+
// An element's text content is never null, though its type allows it
|
|
556
|
+
case "text":
|
|
557
|
+
return code.param(read.wrapper).code(".container.textContent" + (read.unasserted && this.typescript ? "!" : "")).build();
|
|
558
|
+
case "selectorText":
|
|
559
|
+
if (read.unasserted) return element(true).code(".textContent" + (this.typescript ? "!" : "")).build();
|
|
560
|
+
return element(false).code("?.textContent").build();
|
|
561
|
+
case "html":
|
|
562
|
+
return element(!!read.unasserted).code(read.unasserted ? ".outerHTML" : "?.outerHTML").build();
|
|
563
|
+
case "hasClass":
|
|
564
|
+
return element(true).code(".classList.contains(").param(read.className!).code(")").build();
|
|
565
|
+
case "setProps":
|
|
566
|
+
code.param(read.wrapper).code(`.rerender(${read.reassigned ? `(${read.element} = ` : ""}cloneElement(${read.element}, `);
|
|
567
|
+
return code.param(read.props!).code(read.reassigned ? ")))" : "))").build().configure({
|
|
568
|
+
context: ['import {cloneElement} from "react";'],
|
|
569
|
+
dependencies: {"@types/react": "16.14.62"}
|
|
570
|
+
});
|
|
571
|
+
case "simulate":
|
|
572
|
+
if (read.nativeEvent) {
|
|
573
|
+
code.code("fireEvent(");
|
|
574
|
+
element(true);
|
|
575
|
+
code.code(`, Object.defineProperties(createEvent.${read.event}(`);
|
|
576
|
+
element(true);
|
|
577
|
+
code.code("), {");
|
|
578
|
+
read.nativeEvent.forEach(([name, value], i) => code.code(`${i ? ", " : ""}${name}: {value: `).param(value).code("}"));
|
|
579
|
+
return code.code("}))").build().configure({
|
|
580
|
+
context: [`import {createEvent, fireEvent} from "${RTL}";`],
|
|
581
|
+
dependencies: {[RTL]: "12.1.5", "@types/react": "16.14.62"}
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
code.code(`fireEvent.${read.event}(`);
|
|
585
|
+
element(true);
|
|
586
|
+
if (read.eventInit) code.code(", ").param(read.eventInit);
|
|
587
|
+
return code.code(")").build().configure({
|
|
588
|
+
context: [`import {fireEvent} from "${RTL}";`],
|
|
589
|
+
dependencies: {[RTL]: "12.1.5", "@types/react": "16.14.62"}
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* The Enzyme render a call is, where RTL's `render` renders the same DOM: any `mount`, and a
|
|
596
|
+
* `shallow` of a component that renders host elements only, as {@link rendersHostElements} decides.
|
|
597
|
+
*/
|
|
598
|
+
private renderOf(node: J | undefined): Render | undefined {
|
|
599
|
+
if (node?.kind !== J.Kind.MethodInvocation) return undefined;
|
|
600
|
+
const call = node as J.MethodInvocation;
|
|
601
|
+
const api = enzymeMethod(call);
|
|
602
|
+
if (api === "mount") return api;
|
|
603
|
+
const element = call.arguments.elements[0]?.element;
|
|
604
|
+
return api === "shallow" && call.arguments.elements.length === 1 && rendersHostElements(element, this.imports, scanned.components, this.importedNames) ? api : undefined;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
private laidOutByPrettier(node: J): void {
|
|
608
|
+
if (this.prettier) this.reformat.add(node.id);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
private converted(api: string, scope: string, reason: string): void {
|
|
612
|
+
maybeRemoveImport(this, ENZYME);
|
|
613
|
+
this.rows.push({sourcePath: this.sourcePath, scope, api, status: "CONVERTED", reason,
|
|
614
|
+
suggestedAction: "Run the migrated test and review whether an accessible RTL query would better express its intent."});
|
|
615
|
+
}
|
|
616
|
+
}());
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
async recipeList() {
|
|
620
|
+
return [...ADDS_RTL ? [await addDependency(RTL_ADDITION)] : [], new FindEnzymeUsage()];
|
|
621
|
+
}
|
|
622
|
+
}
|