@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,94 @@
|
|
|
1
|
+
import {Column, Cursor} from "@openrewrite/rewrite";
|
|
2
|
+
import {JS} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {isIdentifier, J, Type} from "@openrewrite/rewrite/java";
|
|
4
|
+
|
|
5
|
+
export const ENZYME = "enzyme";
|
|
6
|
+
export const ENZYME_GUIDE = "https://testing-library.com/docs/react-testing-library/migrate-from-enzyme/";
|
|
7
|
+
export const ENZYME_USAGE_TABLE = "org.openrewrite.react.table.EnzymeUsages";
|
|
8
|
+
|
|
9
|
+
export class EnzymeUsageRow {
|
|
10
|
+
@Column({displayName: "Source path", description: "The file containing the Enzyme usage."})
|
|
11
|
+
sourcePath!: string;
|
|
12
|
+
|
|
13
|
+
@Column({displayName: "Scope", description: "The enclosing test or function, or <module> when no name is available."})
|
|
14
|
+
scope!: string;
|
|
15
|
+
|
|
16
|
+
@Column({displayName: "API", description: "The Enzyme API or module reference found."})
|
|
17
|
+
api!: string;
|
|
18
|
+
|
|
19
|
+
@Column({displayName: "Status", description: "REVIEW for remaining usage, or CONVERTED for a migrated expression."})
|
|
20
|
+
status!: string;
|
|
21
|
+
|
|
22
|
+
@Column({displayName: "Reason", description: "A stable reason code explaining the migration action or blocker."})
|
|
23
|
+
reason!: string;
|
|
24
|
+
|
|
25
|
+
@Column({displayName: "Suggested action", description: "The next step for migrating or reviewing this usage."})
|
|
26
|
+
suggestedAction!: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function enzymeModule(value: unknown): value is string {
|
|
30
|
+
return typeof value === "string" && (value === ENZYME || value.startsWith("enzyme/") ||
|
|
31
|
+
(value === "enzyme-to-json" || value.startsWith("enzyme-to-json/")) || /^(?:@[^/]+\/)?enzyme-adapter-/.test(value));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function enzymeMethod(method: J.MethodInvocation): string | undefined {
|
|
35
|
+
const type = method.methodType;
|
|
36
|
+
if (!type) return undefined;
|
|
37
|
+
const owner = Type.FullyQualified.getFullyQualifiedName(type.declaringType);
|
|
38
|
+
return owner === ENZYME || owner.startsWith(`${ENZYME}.`) ? type.name : undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function enzymeWrapper(type: Type | undefined): boolean {
|
|
42
|
+
return !!type && Type.isOfTypeWithName(type, true,
|
|
43
|
+
name => /^enzyme\.(?:ReactWrapper|ShallowWrapper|CommonWrapper)$/.test(name));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function migrationReason(api: string): {reason: string, suggestedAction: string} {
|
|
47
|
+
if (api === "shallow" || api === "dive") {
|
|
48
|
+
return {reason: "SHALLOW_RENDERING", suggestedAction: "Review child rendering and effects before replacing shallow rendering with RTL render."};
|
|
49
|
+
}
|
|
50
|
+
if (["state", "setState", "instance", "invoke"].includes(api)) {
|
|
51
|
+
return {reason: "INTERNAL_STATE", suggestedAction: "Replace implementation-detail access with user interactions and observable DOM assertions."};
|
|
52
|
+
}
|
|
53
|
+
if (api === "simulate") {
|
|
54
|
+
return {reason: "UNSUPPORTED_EVENT", suggestedAction: "Review event payloads and async control flow before selecting user-event or fireEvent."};
|
|
55
|
+
}
|
|
56
|
+
if (api === "find" || api === "findWhere" || api === "filterWhere") {
|
|
57
|
+
return {reason: "SELECTOR_REVIEW", suggestedAction: "Review selector scope, component versus DOM matching, and zero/one/multiple-match behavior."};
|
|
58
|
+
}
|
|
59
|
+
if (api === "mount") {
|
|
60
|
+
return {reason: "RENDER_REVIEW", suggestedAction: "Review every use of the wrapper and its shared setup before replacing mount with RTL render."};
|
|
61
|
+
}
|
|
62
|
+
if (api === "render") {
|
|
63
|
+
return {reason: "STATIC_RENDERING", suggestedAction: "Review static HTML and Cheerio assertions before migrating to RTL DOM rendering."};
|
|
64
|
+
}
|
|
65
|
+
if (api === "configure") {
|
|
66
|
+
return {reason: "ENZYME_SETUP", suggestedAction: "Keep Enzyme setup until no tests or helpers in the owning package need it."};
|
|
67
|
+
}
|
|
68
|
+
return {reason: "WRAPPER_API", suggestedAction: "Review this Enzyme wrapper API for an equivalent RTL interaction or DOM assertion."};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function enclosingScope(start: Cursor): string {
|
|
72
|
+
for (let cursor = start.parent; cursor; cursor = cursor.parent) {
|
|
73
|
+
const node = cursor.value as J;
|
|
74
|
+
if (node?.kind === J.Kind.MethodInvocation) {
|
|
75
|
+
const call = node as J.MethodInvocation;
|
|
76
|
+
const receiver = call.select?.element;
|
|
77
|
+
if (["it", "test", "describe"].includes(call.name.simpleName) ||
|
|
78
|
+
(["only", "skip"].includes(call.name.simpleName) && receiver && isIdentifier(receiver) &&
|
|
79
|
+
["it", "test", "describe"].includes(receiver.simpleName))) {
|
|
80
|
+
const first = call.arguments.elements[0]?.element;
|
|
81
|
+
if (first?.kind === J.Kind.Literal && typeof (first as J.Literal).value === "string") {
|
|
82
|
+
return String((first as J.Literal).value);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (node?.kind === J.Kind.NamedVariable) {
|
|
87
|
+
const variable = node as J.VariableDeclarations.NamedVariable;
|
|
88
|
+
if ((variable.initializer?.element.kind === JS.Kind.ArrowFunction || variable.initializer?.element.kind === J.Kind.Lambda) &&
|
|
89
|
+
isIdentifier(variable.name)) return variable.name.simpleName;
|
|
90
|
+
}
|
|
91
|
+
if (node?.kind === J.Kind.MethodDeclaration) return (node as J.MethodDeclaration).name.simpleName;
|
|
92
|
+
}
|
|
93
|
+
return "<module>";
|
|
94
|
+
}
|
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
import {Cursor, ExecutionContext} from "@openrewrite/rewrite";
|
|
2
|
+
import {isObjectLiteral, JavaScriptVisitor, JS, referencesOf, walk} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {emptySpace, Expression, isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {create} from "mutative";
|
|
5
|
+
import {enzymeMethod, enzymeWrapper} from "./enzyme-usage";
|
|
6
|
+
|
|
7
|
+
const HTML_TAGS = new Set(["a", "abbr", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo",
|
|
8
|
+
"blockquote", "body", "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "data",
|
|
9
|
+
"datalist", "dd", "del", "details", "dfn", "dialog", "div", "dl", "dt", "em", "embed", "fieldset",
|
|
10
|
+
"figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "i",
|
|
11
|
+
"iframe", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "menu", "meter",
|
|
12
|
+
"nav", "noscript", "object", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q",
|
|
13
|
+
"rp", "rt", "ruby", "s", "samp", "section", "select", "slot", "small", "source", "span", "strong", "sub",
|
|
14
|
+
"summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr",
|
|
15
|
+
"track", "u", "ul", "var", "video", "wbr"]);
|
|
16
|
+
const SVG_TAGS = new Set(["circle", "clipPath", "defs", "desc", "ellipse", "foreignObject", "g", "image", "line",
|
|
17
|
+
"linearGradient", "marker", "mask", "path", "pattern", "polygon", "polyline", "radialGradient", "rect", "stop",
|
|
18
|
+
"svg", "symbol", "text", "textPath", "tspan", "use"]);
|
|
19
|
+
|
|
20
|
+
// React writes these props through as identically named string attributes. Props such as
|
|
21
|
+
// `htmlFor`, `className`, `value`, or `checked` differ from their DOM attributes and stay excluded.
|
|
22
|
+
const ATTRIBUTE = String.raw`(?:data-[a-z0-9]+(?:-[a-z0-9]+)*|aria-[a-z]+|id|name|type|role|href|title|alt|placeholder)`;
|
|
23
|
+
const SIMPLE = String.raw`(?:\.-?[_a-zA-Z][\w-]*|#-?[_a-zA-Z][\w-]*|\[${ATTRIBUTE}(?:="[^"\\]*"|='[^'\\]*')?\])`;
|
|
24
|
+
const COMPOUND = new RegExp(String.raw`([a-z][a-zA-Z0-9]*)?(?:${SIMPLE})*`, "y");
|
|
25
|
+
const ATTRIBUTE_VALUE = /="([^"\\]*)"\]|='([^'\\]*)'\]/g;
|
|
26
|
+
|
|
27
|
+
/** The tag of each compound in a selector of compounds separated by single spaces, or undefined if it is not one. */
|
|
28
|
+
function compoundTags(value: string): (string | undefined)[] | undefined {
|
|
29
|
+
const tags: (string | undefined)[] = [];
|
|
30
|
+
for (let i = 0; ;) {
|
|
31
|
+
COMPOUND.lastIndex = i;
|
|
32
|
+
const match = COMPOUND.exec(value);
|
|
33
|
+
if (!match || match[0] === "") return undefined;
|
|
34
|
+
tags.push(match[1]);
|
|
35
|
+
i += match[0].length;
|
|
36
|
+
if (i === value.length) return tags;
|
|
37
|
+
if (value[i++] !== " ") return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Accepts a selector whose Enzyme and DOM meanings agree for host elements: a compound of an HTML
|
|
43
|
+
* or SVG tag, classes, IDs, and quoted pass-through attributes, or several such compounds combined as
|
|
44
|
+
* descendants. Enzyme compares an attribute value strictly against the
|
|
45
|
+
* prop, while the DOM sees it stringified, so values that a number or boolean prop renders to are
|
|
46
|
+
* excluded. Enzyme additionally matches composite elements whose props satisfy a class, ID, or
|
|
47
|
+
* attribute compound, so it finds every element the DOM finds and possibly more: counts can only
|
|
48
|
+
* drop, which a converted assertion shows, while positions can shift, which {@link positional}
|
|
49
|
+
* guards. A composite element between a parent and its child breaks a child combinator, and other
|
|
50
|
+
* combinators and pseudo-classes are excluded.
|
|
51
|
+
*/
|
|
52
|
+
export function domSelector(value: unknown): value is string {
|
|
53
|
+
if (typeof value !== "string" || value === "") return false;
|
|
54
|
+
const tags = compoundTags(value);
|
|
55
|
+
return !!tags && tags.every(tag => tag === undefined || HTML_TAGS.has(tag) || SVG_TAGS.has(tag)) &&
|
|
56
|
+
[...value.matchAll(ATTRIBUTE_VALUE)].every(([, double, single]) => onlyStringPropsRenderTo(double ?? single));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function onlyStringPropsRenderTo(value: string): boolean {
|
|
60
|
+
return value !== "true" && value !== "false" && String(Number(value)) !== value;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function selectorLiteral(node: J | undefined): node is J.Literal {
|
|
64
|
+
return node?.kind === J.Kind.Literal && domSelector((node as J.Literal).value);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The tag of the elements a selector matches. */
|
|
68
|
+
function selectorTag(selector: J.Literal): string | undefined {
|
|
69
|
+
const tags = compoundTags(selector.value as string);
|
|
70
|
+
return tags?.[tags.length - 1];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Whether Enzyme finds exactly the host elements the DOM does, in the same order, which a position
|
|
75
|
+
* into the matches depends on: where every compound names a tag, or `hostNodes()` keeps the host
|
|
76
|
+
* elements a single compound matches.
|
|
77
|
+
*/
|
|
78
|
+
function positional(selector: J.Literal, hostNodes: boolean): boolean {
|
|
79
|
+
const tags = compoundTags(selector.value as string)!;
|
|
80
|
+
return tags.every(tag => tag !== undefined) || (hostNodes && tags.length === 1);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Enzyme's `simulate` calls the React handler directly, while `fireEvent` dispatches a DOM event that
|
|
84
|
+
// React 17 receives through its root container. A dispatched click also runs the default action, such
|
|
85
|
+
// as toggling a checkbox or following a link, so clicks on those elements stay excluded.
|
|
86
|
+
const SIMULATED_EVENTS = new Set(["click", "doubleClick", "mouseDown", "mouseUp", "mouseEnter", "mouseLeave",
|
|
87
|
+
"mouseOver", "mouseOut", "mouseMove", "focus", "blur", "submit", "keyDown", "keyUp", "change", "touchStart",
|
|
88
|
+
"touchMove", "touchEnd", "wheel"]);
|
|
89
|
+
// Enzyme also accepts the DOM's lowercase names of these events, and `dblclick` for a double click
|
|
90
|
+
const NATIVE_EVENT_NAMES = new Map([...[...SIMULATED_EVENTS].map(event => [event.toLowerCase(), event] as const), ["dblclick", "doubleClick"]]);
|
|
91
|
+
const CLICK_DEFAULT_ACTIONS = new Set(["a", "input", "label", "option", "select", "summary", "textarea"]);
|
|
92
|
+
|
|
93
|
+
export function simpleChain(node: Expression): boolean {
|
|
94
|
+
if (node.markers.markers.some(marker => marker.kind === JS.Markers.Optional)) return false;
|
|
95
|
+
if (node.kind === J.Kind.FieldAccess) {
|
|
96
|
+
const field = node as J.FieldAccess;
|
|
97
|
+
return field.name.before.comments.length === 0 && field.name.element.prefix.comments.length === 0 && simpleChain(field.target);
|
|
98
|
+
}
|
|
99
|
+
if (node.kind === J.Kind.MethodInvocation) {
|
|
100
|
+
const call = node as J.MethodInvocation;
|
|
101
|
+
return !call.typeParameters && call.name.prefix.comments.length === 0 &&
|
|
102
|
+
call.arguments.before.comments.length === 0 && call.arguments.elements.every(arg =>
|
|
103
|
+
arg.after.comments.length === 0 && (arg.element.kind !== J.Kind.Empty || arg.element.prefix.comments.length === 0)) &&
|
|
104
|
+
(!call.select || (call.select.after.comments.length === 0 && simpleChain(call.select.element)));
|
|
105
|
+
}
|
|
106
|
+
return isIdentifier(node);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export type WrapperUse = "length" | "exists" | "positionExists" | "nodes" | "selectorText" | "html" | "text" | "hasClass" | "simulate" | "setProps";
|
|
110
|
+
|
|
111
|
+
/** `first` and `last` index like Enzyme's methods of the same name; a literal like `at(n)`. */
|
|
112
|
+
export type ElementIndex = J.Literal | "first" | "last";
|
|
113
|
+
|
|
114
|
+
export interface WrapperRead {
|
|
115
|
+
use: WrapperUse;
|
|
116
|
+
wrapper: J.Identifier;
|
|
117
|
+
selector?: J.Literal;
|
|
118
|
+
index?: ElementIndex;
|
|
119
|
+
/** A `find` within the positioned element. */
|
|
120
|
+
within?: J.Literal;
|
|
121
|
+
/** Found nodes asserted only to be truthy, which any wrapper and any node list are. */
|
|
122
|
+
vacuous?: boolean;
|
|
123
|
+
/** A read outside an assertion, which throws where nothing is found, as Enzyme's single-node methods do. */
|
|
124
|
+
unasserted?: boolean;
|
|
125
|
+
className?: J.Literal;
|
|
126
|
+
event?: string;
|
|
127
|
+
eventInit?: Expression;
|
|
128
|
+
/** The properties a `{nativeEvent}` payload gives the event the handler receives. */
|
|
129
|
+
nativeEvent?: [string, Expression][];
|
|
130
|
+
props?: Expression;
|
|
131
|
+
/** The variable holding the rendered element, which `setProps` clones. */
|
|
132
|
+
element?: string;
|
|
133
|
+
/** Whether each `setProps` assigns its clone to the element, for a later one to clone. */
|
|
134
|
+
reassigned?: boolean;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface WrapperScope {
|
|
138
|
+
declaration: J.VariableDeclarations;
|
|
139
|
+
name: string;
|
|
140
|
+
uses: Map<string, WrapperRead>;
|
|
141
|
+
removedStatements: Set<string>;
|
|
142
|
+
unmounts: Set<string>;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function noArguments(call: J.MethodInvocation): boolean {
|
|
146
|
+
return call.arguments.elements.every(arg => arg.element.kind === J.Kind.Empty);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function call(node: J | undefined, name: string): boolean {
|
|
150
|
+
return node?.kind === J.Kind.MethodInvocation && (node as J.MethodInvocation).name.simpleName === name;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function selectOf(node: J | undefined, target: J): boolean {
|
|
154
|
+
return node?.kind === J.Kind.MethodInvocation && (node as J.MethodInvocation).select?.element === target;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function statement(cursor: Cursor): J | undefined {
|
|
158
|
+
const parent = cursor.parentTree();
|
|
159
|
+
const value = parent?.value as J | undefined;
|
|
160
|
+
if (value?.kind === JS.Kind.ExpressionStatement) return parent!.parentTree()?.value.kind === J.Kind.Block ? value : undefined;
|
|
161
|
+
return value?.kind === J.Kind.Block ? cursor.value as J : undefined;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function statementPosition(cursor: Cursor): boolean {
|
|
165
|
+
return statement(cursor) !== undefined;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The argument `mount` renders, which `render` accepts as it is. */
|
|
169
|
+
export function mountedElement(mount: J.MethodInvocation): boolean {
|
|
170
|
+
const [element] = mount.arguments.elements;
|
|
171
|
+
return mount.arguments.elements.length === 1 && element.element.kind !== J.Kind.Empty && element.element.kind !== JS.Kind.Spread;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The matcher a node list can take the place of found nodes for, as `expect`'s subject. */
|
|
175
|
+
function nodesMatcher(expectCursor: Cursor): "length" | "truthy" | undefined {
|
|
176
|
+
const expect = expectCursor.value as J;
|
|
177
|
+
let matcherCursor = expectCursor.parentTree();
|
|
178
|
+
let negated = false;
|
|
179
|
+
const parent = matcherCursor?.value as J | undefined;
|
|
180
|
+
if (parent?.kind === J.Kind.FieldAccess && (parent as J.FieldAccess).target === expect &&
|
|
181
|
+
(parent as J.FieldAccess).name.element.simpleName === "not") {
|
|
182
|
+
negated = true;
|
|
183
|
+
matcherCursor = matcherCursor!.parentTree();
|
|
184
|
+
}
|
|
185
|
+
const matcher = matcherCursor?.value as J | undefined;
|
|
186
|
+
if (matcher?.kind !== J.Kind.MethodInvocation || (matcher as J.MethodInvocation).select?.element !== (negated ? parent : expect)) return undefined;
|
|
187
|
+
if (call(matcher, "toHaveLength")) return "length";
|
|
188
|
+
return call(matcher, "toBeTruthy") && !negated && noArguments(matcher as J.MethodInvocation) ? "truthy" : undefined;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function stringLiteral(node: J | undefined): node is J.Literal {
|
|
192
|
+
return node?.kind === J.Kind.Literal && typeof (node as J.Literal).value === "string";
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function objectProperties(node: J | undefined): Map<string, Expression> | undefined {
|
|
196
|
+
if (!node || !isObjectLiteral(node) || !node.body) return undefined;
|
|
197
|
+
const properties = new Map<string, Expression>();
|
|
198
|
+
for (const statement of node.body.statements) {
|
|
199
|
+
const property = statement.element as JS.PropertyAssignment;
|
|
200
|
+
if (property.kind !== JS.Kind.PropertyAssignment || property.assigmentToken !== "Colon" ||
|
|
201
|
+
!isIdentifier(property.name.element) || !property.initializer) return undefined;
|
|
202
|
+
properties.set(property.name.element.simpleName, property.initializer);
|
|
203
|
+
}
|
|
204
|
+
return properties;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* `{target: {value}}` sets the value React's change tracking compares, so an empty value, which an
|
|
209
|
+
* input usually starts with, would not call `onChange`. Keyboard events may name their `key`.
|
|
210
|
+
*/
|
|
211
|
+
function eventInit(event: string, init: J | undefined): boolean {
|
|
212
|
+
const properties = objectProperties(init);
|
|
213
|
+
if (event === "change") {
|
|
214
|
+
const target = objectProperties(properties?.get("target"));
|
|
215
|
+
const value = target?.get("value");
|
|
216
|
+
return properties?.size === 1 && target?.size === 1 && value !== undefined && !(stringLiteral(value) && value.value === "");
|
|
217
|
+
}
|
|
218
|
+
if (init === undefined) return true;
|
|
219
|
+
return (event === "keyDown" || event === "keyUp") && properties?.size === 1 && stringLiteral(properties.get("key"));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Enzyme replaces the native event of the synthetic event with a `{nativeEvent}` payload, which a real
|
|
224
|
+
* event whose own properties shadow the same names reproduces for the handler.
|
|
225
|
+
*/
|
|
226
|
+
function nativeEventInit(event: string, init: J | undefined): [string, Expression][] | undefined {
|
|
227
|
+
const properties = objectProperties(init);
|
|
228
|
+
const nativeEvent = objectProperties(properties?.get("nativeEvent"));
|
|
229
|
+
return event !== "change" && properties?.size === 1 && nativeEvent ? [...nativeEvent] : undefined;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function expectArgument(cursor: Cursor, node: J): boolean {
|
|
233
|
+
const parent = cursor.parentTree()?.value as J | undefined;
|
|
234
|
+
if (!call(parent, "expect")) return false;
|
|
235
|
+
const expect = parent as J.MethodInvocation;
|
|
236
|
+
return !expect.select && expect.arguments.elements.length === 1 && expect.arguments.elements[0].element === node;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export interface WrapperDeclaration {
|
|
240
|
+
declaration: J.VariableDeclarations;
|
|
241
|
+
name: string;
|
|
242
|
+
mount: J.MethodInvocation;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export function variableCursor(block: Cursor, declaration: J.VariableDeclarations): Cursor {
|
|
246
|
+
return new Cursor(declaration.variables[0].element, new Cursor(declaration, block));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** A `const` declaration of a wrapper that `classify` accepts the render of, with what it says of the render. */
|
|
250
|
+
export function wrapperDeclaration<R>(statement: J | undefined, classify: (render: J.MethodInvocation) => R | undefined): (WrapperDeclaration & {render: R}) | undefined {
|
|
251
|
+
if (statement?.kind !== J.Kind.VariableDeclarations) return undefined;
|
|
252
|
+
const declaration = statement as J.VariableDeclarations;
|
|
253
|
+
if (declaration.variables.length !== 1 || declaration.typeExpression ||
|
|
254
|
+
!declaration.modifiers.some(modifier => modifier.keyword === "const") ||
|
|
255
|
+
declaration.leadingAnnotations.length > 0) return undefined;
|
|
256
|
+
const variable = declaration.variables[0].element;
|
|
257
|
+
const initializer = variable.initializer?.element;
|
|
258
|
+
if (!isIdentifier(variable.name) || initializer?.kind !== J.Kind.MethodInvocation) return undefined;
|
|
259
|
+
const mount = initializer as J.MethodInvocation;
|
|
260
|
+
if (mount.typeParameters || !mountedElement(mount)) return undefined;
|
|
261
|
+
const render = classify(mount);
|
|
262
|
+
return render === undefined ? undefined : {declaration, name: variable.name.simpleName, mount, render};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Proves that every reference to a block-scoped wrapper is a supported DOM read, so the
|
|
267
|
+
* declaration and all its uses can be converted together. Any other reference, including
|
|
268
|
+
* arguments, returns, and shorthand properties, rejects the whole scope. `events` admits `simulate`
|
|
269
|
+
* and `html` admits `html()`, neither of which a shallow wrapper reads as the DOM does.
|
|
270
|
+
*/
|
|
271
|
+
export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperDeclaration,
|
|
272
|
+
{events, html, untaggedPositions}: {events: boolean, html: boolean, untaggedPositions: boolean}): WrapperScope | undefined {
|
|
273
|
+
const uses = new Map<string, WrapperRead>();
|
|
274
|
+
const removedStatements = new Set<string>();
|
|
275
|
+
const unmounts = new Set<string>();
|
|
276
|
+
let unmounted = false;
|
|
277
|
+
const variable = declaration.variables[0].element;
|
|
278
|
+
|
|
279
|
+
const record = (node: Expression, read: WrapperRead): boolean => {
|
|
280
|
+
if (!simpleChain(node)) return false;
|
|
281
|
+
uses.set(node.id, read);
|
|
282
|
+
return true;
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
const elementIndex = (node: J | undefined, inner: J): ElementIndex | undefined => {
|
|
286
|
+
if (!selectOf(node, inner)) return undefined;
|
|
287
|
+
const method = node as J.MethodInvocation;
|
|
288
|
+
if ((call(method, "first") || call(method, "last")) && noArguments(method)) return method.name.simpleName as "first" | "last";
|
|
289
|
+
const [position] = method.arguments.elements;
|
|
290
|
+
if (call(method, "at") && method.arguments.elements.length === 1 && position.element.kind === J.Kind.Literal &&
|
|
291
|
+
Number.isInteger((position.element as J.Literal).value) && ((position.element as J.Literal).value as number) >= 0) {
|
|
292
|
+
return position.element as J.Literal;
|
|
293
|
+
}
|
|
294
|
+
return undefined;
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
const use = (identifier: J.Identifier, reference: Cursor): boolean => {
|
|
298
|
+
const ancestors: Cursor[] = [];
|
|
299
|
+
for (let c: Cursor | undefined = reference.parentTree(); c && ancestors.length < 5; c = c.parentTree()) ancestors.push(c);
|
|
300
|
+
const first = ancestors[0]?.value as J | undefined;
|
|
301
|
+
if (!selectOf(first, identifier)) return false;
|
|
302
|
+
const method = first as J.MethodInvocation;
|
|
303
|
+
if (call(method, "find")) {
|
|
304
|
+
const args = method.arguments.elements;
|
|
305
|
+
if (args.length !== 1 || !selectorLiteral(args[0].element)) return false;
|
|
306
|
+
const selector = args[0].element;
|
|
307
|
+
let k = 1;
|
|
308
|
+
let inner: J = method;
|
|
309
|
+
let hostNodes = false;
|
|
310
|
+
if (call(ancestors[k]?.value, "hostNodes") && selectOf(ancestors[k].value, inner) && noArguments(ancestors[k].value)) {
|
|
311
|
+
inner = ancestors[k++].value;
|
|
312
|
+
hostNodes = true;
|
|
313
|
+
}
|
|
314
|
+
const index = elementIndex(ancestors[k]?.value, inner);
|
|
315
|
+
let within: J.Literal | undefined;
|
|
316
|
+
if (index) {
|
|
317
|
+
if (!untaggedPositions && !positional(selector, hostNodes)) return false;
|
|
318
|
+
inner = ancestors[k++].value;
|
|
319
|
+
const nested = ancestors[k]?.value as J | undefined;
|
|
320
|
+
if (call(nested, "find") && selectOf(nested, inner)) {
|
|
321
|
+
const [argument] = (nested as J.MethodInvocation).arguments.elements;
|
|
322
|
+
if ((nested as J.MethodInvocation).arguments.elements.length !== 1 || !selectorLiteral(argument.element)) return false;
|
|
323
|
+
within = argument.element;
|
|
324
|
+
inner = ancestors[k++].value;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
const outer = ancestors[k]?.value as J | undefined;
|
|
328
|
+
const outerCursor = ancestors[k];
|
|
329
|
+
const read = {wrapper: identifier, selector, index, within};
|
|
330
|
+
if ((!index || within) && outer?.kind === J.Kind.FieldAccess && (outer as J.FieldAccess).target === inner &&
|
|
331
|
+
(outer as J.FieldAccess).name.element.simpleName === "length") {
|
|
332
|
+
return record(outer as J.FieldAccess, {...read, use: "length"});
|
|
333
|
+
}
|
|
334
|
+
if (!index && expectArgument(ancestors[k - 1], inner)) {
|
|
335
|
+
const matcher = nodesMatcher(outerCursor);
|
|
336
|
+
return matcher !== undefined && record(inner as Expression, {...read, use: "nodes", vacuous: matcher === "truthy"});
|
|
337
|
+
}
|
|
338
|
+
if (!selectOf(outer, inner)) return false;
|
|
339
|
+
const terminal = outer as J.MethodInvocation;
|
|
340
|
+
const terminalArgs = terminal.arguments.elements.filter(arg => arg.element.kind !== J.Kind.Empty).map(arg => arg.element);
|
|
341
|
+
if (call(terminal, "exists") && terminalArgs.length === 0) return record(terminal, {...read, use: !index || within ? "exists" : "positionExists"});
|
|
342
|
+
if (within) return false;
|
|
343
|
+
if ((call(terminal, "text") || html && call(terminal, "html")) && terminalArgs.length === 0) {
|
|
344
|
+
return record(terminal, {...read, use: call(terminal, "text") ? "selectorText" : "html",
|
|
345
|
+
unasserted: !expectArgument(outerCursor, terminal)});
|
|
346
|
+
}
|
|
347
|
+
if (call(terminal, "hasClass") && terminalArgs.length === 1 && stringLiteral(terminalArgs[0]) &&
|
|
348
|
+
/^-?[_a-zA-Z][\w-]*$/.test(terminalArgs[0].value as string)) {
|
|
349
|
+
return record(terminal, {...read, use: "hasClass", className: terminalArgs[0]});
|
|
350
|
+
}
|
|
351
|
+
if (call(terminal, "simulate") && events && statement(outerCursor) && terminalArgs.length >= 1 && terminalArgs.length <= 2 &&
|
|
352
|
+
stringLiteral(terminalArgs[0])) {
|
|
353
|
+
const name = terminalArgs[0].value as string;
|
|
354
|
+
const event = SIMULATED_EVENTS.has(name) ? name : NATIVE_EVENT_NAMES.get(name);
|
|
355
|
+
if (!event) return false;
|
|
356
|
+
const nativeEvent = nativeEventInit(event, terminalArgs[1]);
|
|
357
|
+
if (!nativeEvent && !eventInit(event, terminalArgs[1])) return false;
|
|
358
|
+
if (event === "click" && CLICK_DEFAULT_ACTIONS.has(selectorTag(selector) ?? "")) return false;
|
|
359
|
+
return record(terminal, {...read, use: "simulate", event, ...nativeEvent ? {nativeEvent} : {eventInit: terminalArgs[1]}});
|
|
360
|
+
}
|
|
361
|
+
return false;
|
|
362
|
+
}
|
|
363
|
+
const [argument] = method.arguments.elements;
|
|
364
|
+
if (call(method, "exists") && method.arguments.elements.length === 1 && selectorLiteral(argument.element)) {
|
|
365
|
+
return record(method, {wrapper: identifier, selector: argument.element, use: "exists"});
|
|
366
|
+
}
|
|
367
|
+
if (call(method, "setProps") && method.arguments.elements.length === 1 && statement(ancestors[0]) &&
|
|
368
|
+
argument.element.kind !== J.Kind.Empty && argument.element.kind !== JS.Kind.Spread) {
|
|
369
|
+
return record(method, {wrapper: identifier, use: "setProps", props: argument.element as Expression});
|
|
370
|
+
}
|
|
371
|
+
if (!noArguments(method)) return false;
|
|
372
|
+
if (call(method, "text")) return record(method, {wrapper: identifier, use: "text", unasserted: !expectArgument(ancestors[0], method)});
|
|
373
|
+
if (call(method, "update") && statement(ancestors[0])?.prefix.comments.length === 0 && method.prefix.comments.length === 0) {
|
|
374
|
+
removedStatements.add(method.id);
|
|
375
|
+
return simpleChain(method);
|
|
376
|
+
}
|
|
377
|
+
if (call(method, "unmount") && statement(ancestors[0])) {
|
|
378
|
+
unmounted = true;
|
|
379
|
+
unmounts.add(method.id);
|
|
380
|
+
return simpleChain(method);
|
|
381
|
+
}
|
|
382
|
+
return false;
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
const declared = new Cursor(variable.name, variableCursor(block, declaration));
|
|
386
|
+
const references = referencesOf(declared, name, "value");
|
|
387
|
+
if (!references.some(reference => reference.identifier === variable.name)) return undefined;
|
|
388
|
+
for (const reference of references) {
|
|
389
|
+
if (reference.identifier === variable.name) continue;
|
|
390
|
+
if (reference.declares || unmounted || !use(reference.identifier, reference.cursor)) return undefined;
|
|
391
|
+
}
|
|
392
|
+
return {declaration, name, uses, removedStatements, unmounts};
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** The call a chain of calls and field accesses starts with, such as `mount(...)` in `mount(...).find(...).length`. */
|
|
396
|
+
export function innermostCall(node: J): J.MethodInvocation | undefined {
|
|
397
|
+
let call: J.MethodInvocation | undefined;
|
|
398
|
+
for (let current: J | undefined = node; current;) {
|
|
399
|
+
if (current.kind === J.Kind.FieldAccess) current = (current as J.FieldAccess).target;
|
|
400
|
+
else if (current.kind === J.Kind.MethodInvocation) {
|
|
401
|
+
call = current as J.MethodInvocation;
|
|
402
|
+
current = call.select?.element;
|
|
403
|
+
} else break;
|
|
404
|
+
}
|
|
405
|
+
return call;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
export function idsWithin(node: J, ids: Set<string>): string[] {
|
|
409
|
+
const found: string[] = [];
|
|
410
|
+
walk(node, tree => {
|
|
411
|
+
if (ids.has(tree.id)) found.push(tree.id);
|
|
412
|
+
return true;
|
|
413
|
+
});
|
|
414
|
+
return found;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* A converted wrapper keeps its name, but no longer holds an Enzyme wrapper. Drop the stale
|
|
419
|
+
* Enzyme attribution so that the inventory does not report converted code.
|
|
420
|
+
*/
|
|
421
|
+
export async function withoutEnzymeTypes<T extends J>(node: T, ctx: ExecutionContext): Promise<T> {
|
|
422
|
+
return await new class extends JavaScriptVisitor<ExecutionContext> {
|
|
423
|
+
override async visitIdentifier(identifier: J.Identifier, ctx: ExecutionContext): Promise<J | undefined> {
|
|
424
|
+
const visited = await super.visitIdentifier(identifier, ctx) as J.Identifier;
|
|
425
|
+
if (!enzymeWrapper(visited.type)) return visited;
|
|
426
|
+
return {...visited, type: undefined, fieldType: undefined} as J.Identifier;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
|
|
430
|
+
const visited = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
|
|
431
|
+
if (!enzymeMethod(visited)) return visited;
|
|
432
|
+
return {...visited, methodType: undefined} as J.MethodInvocation;
|
|
433
|
+
}
|
|
434
|
+
}().visit(node, ctx) as T;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Keeps a multi-line `mount(\n element\n)` call's closing line break before the closing
|
|
439
|
+
* parenthesis, rather than before the render options added after the element argument.
|
|
440
|
+
*/
|
|
441
|
+
export async function withRenderOptionsOnElementLine<T extends J>(node: T, ctx: ExecutionContext): Promise<T> {
|
|
442
|
+
return await new class extends JavaScriptVisitor<ExecutionContext> {
|
|
443
|
+
override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
|
|
444
|
+
const [element, options] = method.arguments.elements;
|
|
445
|
+
if (method.arguments.elements.length !== 2 || !objectProperties(options.element)?.has("container")) {
|
|
446
|
+
return super.visitMethodInvocation(method, ctx);
|
|
447
|
+
}
|
|
448
|
+
if (!element.after.whitespace.includes("\n") || element.after.comments.length > 0 ||
|
|
449
|
+
options.after.whitespace !== "" || options.after.comments.length > 0) return method;
|
|
450
|
+
return create(method, draft => {
|
|
451
|
+
draft.arguments.elements[1].after = element.after as any;
|
|
452
|
+
draft.arguments.elements[0].after = emptySpace as any;
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
}().visit(node, ctx) as T;
|
|
456
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import {JS, moduleNameOf} from "@openrewrite/rewrite/javascript";
|
|
2
|
+
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
3
|
+
import {posix} from "path";
|
|
4
|
+
|
|
5
|
+
/** A value an ES module import binds: its local name, the export it names (`default` for a default import), and the module. */
|
|
6
|
+
export interface ImportBinding {
|
|
7
|
+
local: string;
|
|
8
|
+
name: string;
|
|
9
|
+
module: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** The values a source binds with top-level ES module imports, leaving out type-only and namespace imports. */
|
|
13
|
+
export function importBindings(cu: JS.CompilationUnit): ImportBinding[] {
|
|
14
|
+
const bindings: ImportBinding[] = [];
|
|
15
|
+
for (const {element} of cu.statements) {
|
|
16
|
+
if (element.kind !== JS.Kind.Import) continue;
|
|
17
|
+
const declaration = element as JS.Import;
|
|
18
|
+
const specifier = declaration.moduleSpecifier?.element;
|
|
19
|
+
const clause = declaration.importClause;
|
|
20
|
+
if (specifier?.kind !== J.Kind.Literal || !clause || clause.typeOnly) continue;
|
|
21
|
+
const module = moduleNameOf(specifier as J.Literal);
|
|
22
|
+
if (clause.name) bindings.push({local: clause.name.element.simpleName, name: "default", module});
|
|
23
|
+
if (clause.namedBindings?.kind !== JS.Kind.NamedImports) continue;
|
|
24
|
+
for (const {element: imported} of (clause.namedBindings as JS.NamedImports).elements.elements) {
|
|
25
|
+
if (imported.kind !== JS.Kind.ImportSpecifier || imported.importType.element) continue;
|
|
26
|
+
const named = imported.specifier;
|
|
27
|
+
if (isIdentifier(named)) bindings.push({local: named.simpleName, name: named.simpleName, module});
|
|
28
|
+
if (named.kind === JS.Kind.Alias && isIdentifier(named.alias)) {
|
|
29
|
+
const property = named.propertyName.element;
|
|
30
|
+
bindings.push({local: named.alias.simpleName, name: isIdentifier(property) ? property.simpleName : String((property as J.Literal).value), module});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return bindings;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The local names of a source's namespace imports, `import * as name`, which bind a whole module. */
|
|
38
|
+
export function namespaceImports(cu: JS.CompilationUnit): string[] {
|
|
39
|
+
const names: string[] = [];
|
|
40
|
+
for (const {element} of cu.statements) {
|
|
41
|
+
const bindings = element.kind === JS.Kind.Import ? (element as JS.Import).importClause?.namedBindings : undefined;
|
|
42
|
+
if (bindings?.kind === JS.Kind.Alias && isIdentifier((bindings as JS.Alias).alias)) names.push(((bindings as JS.Alias).alias as J.Identifier).simpleName);
|
|
43
|
+
}
|
|
44
|
+
return names;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Node resolves a relative specifier to the file before the directory's index
|
|
48
|
+
const RESOLVED = ["", ".js", ".jsx", ".ts", ".tsx", "/index.js", "/index.jsx", "/index.ts", "/index.tsx"];
|
|
49
|
+
|
|
50
|
+
/** The source a relative module specifier resolves to from the source at `from`, as Node resolves it among `sources`. */
|
|
51
|
+
export function resolveRelative(from: string, specifier: string, sources: {has(path: string): boolean}): string | undefined {
|
|
52
|
+
if (!/^\.\.?(?:\/|$)/.test(specifier)) return undefined;
|
|
53
|
+
const base = posix.normalize(posix.join(posix.dirname(from), specifier));
|
|
54
|
+
return RESOLVED.map(suffix => base + suffix).find(path => sources.has(path));
|
|
55
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import {J} from "@openrewrite/rewrite/java";
|
|
2
|
+
import {JS} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
|
|
4
|
+
/** The React base classes of a class component. */
|
|
5
|
+
export const COMPONENT_BASES: ReadonlySet<string> = new Set(['Component', 'PureComponent']);
|
|
6
|
+
|
|
7
|
+
/** `Component<P, S>` is a parameterized type (possibly wrapped in a type-tree expression) around the plain name; this returns that name. */
|
|
8
|
+
export function unwrapBaseType(type: J | undefined): J | undefined {
|
|
9
|
+
if (type?.kind === JS.Kind.TypeTreeExpression) return unwrapBaseType((type as JS.TypeTreeExpression).expression);
|
|
10
|
+
if (type?.kind === J.Kind.ParameterizedType) return (type as J.ParameterizedType).class;
|
|
11
|
+
if (type?.kind === JS.Kind.ExpressionWithTypeArguments) return (type as JS.ExpressionWithTypeArguments).clazz;
|
|
12
|
+
return type;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The type arguments of `Component<P, S>`, however the parser represents the parameterized base. */
|
|
16
|
+
export function baseTypeArguments(type: J | undefined): J.Container<J> | undefined {
|
|
17
|
+
if (type?.kind === JS.Kind.TypeTreeExpression) return baseTypeArguments((type as JS.TypeTreeExpression).expression);
|
|
18
|
+
if (type?.kind === J.Kind.ParameterizedType) return (type as J.ParameterizedType).typeParameters;
|
|
19
|
+
if (type?.kind === JS.Kind.ExpressionWithTypeArguments) return (type as JS.ExpressionWithTypeArguments).typeArguments;
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The simple name of the class a declaration extends (`Component` for both `Component` and `React.Component`). */
|
|
24
|
+
export function extendedClassName(cd: J.ClassDeclaration): string | undefined {
|
|
25
|
+
const base = unwrapBaseType(cd.extends?.element);
|
|
26
|
+
if (base?.kind === J.Kind.Identifier) return (base as J.Identifier).simpleName;
|
|
27
|
+
if (base?.kind === J.Kind.FieldAccess) return (base as J.FieldAccess).name.element.simpleName;
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Whether the class extends `Component` or `PureComponent`, qualified or not. Matches by name only. */
|
|
32
|
+
export function extendsReactComponentByName(cd: J.ClassDeclaration): boolean {
|
|
33
|
+
const name = extendedClassName(cd);
|
|
34
|
+
return !!name && COMPONENT_BASES.has(name);
|
|
35
|
+
}
|