@openrewrite/recipes-react 0.28.0 → 0.31.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/change-react-type.d.ts +14 -0
- package/dist/change-react-type.d.ts.map +1 -0
- package/dist/change-react-type.js +41 -0
- package/dist/change-react-type.js.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +67 -2
- package/dist/index.js.map +1 -1
- package/dist/react18/add-children-to-props.d.ts.map +1 -1
- package/dist/react18/add-children-to-props.js +24 -6
- package/dist/react18/add-children-to-props.js.map +1 -1
- package/dist/react18/deprecated-react-type.d.ts +8 -0
- package/dist/react18/deprecated-react-type.d.ts.map +1 -0
- package/dist/react18/deprecated-react-type.js +29 -0
- package/dist/react18/deprecated-react-type.js.map +1 -0
- package/dist/react18/deprecated-sfc-element.d.ts +8 -0
- package/dist/react18/deprecated-sfc-element.d.ts.map +1 -0
- package/dist/react18/deprecated-sfc-element.js +29 -0
- package/dist/react18/deprecated-sfc-element.js.map +1 -0
- package/dist/react18/deprecated-sfc.d.ts +8 -0
- package/dist/react18/deprecated-sfc.d.ts.map +1 -0
- package/dist/react18/deprecated-sfc.js +29 -0
- package/dist/react18/deprecated-sfc.js.map +1 -0
- package/dist/react18/deprecated-stateless-component.d.ts +8 -0
- package/dist/react18/deprecated-stateless-component.d.ts.map +1 -0
- package/dist/react18/deprecated-stateless-component.js +29 -0
- package/dist/react18/deprecated-stateless-component.js.map +1 -0
- package/dist/react19/deprecated-legacy-ref.d.ts +8 -0
- package/dist/react19/deprecated-legacy-ref.d.ts.map +1 -0
- package/dist/react19/deprecated-legacy-ref.js +29 -0
- package/dist/react19/deprecated-legacy-ref.js.map +1 -0
- package/dist/react19/deprecated-prop-types-types.d.ts +23 -0
- package/dist/react19/deprecated-prop-types-types.d.ts.map +1 -0
- package/dist/react19/deprecated-prop-types-types.js +191 -0
- package/dist/react19/deprecated-prop-types-types.js.map +1 -0
- package/dist/react19/deprecated-react-child.d.ts +8 -0
- package/dist/react19/deprecated-react-child.d.ts.map +1 -0
- package/dist/react19/deprecated-react-child.js +91 -0
- package/dist/react19/deprecated-react-child.js.map +1 -0
- package/dist/react19/deprecated-react-fragment.d.ts +8 -0
- package/dist/react19/deprecated-react-fragment.d.ts.map +1 -0
- package/dist/react19/deprecated-react-fragment.js +92 -0
- package/dist/react19/deprecated-react-fragment.js.map +1 -0
- package/dist/react19/deprecated-react-node-array.d.ts +8 -0
- package/dist/react19/deprecated-react-node-array.d.ts.map +1 -0
- package/dist/react19/deprecated-react-node-array.js +92 -0
- package/dist/react19/deprecated-react-node-array.js.map +1 -0
- package/dist/react19/deprecated-react-text.d.ts +8 -0
- package/dist/react19/deprecated-react-text.d.ts.map +1 -0
- package/dist/react19/deprecated-react-text.js +91 -0
- package/dist/react19/deprecated-react-text.js.map +1 -0
- package/dist/react19/deprecated-react-types.d.ts.map +1 -1
- package/dist/react19/deprecated-react-types.js +3 -104
- package/dist/react19/deprecated-react-types.js.map +1 -1
- package/dist/react19/deprecated-void-function-component.d.ts +8 -0
- package/dist/react19/deprecated-void-function-component.d.ts.map +1 -0
- package/dist/react19/deprecated-void-function-component.js +32 -0
- package/dist/react19/deprecated-void-function-component.js.map +1 -0
- package/dist/react19/refobject-defaults.d.ts +13 -0
- package/dist/react19/refobject-defaults.d.ts.map +1 -0
- package/dist/react19/refobject-defaults.js +152 -0
- package/dist/react19/refobject-defaults.js.map +1 -0
- package/dist/react19/remove-react-fc.js +3 -2
- package/dist/react19/remove-react-fc.js.map +1 -1
- package/dist/react19/replace-act-import.d.ts +8 -0
- package/dist/react19/replace-act-import.d.ts.map +1 -0
- package/dist/react19/replace-act-import.js +29 -0
- package/dist/react19/replace-act-import.js.map +1 -0
- package/dist/react19/replace-react-shallow-renderer.d.ts +8 -0
- package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -0
- package/dist/react19/replace-react-shallow-renderer.js +29 -0
- package/dist/react19/replace-react-shallow-renderer.js.map +1 -0
- package/dist/react19/replace-use-form-state.d.ts +8 -0
- package/dist/react19/replace-use-form-state.d.ts.map +1 -0
- package/dist/react19/replace-use-form-state.js +29 -0
- package/dist/react19/replace-use-form-state.js.map +1 -0
- package/dist/types/imports.d.ts +31 -0
- package/dist/types/imports.d.ts.map +1 -0
- package/dist/types/imports.js +385 -0
- package/dist/types/imports.js.map +1 -0
- package/dist/types/index.d.ts +11 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +33 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/module.d.ts +6 -0
- package/dist/types/module.d.ts.map +1 -0
- package/dist/types/module.js +5 -0
- package/dist/types/module.js.map +1 -0
- package/dist/types/re-export.d.ts +5 -0
- package/dist/types/re-export.d.ts.map +1 -0
- package/dist/types/re-export.js +12 -0
- package/dist/types/re-export.js.map +1 -0
- package/dist/types/reference.d.ts +20 -0
- package/dist/types/reference.d.ts.map +1 -0
- package/dist/types/reference.js +161 -0
- package/dist/types/reference.js.map +1 -0
- package/dist/types/rename.d.ts +10 -0
- package/dist/types/rename.d.ts.map +1 -0
- package/dist/types/rename.js +136 -0
- package/dist/types/rename.js.map +1 -0
- package/dist/types/replace.d.ts +8 -0
- package/dist/types/replace.d.ts.map +1 -0
- package/dist/types/replace.js +122 -0
- package/dist/types/replace.js.map +1 -0
- package/dist/util/java-recipe-proxy.d.ts +1 -0
- package/dist/util/java-recipe-proxy.d.ts.map +1 -1
- package/dist/util/java-recipe-proxy.js +3 -1
- package/dist/util/java-recipe-proxy.js.map +1 -1
- package/package.json +2 -2
- package/src/change-react-type.ts +32 -0
- package/src/index.ts +48 -0
- package/src/migration/cra-to-vite/add-vite-config.ts +0 -1
- package/src/react18/add-children-to-props.ts +22 -7
- package/src/react18/deprecated-react-type.ts +19 -0
- package/src/react18/deprecated-sfc-element.ts +19 -0
- package/src/react18/deprecated-sfc.ts +19 -0
- package/src/react18/deprecated-stateless-component.ts +19 -0
- package/src/react19/deprecated-legacy-ref.ts +19 -0
- package/src/react19/deprecated-prop-types-types.ts +170 -0
- package/src/react19/deprecated-react-child.ts +67 -0
- package/src/react19/deprecated-react-fragment.ts +74 -0
- package/src/react19/deprecated-react-node-array.ts +74 -0
- package/src/react19/deprecated-react-text.ts +66 -0
- package/src/react19/deprecated-react-types.ts +4 -95
- package/src/react19/deprecated-void-function-component.ts +22 -0
- package/src/react19/refobject-defaults.ts +120 -0
- package/src/react19/remove-react-fc.ts +3 -3
- package/src/react19/replace-act-import.ts +19 -0
- package/src/react19/replace-react-shallow-renderer.ts +19 -0
- package/src/react19/replace-use-form-state.ts +19 -0
- package/src/types/imports.ts +396 -0
- package/src/types/index.ts +21 -0
- package/src/types/module.ts +10 -0
- package/src/types/re-export.ts +14 -0
- package/src/types/reference.ts +186 -0
- package/src/types/rename.ts +112 -0
- package/src/types/replace.ts +123 -0
- package/src/util/java-recipe-proxy.ts +3 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import {check, Cursor, ExecutionContext, foundSearchResult, ScanningRecipe, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
3
|
+
import {findNodeResolutionResult, JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
|
|
4
|
+
import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
|
|
5
|
+
import {major, minVersion, satisfies, valid, validRange} from "semver";
|
|
6
|
+
import {importTypeReferenceOf, onTypeScriptSources, react, typeReferenceOf, unionWith} from "../types";
|
|
7
|
+
import {treesOfType} from "../util/java-recipe-proxy";
|
|
8
|
+
|
|
9
|
+
type TypesReactMajors = Map<string, number>;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Before: `const ref: RefObject<HTMLDivElement> = createRef();`
|
|
13
|
+
* After: `const ref: RefObject<HTMLDivElement | null> = createRef();`
|
|
14
|
+
*
|
|
15
|
+
* Unlike a rename of a removed type, this is not idempotent across versions: `RefObject<T>` is valid on both, and code
|
|
16
|
+
* written for `@types/react` 19 means `current` to be non-null. So, as `PreV5Recipe` does for Material UI, it only edits
|
|
17
|
+
* the sources of a package still on `@types/react` 18 or earlier, read before the first cycle edits anything, so the
|
|
18
|
+
* bump in the same run doesn't count.
|
|
19
|
+
*
|
|
20
|
+
* @see https://react.dev/blog/2024/04/25/react-19-upgrade-guide#useref-requires-argument
|
|
21
|
+
*/
|
|
22
|
+
export class RefObjectDefaults extends ScanningRecipe<TypesReactMajors> {
|
|
23
|
+
readonly name = "org.openrewrite.react.19.refobject-defaults";
|
|
24
|
+
readonly displayName = "Add `null` to the type argument of `RefObject`";
|
|
25
|
+
readonly description = "Replaces React's `RefObject<T>` with `RefObject<T | null>`, since `@types/react` 19 no longer makes `current` nullable. Only edits a package still on `@types/react` 18 or earlier, as its lockfile resolves it or else as its range allows, since code written for 19 means `current` to be non-null. Leaves `any`, a type argument that already includes `null` or `any`, and `MutableRefObject` alone.";
|
|
26
|
+
|
|
27
|
+
initialValue(): TypesReactMajors {
|
|
28
|
+
return new Map();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async scanner(majors: TypesReactMajors): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
32
|
+
return new class extends JsonVisitor<ExecutionContext> {
|
|
33
|
+
override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
|
|
34
|
+
if (!/(^|\/)package\.json$/.test(doc.sourcePath)) return doc;
|
|
35
|
+
const root = doc.sourcePath.slice(0, -"package.json".length);
|
|
36
|
+
const found = typesReactMajor(doc);
|
|
37
|
+
if (found !== undefined && !majors.has(root)) majors.set(root, found);
|
|
38
|
+
return doc;
|
|
39
|
+
}
|
|
40
|
+
}();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async editorWithData(majors: TypesReactMajors): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
44
|
+
const before19 = new class extends JavaScriptVisitor<ExecutionContext> {
|
|
45
|
+
override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
|
|
46
|
+
const found = majorAt(cu.sourcePath, majors);
|
|
47
|
+
return found !== undefined && found < 19 ? foundSearchResult(cu) : cu;
|
|
48
|
+
}
|
|
49
|
+
}();
|
|
50
|
+
return check(before19, onTypeScriptSources(new class extends JavaScriptVisitor<ExecutionContext> {
|
|
51
|
+
override async visitParameterizedType(type: J.ParameterizedType, ctx: ExecutionContext): Promise<J | undefined> {
|
|
52
|
+
const pt = await super.visitParameterizedType(type, ctx) as J.ParameterizedType;
|
|
53
|
+
if (!pt.typeParameters || !isRefObject(new Cursor(pt.class, this.cursor), pt.class)) return pt;
|
|
54
|
+
const typeParameters = await withNullableFirst(pt.typeParameters);
|
|
55
|
+
return typeParameters === pt.typeParameters ? pt : {...pt, typeParameters} as J.ParameterizedType;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
override async visitExpressionWithTypeArguments(expression: JS.ExpressionWithTypeArguments, ctx: ExecutionContext): Promise<J | undefined> {
|
|
59
|
+
const e = await super.visitExpressionWithTypeArguments(expression, ctx) as JS.ExpressionWithTypeArguments;
|
|
60
|
+
if (!e.typeArguments || !isRefObject(new Cursor(e.clazz, this.cursor), e.clazz)) return e;
|
|
61
|
+
const typeArguments = await withNullableFirst(e.typeArguments);
|
|
62
|
+
return typeArguments === e.typeArguments ? e : {...e, typeArguments} as JS.ExpressionWithTypeArguments;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
override async visitImportType(importType: JS.ImportType, ctx: ExecutionContext): Promise<J | undefined> {
|
|
66
|
+
const it = await super.visitImportType(importType, ctx) as JS.ImportType;
|
|
67
|
+
if (!it.typeArguments || importTypeReferenceOf(it, react)?.member !== 'RefObject') return it;
|
|
68
|
+
const typeArguments = await withNullableFirst(it.typeArguments);
|
|
69
|
+
return typeArguments === it.typeArguments ? it : {...it, typeArguments} as JS.ImportType;
|
|
70
|
+
}
|
|
71
|
+
}()));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// HACK: core's ScanningRecipe.editor() hides editorWithData behind a lazy wrapper, so the host would send the editor
|
|
75
|
+
// every tree (openrewrite/rewrite#9734)
|
|
76
|
+
override async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
77
|
+
return check(treesOfType("org.openrewrite.javascript.tree.JS"), super.editor());
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function typesReactMajor(doc: Json.Document): number | undefined {
|
|
82
|
+
const resolution = findNodeResolutionResult(doc);
|
|
83
|
+
const declared = [...resolution?.dependencies ?? [], ...resolution?.devDependencies ?? [],
|
|
84
|
+
...resolution?.optionalDependencies ?? [], ...resolution?.peerDependencies ?? []].filter(dep => dep.name === '@types/react');
|
|
85
|
+
const resolved = declared.map(dep => dep.resolved?.version).find((version, i) => version !== undefined && valid(version) !== null &&
|
|
86
|
+
(!validRange(declared[i].versionConstraint) || satisfies(version, declared[i].versionConstraint)));
|
|
87
|
+
if (resolved) return major(resolved);
|
|
88
|
+
const lowest = declared.map(dep => validRange(dep.versionConstraint) ? minVersion(dep.versionConstraint) : null).find(version => version);
|
|
89
|
+
return lowest ? lowest.major : undefined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function majorAt(path: string, majors: TypesReactMajors): number | undefined {
|
|
93
|
+
let nearest: string | undefined;
|
|
94
|
+
for (const root of majors.keys()) if (path.startsWith(root) && (nearest === undefined || root.length > nearest.length)) nearest = root;
|
|
95
|
+
return nearest === undefined ? undefined : majors.get(nearest);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isRefObject(cursor: Cursor, name: J): boolean {
|
|
99
|
+
return typeReferenceOf(cursor, name, react)?.member === 'RefObject';
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function withNullableFirst<T extends J>(typeArguments: J.Container<T>): Promise<J.Container<T>> {
|
|
103
|
+
const [first, ...rest] = typeArguments.elements;
|
|
104
|
+
if (!first || membersOf(first.element).some(t => isNull(t) || isAny(t))) return typeArguments;
|
|
105
|
+
return {...typeArguments, elements: [{...first, element: await unionWith(first.element, 'null') as T}, ...rest]};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function membersOf(type: J): J[] {
|
|
109
|
+
if (type.kind === JS.Kind.Union) return (type as JS.Union).types.flatMap(t => membersOf(t.element));
|
|
110
|
+
if (type.kind === J.Kind.ParenthesizedTypeTree) return membersOf((type as J.ParenthesizedTypeTree).parenthesizedType.tree.element);
|
|
111
|
+
return [type];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function isNull(type: J): boolean {
|
|
115
|
+
return type.kind === JS.Kind.LiteralType && ((type as JS.LiteralType).literal as J.Literal).valueSource === 'null';
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function isAny(type: J): boolean {
|
|
119
|
+
return isIdentifier(type) && type.simpleName === 'any';
|
|
120
|
+
}
|
|
@@ -5,11 +5,11 @@ import {
|
|
|
5
5
|
pattern,
|
|
6
6
|
rewrite,
|
|
7
7
|
template,
|
|
8
|
-
maybeUnbind,
|
|
9
8
|
isVendoredOrBundled
|
|
10
9
|
} from "@openrewrite/rewrite/javascript";
|
|
11
10
|
import {Expression, J, singleSpace, emptySpace} from "@openrewrite/rewrite/java";
|
|
12
11
|
import {JS} from "@openrewrite/rewrite/javascript";
|
|
12
|
+
import {dropImport, react} from "../types";
|
|
13
13
|
|
|
14
14
|
/**
|
|
15
15
|
* Removes React.FC and FC type annotations from functional components.
|
|
@@ -105,8 +105,8 @@ export class RemoveReactFC extends Recipe {
|
|
|
105
105
|
: arrowFn;
|
|
106
106
|
|
|
107
107
|
// Remove the type expression and update the initializer
|
|
108
|
-
|
|
109
|
-
|
|
108
|
+
dropImport(this, react, "FC");
|
|
109
|
+
dropImport(this, react, "FunctionComponent");
|
|
110
110
|
|
|
111
111
|
const updatedVarDecl: J.VariableDeclarations = {
|
|
112
112
|
...v,
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import {Recipe} from "@openrewrite/rewrite";
|
|
2
|
+
import {ChangeImport} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* This recipe can be replaced by an inline `change-import` entry in `react-migrate.yml` once
|
|
6
|
+
* {@link https://github.com/openrewrite/rewrite/issues/10113 openrewrite/rewrite#10113} is fixed. Until then, the
|
|
7
|
+
* platform can't load a TypeScript recipe configured with options from the jar's YAML.
|
|
8
|
+
*
|
|
9
|
+
* @see https://react.dev/blog/2024/04/25/react-19-upgrade-guide#removed-react-dom-test-utils
|
|
10
|
+
*/
|
|
11
|
+
export class ReplaceActImport extends Recipe {
|
|
12
|
+
readonly name = "org.openrewrite.react.19.replace-act-import";
|
|
13
|
+
readonly displayName = "Replace `act` import from `react-dom/test-utils`";
|
|
14
|
+
readonly description = "Imports `act` from `react` instead of `react-dom/test-utils`, where React 19 deprecated it and removed the other test utilities.";
|
|
15
|
+
|
|
16
|
+
async recipeList(): Promise<Recipe[]> {
|
|
17
|
+
return [new ChangeImport({oldModule: "react-dom/test-utils", oldMember: "act", newModule: "react"})];
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import {Recipe} from "@openrewrite/rewrite";
|
|
2
|
+
import {ChangeModuleSpecifier} from "../mui/change-module-specifier";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* This recipe can be replaced by an inline `mui.change-module-specifier` entry in `react-migrate.yml` once
|
|
6
|
+
* {@link https://github.com/openrewrite/rewrite/issues/10113 openrewrite/rewrite#10113} is fixed. Until then, the
|
|
7
|
+
* platform can't load a TypeScript recipe configured with options from the jar's YAML.
|
|
8
|
+
*
|
|
9
|
+
* @see https://react.dev/blog/2024/04/25/react-19-upgrade-guide#removed-react-test-renderer-shallow
|
|
10
|
+
*/
|
|
11
|
+
export class ReplaceReactShallowRenderer extends Recipe {
|
|
12
|
+
readonly name = "org.openrewrite.react.19.replace-react-shallow-renderer";
|
|
13
|
+
readonly displayName = "Replace `react-test-renderer/shallow` import";
|
|
14
|
+
readonly description = "Imports the shallow renderer from the standalone `react-shallow-renderer` package instead of `react-test-renderer/shallow`, which React 19 removed.";
|
|
15
|
+
|
|
16
|
+
async recipeList(): Promise<Recipe[]> {
|
|
17
|
+
return [new ChangeModuleSpecifier({oldPattern: "react-test-renderer/shallow", newModule: "react-shallow-renderer"})];
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import {Recipe} from "@openrewrite/rewrite";
|
|
2
|
+
import {ChangeImport} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* This recipe can be replaced by an inline `change-import` entry in `react-migrate.yml` once
|
|
6
|
+
* {@link https://github.com/openrewrite/rewrite/issues/10113 openrewrite/rewrite#10113} is fixed. Until then, the
|
|
7
|
+
* platform can't load a TypeScript recipe configured with options from the jar's YAML.
|
|
8
|
+
*
|
|
9
|
+
* @see https://react.dev/blog/2024/12/05/react-19#new-hook-useactionstate
|
|
10
|
+
*/
|
|
11
|
+
export class ReplaceUseFormState extends Recipe {
|
|
12
|
+
readonly name = "org.openrewrite.react.19.replace-use-form-state";
|
|
13
|
+
readonly displayName = "Replace `useFormState` with `useActionState`";
|
|
14
|
+
readonly description = "Replaces `useFormState` from `react-dom` with `useActionState` from `react`, its React 19 name.";
|
|
15
|
+
|
|
16
|
+
async recipeList(): Promise<Recipe[]> {
|
|
17
|
+
return [new ChangeImport({oldModule: "react-dom", oldMember: "useFormState", newModule: "react", newMember: "useActionState"})];
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
import {Cursor, randomId} from "@openrewrite/rewrite";
|
|
2
|
+
import {emptySpace, isIdentifier, J, singleSpace} from "@openrewrite/rewrite/java";
|
|
3
|
+
import {
|
|
4
|
+
bindingNames,
|
|
5
|
+
JavaScriptParser,
|
|
6
|
+
JavaScriptVisitor,
|
|
7
|
+
JS,
|
|
8
|
+
namesUsedWithin,
|
|
9
|
+
RemoveImport,
|
|
10
|
+
resolve
|
|
11
|
+
} from "@openrewrite/rewrite/javascript";
|
|
12
|
+
import {Module} from "./module";
|
|
13
|
+
import {typeReferenceOf} from "./reference";
|
|
14
|
+
|
|
15
|
+
/** A file, or a `declare module '…' {}` block, which holds imports of its own. */
|
|
16
|
+
export type ImportScope = JS.CompilationUnit | J.Block;
|
|
17
|
+
|
|
18
|
+
export interface ModuleImports {
|
|
19
|
+
/** Local name → the module's member it binds. `F` → `FC` for `import {FC as F}`. */
|
|
20
|
+
readonly named: Map<string, { member: string, typeOnly: boolean }>;
|
|
21
|
+
/** Namespace and default imports. `R` for `import * as R`. */
|
|
22
|
+
readonly qualifiers: Set<string>;
|
|
23
|
+
/** Whether anything, from any module, binds the module's UMD global. */
|
|
24
|
+
readonly bindsGlobal: boolean;
|
|
25
|
+
/** `R` for `import type R from 'react'`, which can qualify a type but takes no named import. */
|
|
26
|
+
readonly typeOnlyDefault?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const importsCache = new WeakMap<ImportScope, Map<string, ModuleImports>>();
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* What a scope's own imports bind of `from`.
|
|
33
|
+
* `import {FC as F, type ReactNode} from 'react'` → `named: {F → FC, ReactNode → ReactNode (type-only)}`
|
|
34
|
+
*/
|
|
35
|
+
export function importsOf(scope: ImportScope, from: Module): ModuleImports {
|
|
36
|
+
let byModule = importsCache.get(scope);
|
|
37
|
+
if (!byModule) importsCache.set(scope, byModule = new Map());
|
|
38
|
+
let imports = byModule.get(from.module);
|
|
39
|
+
if (imports) return imports;
|
|
40
|
+
const named = new Map<string, { member: string, typeOnly: boolean }>();
|
|
41
|
+
const qualifiers = new Set<string>();
|
|
42
|
+
let bindsGlobal = false;
|
|
43
|
+
let typeOnlyDefault: string | undefined;
|
|
44
|
+
const binds = (local: string) => {
|
|
45
|
+
if (local === from.global) bindsGlobal = true;
|
|
46
|
+
};
|
|
47
|
+
for (const {element: statement} of scope.statements) {
|
|
48
|
+
if (statement.kind !== JS.Kind.Import) continue;
|
|
49
|
+
const clause = (statement as JS.Import).importClause;
|
|
50
|
+
if (!clause) continue;
|
|
51
|
+
const fromModule = moduleOf(statement as JS.Import) === from.module;
|
|
52
|
+
const local = clause.name?.element.simpleName;
|
|
53
|
+
if (local) binds(local);
|
|
54
|
+
if (local && fromModule) qualifiers.add(local);
|
|
55
|
+
if (local && fromModule && clause.typeOnly && !clause.namedBindings) typeOnlyDefault ??= local;
|
|
56
|
+
const bindings = clause.namedBindings;
|
|
57
|
+
if (bindings?.kind === JS.Kind.Alias) {
|
|
58
|
+
const alias = (bindings as JS.Alias).alias;
|
|
59
|
+
if (isIdentifier(alias)) {
|
|
60
|
+
binds(alias.simpleName);
|
|
61
|
+
if (fromModule) qualifiers.add(alias.simpleName);
|
|
62
|
+
}
|
|
63
|
+
} else if (bindings?.kind === JS.Kind.NamedImports) {
|
|
64
|
+
for (const {element: specifier} of (bindings as JS.NamedImports).elements.elements) {
|
|
65
|
+
if (specifier.kind !== JS.Kind.ImportSpecifier) continue;
|
|
66
|
+
const member = memberOf(specifier as JS.ImportSpecifier);
|
|
67
|
+
const localName = localOf(specifier as JS.ImportSpecifier);
|
|
68
|
+
if (!localName) continue;
|
|
69
|
+
binds(localName);
|
|
70
|
+
if (fromModule && member) {
|
|
71
|
+
named.set(localName, {member, typeOnly: clause.typeOnly || (specifier as JS.ImportSpecifier).importType.element});
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
imports = {named, qualifiers, bindsGlobal, typeOnlyDefault};
|
|
77
|
+
byModule.set(from.module, imports);
|
|
78
|
+
return imports;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Reuses an existing import instead of adding a second one.
|
|
83
|
+
* `import {type FC as F} from 'react'`, `'FC'` → `true`
|
|
84
|
+
*/
|
|
85
|
+
export function importsMember(scope: ImportScope, from: Module, member: string): boolean {
|
|
86
|
+
return localNameOf(importsOf(scope, from), member) !== undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** `F` for `FC` with `import {FC as F}`. */
|
|
90
|
+
export function localNameOf(imports: ModuleImports, member: string): string | undefined {
|
|
91
|
+
return [...imports.named].find(([, imported]) => imported.member === member)?.[0];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The file, then each enclosing `declare module '…'` block, innermost first. */
|
|
95
|
+
export function importScopesOf(cursor: Cursor): ImportScope[] {
|
|
96
|
+
const scopes: ImportScope[] = [];
|
|
97
|
+
for (let c: Cursor | undefined = cursor; c; c = c.parent) {
|
|
98
|
+
const node = c.value as J | undefined;
|
|
99
|
+
if (node?.kind === JS.Kind.CompilationUnit) scopes.push(node as JS.CompilationUnit);
|
|
100
|
+
const body = node?.kind === JS.Kind.NamespaceDeclaration && (node as JS.NamespaceDeclaration).name.element.kind === J.Kind.Literal ?
|
|
101
|
+
(node as JS.NamespaceDeclaration).body : undefined;
|
|
102
|
+
if (body) scopes.push(body);
|
|
103
|
+
}
|
|
104
|
+
return scopes;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Whether `id` reads the binding `scope` declares, not one of the same name nearer to it. */
|
|
108
|
+
export function boundIn(cursor: Cursor, id: J.Identifier, scope: ImportScope): boolean {
|
|
109
|
+
const owner = resolve(cursor, id);
|
|
110
|
+
return owner !== undefined && (owner.id === scope.id ||
|
|
111
|
+
owner.kind === JS.Kind.NamespaceDeclaration && (owner as JS.NamespaceDeclaration).body?.id === scope.id);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** `export const FC = …` beside `import type {FC}`: a value read of `FC` reads the value, not the type. */
|
|
115
|
+
export function declaresTopLevelValue(scope: ImportScope, name: string): boolean {
|
|
116
|
+
return scope.statements.some(({element: s}) => {
|
|
117
|
+
const declares = (v: J.VariableDeclarations) => v.variables.some(n => bindingNames(n.element.name).some(b => b.name === name));
|
|
118
|
+
if (s.kind === J.Kind.VariableDeclarations) return declares(s as J.VariableDeclarations);
|
|
119
|
+
if (s.kind === JS.Kind.ScopedVariableDeclarations) {
|
|
120
|
+
return (s as JS.ScopedVariableDeclarations).variables.some(({element: v}) =>
|
|
121
|
+
v.kind === J.Kind.VariableDeclarations && declares(v as J.VariableDeclarations));
|
|
122
|
+
}
|
|
123
|
+
return s.kind === J.Kind.MethodDeclaration && (s as J.MethodDeclaration).name.simpleName === name;
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** `'react'` for `import … from 'react'` and `import x = require('react')`. */
|
|
128
|
+
export function moduleOf(i: JS.Import): string | undefined {
|
|
129
|
+
const required = i.initializer?.element as J.MethodInvocation | undefined;
|
|
130
|
+
const specifier = i.moduleSpecifier?.element ??
|
|
131
|
+
(required?.kind === J.Kind.MethodInvocation && required.name.simpleName === 'require' && !required.select ?
|
|
132
|
+
required.arguments.elements[0]?.element : undefined);
|
|
133
|
+
return specifier?.kind === J.Kind.Literal ? (specifier as J.Literal).value as string : undefined;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The name an export is known by, written as an identifier or, since ES2022, a string literal.
|
|
138
|
+
* `FC` for `FC as F` and for `"FC" as F`
|
|
139
|
+
*/
|
|
140
|
+
export function exportName(name: J): string | undefined {
|
|
141
|
+
if (isIdentifier(name)) return name.simpleName;
|
|
142
|
+
return name.kind === J.Kind.Literal && typeof (name as J.Literal).value === 'string' ? (name as J.Literal).value as string : undefined;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** `FC` for `import {FC}` and `import {FC as F}`. */
|
|
146
|
+
export function memberOf(specifier: JS.ImportSpecifier): string | undefined {
|
|
147
|
+
const s = specifier.specifier;
|
|
148
|
+
return s.kind === JS.Kind.Alias ? exportName((s as JS.Alias).propertyName.element) : exportName(s);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function localOf(specifier: JS.ImportSpecifier): string | undefined {
|
|
152
|
+
const s = specifier.specifier;
|
|
153
|
+
const local = s.kind === JS.Kind.Alias ? (s as JS.Alias).alias : s;
|
|
154
|
+
return isIdentifier(local) ? local.simpleName : undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Drops a migrated member's import once nothing uses it, keeping the namespace import that classic JSX needs.
|
|
159
|
+
* `import {FC, VFC} from 'react'` with `VFC` unused → `import {FC} from 'react'`
|
|
160
|
+
* `import * as React from 'react'` used only by JSX → kept
|
|
161
|
+
*/
|
|
162
|
+
export function dropImport(visitor: JavaScriptVisitor<any>, from: Module, member: string): void {
|
|
163
|
+
if (!visitor.afterVisit.some(v => v instanceof DropImport && v.module === from.module && v.member === member)) {
|
|
164
|
+
visitor.afterVisit.push(new DropImport(from.module, member));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
class DropImport<P> extends JavaScriptVisitor<P> {
|
|
169
|
+
constructor(readonly module: string, readonly member: string) {
|
|
170
|
+
super();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
override async visitJsCompilationUnit(cu: JS.CompilationUnit, p: P): Promise<J | undefined> {
|
|
174
|
+
const hidden = await this.withSameSpelledValuesHidden(cu);
|
|
175
|
+
const removedHidden = await this.removeKeepingNamespaces(hidden, p);
|
|
176
|
+
if (!removedHidden || removedHidden === hidden) return cu;
|
|
177
|
+
const removed = hidden === cu ? removedHidden : withStatementsRestored(cu, removedHidden);
|
|
178
|
+
const kept = withClosingLayoutKept(cu, removed);
|
|
179
|
+
return isModule(cu) && !isModule(kept) ? await withModuleMarker(kept) : kept;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private async withSameSpelledValuesHidden(cu: JS.CompilationUnit): Promise<JS.CompilationUnit> {
|
|
183
|
+
const locals = [...importsOf(cu, {module: this.module}).named]
|
|
184
|
+
.filter(([local, i]) => i.member === this.member && i.typeOnly && declaresTopLevelValue(cu, local))
|
|
185
|
+
.map(([local]) => local);
|
|
186
|
+
if (locals.length === 0) return cu;
|
|
187
|
+
const from = {module: this.module};
|
|
188
|
+
return await new class extends JavaScriptVisitor<void> {
|
|
189
|
+
override async visitImportDeclaration(i: JS.Import): Promise<J | undefined> {
|
|
190
|
+
return i;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
override async visitIdentifier(identifier: J.Identifier, p: void): Promise<J | undefined> {
|
|
194
|
+
const id = await super.visitIdentifier(identifier, p) as J.Identifier;
|
|
195
|
+
return locals.includes(id.simpleName) && !typeReferenceOf(this.cursor, id, from) ?
|
|
196
|
+
{...id, simpleName: `__value_${id.simpleName}`} as J.Identifier : id;
|
|
197
|
+
}
|
|
198
|
+
}().visit<JS.CompilationUnit>(cu, undefined) ?? cu;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private async removeKeepingNamespaces(cu: JS.CompilationUnit, p: P): Promise<JS.CompilationUnit | undefined> {
|
|
202
|
+
const namespaces = new Map(cu.statements.filter(s => this.isNamespaceImport(s.element)).map(s => [s.element.id, s]));
|
|
203
|
+
const remove = new RemoveImport<P>(this.module, this.member);
|
|
204
|
+
if (namespaces.size === 0) return remove.visit<JS.CompilationUnit>(cu, p);
|
|
205
|
+
const standIns = cu.statements.map(s => namespaces.has(s.element.id) ?
|
|
206
|
+
{...s, element: {kind: J.Kind.Empty, id: s.element.id, prefix: s.element.prefix, markers: s.element.markers} as J} : s);
|
|
207
|
+
const standing = {...cu, statements: standIns};
|
|
208
|
+
const removed = await remove.visit<JS.CompilationUnit>(standing, p);
|
|
209
|
+
if (!removed || removed === standing) return cu;
|
|
210
|
+
const statements = removed.statements.map(s => {
|
|
211
|
+
const namespace = namespaces.get(s.element.id);
|
|
212
|
+
if (!namespace) return s;
|
|
213
|
+
return s.element.prefix === namespace.element.prefix ? namespace :
|
|
214
|
+
{...namespace, element: {...namespace.element, prefix: s.element.prefix}};
|
|
215
|
+
});
|
|
216
|
+
return {...removed, statements} as JS.CompilationUnit;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private isNamespaceImport(statement: J): boolean {
|
|
220
|
+
return statement.kind === JS.Kind.Import && moduleOf(statement as JS.Import) === this.module &&
|
|
221
|
+
(statement as JS.Import).importClause?.namedBindings?.kind === JS.Kind.Alias;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function withStatementsRestored(original: JS.CompilationUnit, edited: JS.CompilationUnit): JS.CompilationUnit {
|
|
226
|
+
const originals = new Map(original.statements.map(s => [s.element.id, s.element]));
|
|
227
|
+
return {
|
|
228
|
+
...edited,
|
|
229
|
+
statements: edited.statements.map(s => {
|
|
230
|
+
const was = originals.get(s.element.id);
|
|
231
|
+
return !was || s.element.kind === JS.Kind.Import ? s : {...s, element: {...was, prefix: s.element.prefix}};
|
|
232
|
+
})
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function isModule(cu: JS.CompilationUnit): boolean {
|
|
237
|
+
return cu.statements.some(({element: s}) =>
|
|
238
|
+
s.kind === JS.Kind.Import || s.kind === JS.Kind.ExportDeclaration || s.kind === JS.Kind.ExportAssignment ||
|
|
239
|
+
((s as {modifiers?: J.Modifier[]}).modifiers ?? []).some(m => m.keyword === 'export'));
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const parser = new JavaScriptParser();
|
|
243
|
+
|
|
244
|
+
async function withModuleMarker(cu: JS.CompilationUnit): Promise<JS.CompilationUnit> {
|
|
245
|
+
const parsed = await parser.parseOnly({text: 'export {};', sourcePath: 'module-marker.ts'}) as JS.CompilationUnit;
|
|
246
|
+
const marker = parsed.statements[0];
|
|
247
|
+
const placed = {...marker, element: {...marker.element, id: randomId(), prefix: {...marker.element.prefix, whitespace: cu.statements.length ? '\n\n' : ''}}};
|
|
248
|
+
return {...cu, statements: [...cu.statements, placed]};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function withClosingLayoutKept(before: JS.CompilationUnit, after: JS.CompilationUnit): JS.CompilationUnit {
|
|
252
|
+
const originals = new Map(before.statements.map(s => [s.element.id, s.element]));
|
|
253
|
+
const statements = after.statements.map(s => {
|
|
254
|
+
const original = originals.get(s.element.id);
|
|
255
|
+
if (s.element.kind !== JS.Kind.Import || !original || original === s.element) return s;
|
|
256
|
+
const kept = closingLayoutKept(original as JS.Import, s.element as JS.Import);
|
|
257
|
+
return kept === s.element ? s : {...s, element: kept};
|
|
258
|
+
});
|
|
259
|
+
return statements.every((s, i) => s === after.statements[i]) ? after : {...after, statements};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function closingLayoutKept(original: JS.Import, imported: JS.Import): JS.Import {
|
|
263
|
+
const was = namedImportsOf(original)?.elements.elements;
|
|
264
|
+
const named = namedImportsOf(imported);
|
|
265
|
+
const now = named?.elements.elements;
|
|
266
|
+
if (!was || !named || !now || now.length === 0 || now.length >= was.length) return imported;
|
|
267
|
+
const lastWas = was[was.length - 1], lastNow = now[now.length - 1];
|
|
268
|
+
if (lastNow.element.id === lastWas.element.id) return imported;
|
|
269
|
+
const last = {...lastNow, after: lastWas.after, markers: lastWas.markers};
|
|
270
|
+
return {
|
|
271
|
+
...imported,
|
|
272
|
+
importClause: {
|
|
273
|
+
...imported.importClause!,
|
|
274
|
+
namedBindings: {...named, elements: {...named.elements, elements: [...now.slice(0, -1), last]}} as JS.NamedImports
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function namedImportsOf(i: JS.Import): JS.NamedImports | undefined {
|
|
280
|
+
const bindings = i.importClause?.namedBindings;
|
|
281
|
+
return bindings?.kind === JS.Kind.NamedImports ? bindings as JS.NamedImports : undefined;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* `declare module '…' {}` blocks hold their own imports, which the file-level `maybeBind` and `RemoveImport` don't reach.
|
|
286
|
+
* Queues adding `member` to, or dropping it from, the block's import of `from`, once the visit is done.
|
|
287
|
+
*/
|
|
288
|
+
export function editBlockImports(visitor: JavaScriptVisitor<any>, block: J.Block, from: Module, edit: { add?: string, drop?: string }): void {
|
|
289
|
+
let edits = visitor.afterVisit.find(v => v instanceof EditBlockImports && v.blockId === block.id && v.module === from.module) as
|
|
290
|
+
EditBlockImports<any> | undefined;
|
|
291
|
+
if (!edits) visitor.afterVisit.push(edits = new EditBlockImports(block.id, from.module));
|
|
292
|
+
if (edit.add) edits.add.add(edit.add);
|
|
293
|
+
if (edit.drop) edits.drop.add(edit.drop);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
class EditBlockImports<P> extends JavaScriptVisitor<P> {
|
|
297
|
+
readonly add = new Set<string>();
|
|
298
|
+
readonly drop = new Set<string>();
|
|
299
|
+
|
|
300
|
+
constructor(readonly blockId: string, readonly module: string) {
|
|
301
|
+
super();
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
override async visitBlock(block: J.Block, p: P): Promise<J | undefined> {
|
|
305
|
+
const visited = await super.visitBlock(block, p) as J.Block;
|
|
306
|
+
return visited.id === this.blockId ? this.edited(visited) : visited;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
private edited(block: J.Block): J.Block {
|
|
310
|
+
const from = {module: this.module};
|
|
311
|
+
const imports = importsOf(block, from);
|
|
312
|
+
const used = namesUsedWithin(block.statements.filter(s => s.element.kind !== JS.Kind.Import));
|
|
313
|
+
const drop = new Set([...this.drop].filter(member => {
|
|
314
|
+
const local = localNameOf(imports, member);
|
|
315
|
+
return local !== undefined && !used.has(local);
|
|
316
|
+
}));
|
|
317
|
+
const pending = [...this.add].filter(member => !localNameOf(imports, member));
|
|
318
|
+
let appended = false;
|
|
319
|
+
const statements = block.statements.flatMap(statement => {
|
|
320
|
+
const i = statement.element as JS.Import;
|
|
321
|
+
const named = i.kind === JS.Kind.Import && moduleOf(i) === this.module ? namedImportsOf(i) : undefined;
|
|
322
|
+
if (!named) return [statement];
|
|
323
|
+
let elements = named.elements.elements.flatMap(e => {
|
|
324
|
+
const member = memberOf(e.element as JS.ImportSpecifier);
|
|
325
|
+
if (member === undefined || !drop.has(member)) return [e];
|
|
326
|
+
const next = pending.shift();
|
|
327
|
+
return next === undefined ? [] : [{...e, element: specifierFor(e.element as JS.ImportSpecifier, next)}];
|
|
328
|
+
});
|
|
329
|
+
if (!appended && pending.length && elements.length) {
|
|
330
|
+
appended = true;
|
|
331
|
+
const last = elements[elements.length - 1];
|
|
332
|
+
elements = [...elements.slice(0, -1), {...last, after: emptySpace},
|
|
333
|
+
...pending.splice(0).map((member, k, added) => ({
|
|
334
|
+
...last, element: specifierFor(last.element as JS.ImportSpecifier, member, singleSpace),
|
|
335
|
+
after: k === added.length - 1 ? last.after : emptySpace
|
|
336
|
+
}))];
|
|
337
|
+
}
|
|
338
|
+
if (elements.length === 0 && !i.importClause?.name) return [];
|
|
339
|
+
return [{...statement, element: {...i, importClause: {...i.importClause!, namedBindings: {...named, elements: {...named.elements, elements}}}}}];
|
|
340
|
+
});
|
|
341
|
+
return {...block, statements};
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function specifierFor(like: JS.ImportSpecifier, member: string, prefix = like.prefix): JS.ImportSpecifier {
|
|
346
|
+
const s = like.specifier;
|
|
347
|
+
const name: J = s.kind === JS.Kind.Alias ? {...(s as JS.Alias).propertyName.element, prefix: s.prefix} : s;
|
|
348
|
+
const identifier: J.Identifier = isIdentifier(name) ? name :
|
|
349
|
+
{kind: J.Kind.Identifier, id: randomId(), prefix: name.prefix, markers: name.markers, annotations: [], simpleName: member};
|
|
350
|
+
return {...like, id: randomId(), prefix, specifier: {...identifier, id: randomId(), simpleName: member, type: undefined}};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Keeps a moved type's import type-only, as core's rebind moves `import {Validator} from 'react'` to a value import.
|
|
355
|
+
* Only imports of `members` from `to` that the file did not have before the visit change.
|
|
356
|
+
* `import {Validator} from 'prop-types'` → `import type {Validator} from 'prop-types'`;
|
|
357
|
+
* beside `checkPropTypes` → `import {checkPropTypes, type Validator} from 'prop-types'`
|
|
358
|
+
*/
|
|
359
|
+
export function keepMovedTypesTypeOnly(visitor: JavaScriptVisitor<any>, cu: JS.CompilationUnit, to: Module, members: readonly string[]): void {
|
|
360
|
+
const existing = new Set<string>();
|
|
361
|
+
for (const {element: statement} of cu.statements) {
|
|
362
|
+
const named = statement.kind === JS.Kind.Import && moduleOf(statement as JS.Import) === to.module ? namedImportsOf(statement as JS.Import) : undefined;
|
|
363
|
+
named?.elements.elements.forEach(e => existing.add(e.element.id));
|
|
364
|
+
}
|
|
365
|
+
visitor.afterVisit.push(new TypeOnlyImports(to.module, new Set(members), existing));
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
class TypeOnlyImports<P> extends JavaScriptVisitor<P> {
|
|
369
|
+
constructor(readonly module: string, readonly members: ReadonlySet<string>, readonly existing: ReadonlySet<string>) {
|
|
370
|
+
super();
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
|
|
374
|
+
const statements = cu.statements.map(s => s.element.kind === JS.Kind.Import && moduleOf(s.element as JS.Import) === this.module ?
|
|
375
|
+
{...s, element: this.typeOnly(s.element as JS.Import)} : s);
|
|
376
|
+
return statements.every((s, i) => s.element === cu.statements[i].element) ? cu : {...cu, statements} as JS.CompilationUnit;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
private typeOnly(i: JS.Import): JS.Import {
|
|
380
|
+
const clause = i.importClause;
|
|
381
|
+
const named = namedImportsOf(i);
|
|
382
|
+
if (!clause || clause.typeOnly || !named) return i;
|
|
383
|
+
const moved = (s: J) => s.kind === JS.Kind.ImportSpecifier && !this.existing.has(s.id) &&
|
|
384
|
+
!(s as JS.ImportSpecifier).importType.element && this.members.has(memberOf(s as JS.ImportSpecifier) ?? '');
|
|
385
|
+
const elements = named.elements.elements;
|
|
386
|
+
if (!elements.some(e => moved(e.element))) return i;
|
|
387
|
+
if (!clause.name && elements.every(e => moved(e.element))) {
|
|
388
|
+
const bindings = named.prefix.whitespace ? named : {...named, prefix: singleSpace};
|
|
389
|
+
return {...i, importClause: {...clause, typeOnly: true, namedBindings: bindings}};
|
|
390
|
+
}
|
|
391
|
+
const inline = (s: JS.ImportSpecifier): JS.ImportSpecifier =>
|
|
392
|
+
({...s, importType: {...s.importType, element: true}, specifier: {...s.specifier, prefix: singleSpace}});
|
|
393
|
+
const marked = elements.map(e => moved(e.element) ? {...e, element: inline(e.element as JS.ImportSpecifier)} : e);
|
|
394
|
+
return {...i, importClause: {...clause, namedBindings: {...named, elements: {...named.elements, elements: marked}} as JS.NamedImports}};
|
|
395
|
+
}
|
|
396
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import {and, check, ExecutionContext, not, Tree, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {hasSourcePath, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
|
|
4
|
+
export type {Module} from "./module";
|
|
5
|
+
export {react} from "./module";
|
|
6
|
+
export {dropImport, importsMember, importsOf, isModule, keepMovedTypesTypeOnly} from "./imports";
|
|
7
|
+
export type {TypeReference} from "./reference";
|
|
8
|
+
export {typeReferenceOf, importTypeReferenceOf, inTypePosition, globalTypeName} from "./reference";
|
|
9
|
+
export {typeName, renamingTypes} from "./rename";
|
|
10
|
+
export {replaceType, flattenUnion, unionWith} from "./replace";
|
|
11
|
+
export {markReExport} from "./re-export";
|
|
12
|
+
|
|
13
|
+
const TYPESCRIPT_SOURCES = "**/*.ts;**/*.tsx;**/*.mts;**/*.cts";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Types only appear in TypeScript, and vendored or generated code isn't ours to migrate.
|
|
17
|
+
* `src/App.tsx` → visited; `src/App.jsx`, `dist/index.d.ts` → skipped
|
|
18
|
+
*/
|
|
19
|
+
export function onTypeScriptSources<T extends Tree>(visitor: TreeVisitor<T, ExecutionContext>): Promise<TreeVisitor<T, ExecutionContext>> {
|
|
20
|
+
return check(and(hasSourcePath(TYPESCRIPT_SOURCES), not(isVendoredOrBundled())), visitor);
|
|
21
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A module whose exported types a recipe migrates, and the global its UMD build declares.
|
|
3
|
+
* `{module: 'react', global: 'React'}` also finds `React.FC` in a file that imports nothing.
|
|
4
|
+
*/
|
|
5
|
+
export interface Module {
|
|
6
|
+
readonly module: string;
|
|
7
|
+
readonly global?: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const react: Module = {module: 'react', global: 'React'};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import {Cursor, foundSearchResult} from "@openrewrite/rewrite";
|
|
2
|
+
import {JS} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {Module} from "./module";
|
|
4
|
+
import {reExportedTypeOf} from "./reference";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Marks a re-export of a type no name replaces for a person, as no type expression can be re-exported.
|
|
8
|
+
* `export type {ReactText}`, `'ReactText'` → marked. A renamed type's re-exports move with core's `maybeRebind`.
|
|
9
|
+
*/
|
|
10
|
+
export function markReExport(cursor: Cursor, specifier: JS.ExportSpecifier, from: Module, removed: string): JS.ExportSpecifier {
|
|
11
|
+
return reExportedTypeOf(cursor, specifier, from)?.ref.member === removed
|
|
12
|
+
? foundSearchResult(specifier, `${removed} was removed from @types/${from.module}: re-export its replacement by hand`)
|
|
13
|
+
: specifier;
|
|
14
|
+
}
|