@openrewrite/recipes-react 0.16.0 → 0.17.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.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/migration/cra-to-vite/add-vite-config.d.ts +7 -0
- package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/add-vite-config.js +58 -1
- package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -1
- package/dist/migration/cra-to-vite/cra-file-gate.d.ts +3 -0
- package/dist/migration/cra-to-vite/cra-file-gate.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-file-gate.js +10 -0
- package/dist/migration/cra-to-vite/cra-file-gate.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-runtime.d.ts +2 -0
- package/dist/migration/cra-to-vite/cra-runtime.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-runtime.js +24 -0
- package/dist/migration/cra-to-vite/cra-runtime.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-script.d.ts +8 -0
- package/dist/migration/cra-to-vite/cra-script.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-script.js +82 -0
- package/dist/migration/cra-to-vite/cra-script.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-to-vite.d.ts +2 -1
- package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/cra-to-vite.js +23 -16
- package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -1
- package/dist/migration/cra-to-vite/cra-typecheck.d.ts +4 -0
- package/dist/migration/cra-to-vite/cra-typecheck.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-typecheck.js +35 -0
- package/dist/migration/cra-to-vite/cra-typecheck.js.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js +2 -1
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
- package/dist/migration/cra-to-vite/index.d.ts +8 -2
- package/dist/migration/cra-to-vite/index.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/index.js +17 -2
- package/dist/migration/cra-to-vite/index.js.map +1 -1
- package/dist/migration/cra-to-vite/migrate-cra-package.d.ts +17 -0
- package/dist/migration/cra-to-vite/migrate-cra-package.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-package.js +181 -0
- package/dist/migration/cra-to-vite/migrate-cra-package.js.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts +9 -0
- package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js +66 -0
- package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts +49 -0
- package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js +506 -0
- package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js.map +1 -0
- package/dist/migration/cra-to-vite/move-public-index-html.d.ts +2 -0
- package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/move-public-index-html.js +12 -7
- package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -1
- package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts +30 -0
- package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/plan-cra-to-vite.js +428 -0
- package/dist/migration/cra-to-vite/plan-cra-to-vite.js.map +1 -0
- package/dist/migration/cra-to-vite/prepare-cra-package.d.ts +15 -0
- package/dist/migration/cra-to-vite/prepare-cra-package.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/prepare-cra-package.js +100 -0
- package/dist/migration/cra-to-vite/prepare-cra-package.js.map +1 -0
- package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts +12 -0
- package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/remove-cra-configuration.js +85 -0
- package/dist/migration/cra-to-vite/remove-cra-configuration.js.map +1 -0
- package/dist/migration/cra-to-vite/rename-jsx-files.d.ts +20 -0
- package/dist/migration/cra-to-vite/rename-jsx-files.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/rename-jsx-files.js +220 -0
- package/dist/migration/cra-to-vite/rename-jsx-files.js.map +1 -0
- package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/rename-process-env-react-app.js +6 -3
- package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -1
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +1 -1
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -1
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +11 -4
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +47 -30
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -1
- package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts +3 -0
- package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/resolved-cra-dependency.js +42 -0
- package/dist/migration/cra-to-vite/resolved-cra-dependency.js.map +1 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +13 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/scan-cra-projects.js +52 -4
- package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -1
- package/dist/migration/cra-to-vite/shared.d.ts +1 -1
- package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/shared.js +19 -4
- package/dist/migration/cra-to-vite/shared.js.map +1 -1
- package/dist/migration/cra-to-vite/svg-component.d.ts +5 -0
- package/dist/migration/cra-to-vite/svg-component.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/svg-component.js +60 -0
- package/dist/migration/cra-to-vite/svg-component.js.map +1 -0
- package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/update-react-app-env-types.js +8 -2
- package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +3 -2
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +18 -14
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -1
- package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
- package/dist/react18/replace-reactdom-render.js +16 -8
- package/dist/react18/replace-reactdom-render.js.map +1 -1
- package/dist/testing/enzyme-constant-strings.d.ts +12 -0
- package/dist/testing/enzyme-constant-strings.d.ts.map +1 -0
- package/dist/testing/enzyme-constant-strings.js +101 -0
- package/dist/testing/enzyme-constant-strings.js.map +1 -0
- package/dist/testing/enzyme-host-components.d.ts.map +1 -1
- package/dist/testing/enzyme-host-components.js +5 -2
- package/dist/testing/enzyme-host-components.js.map +1 -1
- package/dist/testing/enzyme-portals.d.ts +38 -0
- package/dist/testing/enzyme-portals.d.ts.map +1 -0
- package/dist/testing/enzyme-portals.js +226 -0
- package/dist/testing/enzyme-portals.js.map +1 -0
- package/dist/testing/enzyme-selector-names.d.ts +9 -0
- package/dist/testing/enzyme-selector-names.d.ts.map +1 -0
- package/dist/testing/enzyme-selector-names.js +50 -0
- package/dist/testing/enzyme-selector-names.js.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts +71 -8
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +321 -34
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +27 -4
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +12 -6
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +140 -16
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/util/java-recipe-proxy.d.ts +16 -0
- package/dist/util/java-recipe-proxy.d.ts.map +1 -0
- package/dist/util/java-recipe-proxy.js +85 -0
- package/dist/util/java-recipe-proxy.js.map +1 -0
- package/dist/util/module-imports.d.ts +1 -0
- package/dist/util/module-imports.d.ts.map +1 -1
- package/dist/util/module-imports.js +5 -1
- package/dist/util/module-imports.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +2 -1
- package/src/migration/cra-to-vite/add-vite-config.ts +53 -1
- package/src/migration/cra-to-vite/cra-file-gate.ts +8 -0
- package/src/migration/cra-to-vite/cra-runtime.ts +16 -0
- package/src/migration/cra-to-vite/cra-script.ts +61 -0
- package/src/migration/cra-to-vite/cra-to-vite.ts +25 -36
- package/src/migration/cra-to-vite/cra-typecheck.ts +33 -0
- package/src/migration/cra-to-vite/find-cra-config-blockers.ts +2 -1
- package/src/migration/cra-to-vite/index.ts +10 -2
- package/src/migration/cra-to-vite/migrate-cra-package.ts +127 -0
- package/src/migration/cra-to-vite/migrate-cra-svg-imports.ts +41 -0
- package/src/migration/cra-to-vite/migrate-cra-tests-to-vitest.ts +376 -0
- package/src/migration/cra-to-vite/move-public-index-html.ts +12 -7
- package/src/migration/cra-to-vite/plan-cra-to-vite.ts +283 -0
- package/src/migration/cra-to-vite/prepare-cra-package.ts +86 -0
- package/src/migration/cra-to-vite/remove-cra-configuration.ts +64 -0
- package/src/migration/cra-to-vite/rename-jsx-files.ts +155 -0
- package/src/migration/cra-to-vite/rename-process-env-react-app.ts +6 -3
- package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +1 -1
- package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +52 -33
- package/src/migration/cra-to-vite/resolved-cra-dependency.ts +41 -0
- package/src/migration/cra-to-vite/scan-cra-projects.ts +57 -6
- package/src/migration/cra-to-vite/shared.ts +20 -10
- package/src/migration/cra-to-vite/svg-component.ts +39 -0
- package/src/migration/cra-to-vite/update-react-app-env-types.ts +11 -4
- package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +22 -28
- package/src/react18/replace-reactdom-render.ts +17 -8
- package/src/testing/enzyme-constant-strings.ts +95 -0
- package/src/testing/enzyme-host-components.ts +6 -2
- package/src/testing/enzyme-portals.ts +279 -0
- package/src/testing/enzyme-selector-names.ts +59 -0
- package/src/testing/enzyme-to-react-testing-library.ts +425 -50
- package/src/testing/enzyme-usage.ts +29 -4
- package/src/testing/enzyme-wrapper-scope.ts +181 -30
- package/src/util/java-recipe-proxy.ts +81 -0
- package/src/util/module-imports.ts +6 -1
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import {check, ExecutionContext, not, Tree, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {isVendoredOrBundled, JavaScriptVisitor, JS, JSX} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {Expression, isIdentifier, isLiteral, J} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
|
|
5
|
+
import {dirName, nearestRoot} from "./shared";
|
|
6
|
+
import {craToViteBlockersTable} from "./cra-blockers-table";
|
|
7
|
+
import {posix} from "node:path";
|
|
8
|
+
import {craFilesOnly} from './cra-file-gate';
|
|
9
|
+
|
|
10
|
+
class JsxProjects extends CraProjects {
|
|
11
|
+
readonly jsxPaths = new Set<string>();
|
|
12
|
+
readonly reportedCollisions = new Set<string>();
|
|
13
|
+
renamePlan?: {renames: Map<string, string>, collisions: Map<string, string>};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* `src/App.js` containing `<App />` becomes `src/App.jsx`; `import './App.js'` becomes `import './App.jsx'`.
|
|
18
|
+
* Extensionless imports keep resolving without an edit. Only parsed JSX in eligible CRA client sources triggers
|
|
19
|
+
* a rename; JSX text in comments or strings does not. Imports are updated only within the owning package.
|
|
20
|
+
*
|
|
21
|
+
* @see https://vite.dev/guide/features.html#jsx
|
|
22
|
+
*/
|
|
23
|
+
export class RenameJsxFiles extends CraScanningRecipe {
|
|
24
|
+
readonly name = "org.openrewrite.react.cra-to-vite.rename-jsx-files";
|
|
25
|
+
readonly displayName = "Rename JavaScript files containing JSX to `.jsx`";
|
|
26
|
+
readonly description = "Renames `.js` client files containing JSX in Create React App packages to `.jsx` and updates explicit relative `.js` imports, re-exports and dynamic imports within the same package. Extensionless imports and JSX-free files stay unchanged. Destination path collisions are recorded for manual resolution.";
|
|
27
|
+
|
|
28
|
+
override initialValue(): JsxProjects {
|
|
29
|
+
return new JsxProjects();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
override async scanner(acc: JsxProjects): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
33
|
+
const projects = await super.scanner(acc);
|
|
34
|
+
const jsx = await check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
35
|
+
private path = "";
|
|
36
|
+
|
|
37
|
+
override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
38
|
+
if (!cu.sourcePath.endsWith(".js")) return cu;
|
|
39
|
+
this.path = cu.sourcePath;
|
|
40
|
+
return super.visitJsCompilationUnit(cu, ctx);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
override async visitJsxTag(tag: JSX.Tag): Promise<J | undefined> {
|
|
44
|
+
acc.jsxPaths.add(this.path);
|
|
45
|
+
return tag;
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
return craFilesOnly(new class extends TreeVisitor<Tree, ExecutionContext> {
|
|
49
|
+
override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext): Promise<R | undefined> {
|
|
50
|
+
await projects.visit(tree, ctx);
|
|
51
|
+
if (tree.kind === JS.Kind.CompilationUnit) await jsx.visit(tree, ctx);
|
|
52
|
+
return tree as R;
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
override async editorWithData(acc: JsxProjects): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
58
|
+
// The scheduler constructs an editor for each source file; calculate the repository-wide plan once.
|
|
59
|
+
if (!acc.renamePlan) {
|
|
60
|
+
const renames = new Map<string, string>();
|
|
61
|
+
const collisions = new Map<string, string>();
|
|
62
|
+
const existing = new Map<string, string>();
|
|
63
|
+
for (const path of acc.paths) {
|
|
64
|
+
existing.set(path.toLowerCase(), path);
|
|
65
|
+
// A directory at the destination blocks a file move just as an existing file does.
|
|
66
|
+
for (let dir = dirName(path); dir; dir = dirName(dir)) existing.set(dir.toLowerCase(), dir);
|
|
67
|
+
}
|
|
68
|
+
for (const path of acc.jsxPaths) {
|
|
69
|
+
if (!acc.isViteClientSource(path)) continue;
|
|
70
|
+
const target = path + "x";
|
|
71
|
+
const collision = existing.get(target.toLowerCase());
|
|
72
|
+
if (collision) collisions.set(path, collision);
|
|
73
|
+
else renames.set(path, target);
|
|
74
|
+
}
|
|
75
|
+
acc.renamePlan = {renames, collisions};
|
|
76
|
+
}
|
|
77
|
+
const {renames, collisions} = acc.renamePlan;
|
|
78
|
+
const table = craToViteBlockersTable();
|
|
79
|
+
return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
80
|
+
private path = "";
|
|
81
|
+
|
|
82
|
+
override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<JS.CompilationUnit | undefined> {
|
|
83
|
+
if (!acc.isViteClientSource(cu.sourcePath)) return cu;
|
|
84
|
+
this.path = cu.sourcePath;
|
|
85
|
+
const collision = collisions.get(this.path);
|
|
86
|
+
if (collision && !acc.reportedCollisions.has(this.path)) {
|
|
87
|
+
acc.reportedCollisions.add(this.path);
|
|
88
|
+
table.insertRow(ctx, {
|
|
89
|
+
filePath: this.path, category: "jsx-path-collision", detail: `${collision} already exists`,
|
|
90
|
+
nextStep: `Resolve the destination path collision before renaming ${this.path} to ${this.path}x.`
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
const visited = await super.visitJsCompilationUnit(cu, ctx) as JS.CompilationUnit;
|
|
94
|
+
const target = renames.get(this.path);
|
|
95
|
+
return target ? {...visited, sourcePath: target} : visited;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
override async visitImportDeclaration(node: JS.Import, ctx: ExecutionContext): Promise<JS.Import | undefined> {
|
|
99
|
+
const visited = await super.visitImportDeclaration(node, ctx) as JS.Import;
|
|
100
|
+
const module = visited.moduleSpecifier;
|
|
101
|
+
if (!module) return visited;
|
|
102
|
+
const renamed = this.renameModule(module.element);
|
|
103
|
+
return renamed === module.element ? visited : {...visited, moduleSpecifier: {...module, element: renamed}};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
override async visitExportDeclaration(node: JS.ExportDeclaration, ctx: ExecutionContext): Promise<JS.ExportDeclaration | undefined> {
|
|
107
|
+
const visited = await super.visitExportDeclaration(node, ctx) as JS.ExportDeclaration;
|
|
108
|
+
const module = visited.moduleSpecifier;
|
|
109
|
+
if (!module) return visited;
|
|
110
|
+
const renamed = this.renameModule(module.element);
|
|
111
|
+
return renamed === module.element ? visited : {...visited, moduleSpecifier: {...module, element: renamed}};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
override async visitFunctionCall(node: JS.FunctionCall, ctx: ExecutionContext): Promise<JS.FunctionCall | undefined> {
|
|
115
|
+
const visited = await super.visitFunctionCall(node, ctx) as JS.FunctionCall;
|
|
116
|
+
const fn = visited.function?.element;
|
|
117
|
+
if (!fn || !isIdentifier(fn) || fn.simpleName !== "import") return visited;
|
|
118
|
+
const first = visited.arguments.elements[0];
|
|
119
|
+
if (!first) return visited;
|
|
120
|
+
const renamed = this.renameModule(first.element);
|
|
121
|
+
if (renamed === first.element) return visited;
|
|
122
|
+
return {...visited, arguments: {...visited.arguments, elements: [
|
|
123
|
+
{...first, element: renamed}, ...visited.arguments.elements.slice(1)
|
|
124
|
+
]}};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
override async visitMethodInvocation(node: J.MethodInvocation, ctx: ExecutionContext): Promise<J.MethodInvocation | undefined> {
|
|
128
|
+
const visited = await super.visitMethodInvocation(node, ctx) as J.MethodInvocation;
|
|
129
|
+
if (visited.select || visited.name.simpleName !== 'require') return visited;
|
|
130
|
+
const first = visited.arguments.elements[0];
|
|
131
|
+
if (!first) return visited;
|
|
132
|
+
const renamed = this.renameModule(first.element);
|
|
133
|
+
return renamed === first.element ? visited : {...visited, arguments: {...visited.arguments, elements: [
|
|
134
|
+
{...first, element: renamed}, ...visited.arguments.elements.slice(1)
|
|
135
|
+
]}};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private renameModule(expression: Expression): Expression {
|
|
139
|
+
if (!isLiteral(expression) || typeof expression.value !== "string") return expression;
|
|
140
|
+
const value = expression.value;
|
|
141
|
+
const suffix = value.search(/[?#]/);
|
|
142
|
+
const path = suffix < 0 ? value : value.slice(0, suffix);
|
|
143
|
+
if (!(path.startsWith("./") || path.startsWith("../") || path.startsWith('/')) || !path.endsWith(".js")) return expression;
|
|
144
|
+
const owner = nearestRoot(acc.packageDirs, this.path);
|
|
145
|
+
const resolved = posix.normalize(path.startsWith('/') ? posix.join(owner ?? '', path.slice(1)) : posix.join(dirName(this.path), path));
|
|
146
|
+
if (!renames.has(resolved) || nearestRoot(acc.packageDirs, this.path) !== nearestRoot(acc.packageDirs, resolved)) return expression;
|
|
147
|
+
const source = expression.valueSource;
|
|
148
|
+
if (!source) return expression;
|
|
149
|
+
const renamed = path + 'x' + (suffix < 0 ? '' : value.slice(suffix));
|
|
150
|
+
const rewritten = suffix < 0 ? source.slice(0, -1) + 'x' + source.slice(-1) : source.replace(/js(?=[?#])/, 'jsx');
|
|
151
|
+
return {...expression, value: renamed, valueSource: rewritten === source ? JSON.stringify(renamed) : rewritten} as J.Literal;
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
@@ -12,9 +12,9 @@ const NODE_SIDE_FILE = /^(setupProxy|craco\.config|config-overrides|webpack\.con
|
|
|
12
12
|
const recordedNames = new WeakMap<CraProjects, Set<string>>();
|
|
13
13
|
|
|
14
14
|
/** Parsed instead of built by hand so the nodes carry the type attribution and ids a parse gives them. */
|
|
15
|
-
async function importMetaEnv(prefix: J.Space): Promise<J
|
|
16
|
-
const cu = await new JavaScriptParser().parseOne({text: "
|
|
17
|
-
const expression = cu.statements[0].element as unknown as J
|
|
15
|
+
async function importMetaEnv(prefix: J.Space, text = "import.meta.env"): Promise<J> {
|
|
16
|
+
const cu = await new JavaScriptParser().parseOne({text: text + ";", sourcePath: "import-meta-env.ts"}) as JS.CompilationUnit;
|
|
17
|
+
const expression = cu.statements[0].element as unknown as J;
|
|
18
18
|
return {...expression, prefix};
|
|
19
19
|
}
|
|
20
20
|
|
|
@@ -67,6 +67,9 @@ export class RenameProcessEnvReactApp extends CraScanningRecipe {
|
|
|
67
67
|
override async visitFieldAccess(fieldAccess: J.FieldAccess, ctx: ExecutionContext): Promise<J | undefined> {
|
|
68
68
|
const visited = await super.visitFieldAccess(fieldAccess, ctx) as J.FieldAccess;
|
|
69
69
|
const name = visited.name.element.simpleName;
|
|
70
|
+
if (isProcessEnv(visited.target) && (name === "NODE_ENV" || name === "PUBLIC_URL")) {
|
|
71
|
+
return importMetaEnv(visited.prefix, name === "NODE_ENV" ? "import.meta.env.MODE" : "import.meta.env.BASE_URL.replace(/\\/$/, '')");
|
|
72
|
+
}
|
|
70
73
|
if (!name.startsWith(CRA_ENV_PREFIX) || name.length === CRA_ENV_PREFIX.length || !isProcessEnv(visited.target)) {
|
|
71
74
|
return visited;
|
|
72
75
|
}
|
|
@@ -5,7 +5,7 @@ import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
|
|
|
5
5
|
import {CRA_ENV_PREFIX, isEnvFile, VITE_ENV_PREFIX} from "./shared";
|
|
6
6
|
|
|
7
7
|
const ASSIGNMENT = new RegExp(`^(\\s*(?:export\\s+)?)${CRA_ENV_PREFIX}([A-Za-z0-9_]+)(\\s*=)`);
|
|
8
|
-
const EXPANSION =
|
|
8
|
+
const EXPANSION = /(?<!\\)(\$\{?)REACT_APP_([A-Za-z0-9_]+)/g;
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Renames `REACT_APP_*` variables to `VITE_*` in `.env` files, including `${REACT_APP_*}` expansions.
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import {ExecutionContext, Option,
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
} from "./shared";
|
|
1
|
+
import {ExecutionContext, Option, SourceFile} from "@openrewrite/rewrite";
|
|
2
|
+
import {JavaDependencyRecipe} from "../../util/java-recipe-proxy";
|
|
3
|
+
import {getMemberKeyName, Json, membersOf} from "@openrewrite/rewrite/json";
|
|
4
|
+
import {hasDependency, memberObject, runsOnVite, isPackageJson, rootObject, stringValue, VITE, VITE_PLUGIN_REACT} from "./shared";
|
|
6
5
|
|
|
7
6
|
/**
|
|
8
7
|
* Adds `vite` and `@vitejs/plugin-react` to `devDependencies` of a package that depends on `react-scripts`,
|
|
@@ -13,16 +12,15 @@ import {
|
|
|
13
12
|
* ```
|
|
14
13
|
*
|
|
15
14
|
* The default versions are a peer-consistent pair that both need Node 20.19 or later. `react-scripts` stays
|
|
16
|
-
* while a script such as `test` still runs it, because it provides Jest. The `eject` script
|
|
17
|
-
*
|
|
18
|
-
* `build` script still depends on `react-scripts` is left to the finders.
|
|
15
|
+
* while a script such as `test` still runs it, because it provides Jest. The `eject` script also retains the dependency until script migration removes it.
|
|
16
|
+
* Packages using `craco`, `react-app-rewired` or wrapped `start` or `build` scripts are left to the finders.
|
|
19
17
|
*
|
|
20
18
|
* @see https://react.dev/blog/2025/02/14/sunsetting-create-react-app#how-to-migrate-to-a-build-tool
|
|
21
19
|
*/
|
|
22
|
-
export class ReplaceReactScriptsDependency extends
|
|
20
|
+
export class ReplaceReactScriptsDependency extends JavaDependencyRecipe {
|
|
23
21
|
readonly name = "org.openrewrite.react.cra-to-vite.replace-react-scripts-dependency";
|
|
24
22
|
readonly displayName = "Replace `react-scripts` dependency with Vite";
|
|
25
|
-
readonly description = "Adds `vite` and `@vitejs/plugin-react` as dev dependencies
|
|
23
|
+
readonly description = "Adds `vite` and `@vitejs/plugin-react` together as dev dependencies and removes `react-scripts` or scoped forks only when no script still invokes them. Regenerates the lock natively; declined dependency edits leave the manifest and lock consistent. Wrapped CRA packages are left unchanged.";
|
|
26
24
|
|
|
27
25
|
@Option({
|
|
28
26
|
displayName: "Vite version",
|
|
@@ -40,32 +38,53 @@ export class ReplaceReactScriptsDependency extends Recipe {
|
|
|
40
38
|
})
|
|
41
39
|
pluginReactVersion?: string;
|
|
42
40
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
41
|
+
/** Package directories (with a trailing slash, or an empty string at root) accepted by the native engine. Known after generate. */
|
|
42
|
+
readonly landed = new Set<string>();
|
|
43
|
+
private readonly manifests: Json.Document[] = [];
|
|
44
|
+
|
|
45
|
+
constructor(options?: { viteVersion?: string; pluginReactVersion?: string; addSvgr?: boolean }) {
|
|
46
|
+
const {viteVersion = "^7.0.0", pluginReactVersion = "^5.2.0", addSvgr = false} = options ?? {};
|
|
47
|
+
super("org.openrewrite.react.migrate.ReplaceReactScriptsDependency", {viteVersion, pluginReactVersion, addSvgr}, true);
|
|
48
|
+
this.viteVersion = viteVersion;
|
|
49
|
+
this.pluginReactVersion = pluginReactVersion;
|
|
50
|
+
this.addSvgr = addSvgr;
|
|
47
51
|
}
|
|
48
52
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
53
|
+
@Option({displayName: "Add SVGR", description: "Also add `vite-plugin-svgr` when the caller migrates SVG ReactComponent imports in this package.", required: false})
|
|
54
|
+
addSvgr?: boolean;
|
|
55
|
+
|
|
56
|
+
override initialValue(): number {
|
|
57
|
+
this.landed.clear();
|
|
58
|
+
this.manifests.length = 0;
|
|
59
|
+
return super.initialValue();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
protected override scanned(manifest: SourceFile): boolean {
|
|
63
|
+
if (manifest.kind !== Json.Kind.Document || !isPackageJson(manifest.sourcePath)) return true;
|
|
64
|
+
const pkg = rootObject(manifest as Json.Document);
|
|
65
|
+
if (pkg && runsOnVite(pkg)) this.manifests.push(manifest as Json.Document);
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
56
68
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
69
|
+
override async generate(acc: number, ctx: ExecutionContext): Promise<SourceFile[]> {
|
|
70
|
+
const generated = await super.generate(acc, ctx);
|
|
71
|
+
const editor = await this.java.editorWithData(acc);
|
|
72
|
+
for (const manifest of this.manifests) {
|
|
73
|
+
const edited = await editor.visit<Json.Document>(manifest, ctx);
|
|
74
|
+
const pkg = edited && rootObject(edited);
|
|
75
|
+
const before = rootObject(manifest)!;
|
|
76
|
+
const scripts = memberObject(before, "scripts");
|
|
77
|
+
const keepCra = scripts && membersOf(scripts).some(member => stringValue(member.value)?.includes("react-scripts"));
|
|
78
|
+
const removed = keepCra || ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"].every(section => {
|
|
79
|
+
const deps = pkg && memberObject(pkg, section);
|
|
80
|
+
return !deps || membersOf(deps).every(member => !/^(?:@[^/]+\/)?react-scripts$/.test(getMemberKeyName(member) ?? ""));
|
|
81
|
+
});
|
|
82
|
+
// A warning-only result from a declined removal is not a landed dependency edit.
|
|
83
|
+
if (edited !== manifest && removed && pkg && hasDependency(pkg, VITE) && hasDependency(pkg, VITE_PLUGIN_REACT) &&
|
|
84
|
+
(!this.addSvgr || hasDependency(pkg, "vite-plugin-svgr"))) {
|
|
85
|
+
this.landed.add(manifest.sourcePath.slice(0, -"package.json".length));
|
|
68
86
|
}
|
|
69
|
-
}
|
|
87
|
+
}
|
|
88
|
+
return generated;
|
|
70
89
|
}
|
|
71
90
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import {isBuiltin} from 'node:module';
|
|
2
|
+
import {satisfies, valid, validRange} from 'semver';
|
|
3
|
+
import {NodeResolutionResult, NodeResolutionResultQueries} from '@openrewrite/rewrite/javascript';
|
|
4
|
+
|
|
5
|
+
/** Select an installed version only when the original requests establish ordinary semver provenance. */
|
|
6
|
+
export function originalCraDependencyVersion(
|
|
7
|
+
resolution: NodeResolutionResult | undefined,
|
|
8
|
+
packageName: string,
|
|
9
|
+
): string | undefined {
|
|
10
|
+
if (!resolution?.resolvedDependencies || isBuiltin(packageName) || packageName.startsWith('node:')) {
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
const installed = NodeResolutionResultQueries.getAllResolvedVersions(resolution, packageName);
|
|
14
|
+
const versions = new Set(installed.map(dependency => dependency.version));
|
|
15
|
+
if (versions.size !== 1) return undefined;
|
|
16
|
+
const version = installed[0].version;
|
|
17
|
+
if (!version || !valid(version) || !/^\d/.test(version) || version.trim() !== version) return undefined;
|
|
18
|
+
|
|
19
|
+
let hasProvenance = false;
|
|
20
|
+
// Inspect every original request: a semver-looking fork can share the registry package's version.
|
|
21
|
+
for (const owner of [resolution, ...resolution.resolvedDependencies]) {
|
|
22
|
+
for (const scope of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies', 'bundledDependencies'] as const) {
|
|
23
|
+
const requests = scope === 'bundledDependencies'
|
|
24
|
+
? ('bundledDependencies' in owner ? owner.bundledDependencies : undefined)
|
|
25
|
+
: owner[scope];
|
|
26
|
+
for (const request of requests ?? []) {
|
|
27
|
+
const targetsAlias = request.versionConstraint === `npm:${packageName}` ||
|
|
28
|
+
request.versionConstraint?.startsWith(`npm:${packageName}@`);
|
|
29
|
+
if (request.name !== packageName && request.resolved?.name !== packageName && !targetsAlias) continue;
|
|
30
|
+
if (request.name !== packageName || !request.versionConstraint?.trim() ||
|
|
31
|
+
!validRange(request.versionConstraint) ||
|
|
32
|
+
!satisfies(version, request.versionConstraint) ||
|
|
33
|
+
(request.resolved && (request.resolved.name !== packageName || request.resolved.version !== version))) {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
hasProvenance = true;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return hasProvenance ? version : undefined;
|
|
41
|
+
}
|
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
import {ExecutionContext, ScanningRecipe, Tree, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
-
import {Json} from "@openrewrite/rewrite/json";
|
|
2
|
+
import {Json, valueAt} from "@openrewrite/rewrite/json";
|
|
3
3
|
import {PlainText} from "@openrewrite/rewrite/text";
|
|
4
|
-
import {
|
|
4
|
+
import {findNodeResolutionResult, JS} from "@openrewrite/rewrite/javascript";
|
|
5
|
+
import {satisfies, valid, validRange} from 'semver';
|
|
6
|
+
import {craFilesOnly} from './cra-file-gate';
|
|
7
|
+
import {svgComponentName} from "./svg-component";
|
|
8
|
+
import {baseName, dirName, isCraPackage, runsOnVite, nearestRoot, isPackageJson, joinPath, rootObject, stringValue} from "./shared";
|
|
5
9
|
|
|
6
10
|
/** What the recipes that add or move files need to know about the whole repository before they edit it. */
|
|
7
11
|
export class CraProjects {
|
|
12
|
+
/** Optional admission decision populated before generators run, after all scanners have completed. */
|
|
13
|
+
allowedRoots?: ReadonlySet<string>;
|
|
8
14
|
/** Directories of the `package.json` files that Create React App built; `''` is the repository root. */
|
|
9
15
|
readonly roots = new Set<string>();
|
|
10
16
|
/** The subset of `roots` whose `start` and `build` will run on Vite, the only ones the edit recipes change. */
|
|
@@ -13,8 +19,11 @@ export class CraProjects {
|
|
|
13
19
|
readonly packageDirs = new Set<string>();
|
|
14
20
|
/** Every source path in the repository, to tell whether a file already exists. */
|
|
15
21
|
readonly paths = new Set<string>();
|
|
22
|
+
readonly svgComponentFiles = new Set<string>();
|
|
16
23
|
/** The `public/index.html` text of each directory. */
|
|
17
24
|
readonly indexHtml = new Map<string, string>();
|
|
25
|
+
/** Original manifests used to carry CRA's configuration into generated files. */
|
|
26
|
+
readonly configSettings = new Map<string, {homepage?: string; proxy?: string; reactVersion?: string}>();
|
|
18
27
|
|
|
19
28
|
/**
|
|
20
29
|
* True when the file belongs to a Create React App package: the nearest `package.json` above it, not any
|
|
@@ -28,13 +37,27 @@ export class CraProjects {
|
|
|
28
37
|
/** True when the file belongs to a package whose `start` and `build` will run on Vite, so the edit recipes may change it. */
|
|
29
38
|
isViteFile(sourcePath: string): boolean {
|
|
30
39
|
const owner = nearestRoot(this.packageDirs, sourcePath);
|
|
31
|
-
return owner !== undefined && this.
|
|
40
|
+
return owner !== undefined && this.mayMigrate(owner);
|
|
32
41
|
}
|
|
33
42
|
|
|
34
43
|
/** True when the file is client code that CRA bundled: below the `src/` of a package that runs on Vite. */
|
|
35
44
|
isViteClientSource(sourcePath: string): boolean {
|
|
36
45
|
const owner = nearestRoot(this.packageDirs, sourcePath);
|
|
37
|
-
return owner !== undefined && this.
|
|
46
|
+
return owner !== undefined && this.mayMigrate(owner) && sourcePath.startsWith(joinPath(owner, "src/"));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** True when the file is client code (see isViteClientSource) of the package rooted at `root`. */
|
|
50
|
+
isClientSourceOf(root: string | undefined, sourcePath: string): boolean {
|
|
51
|
+
return nearestRoot(this.packageDirs, sourcePath) === root && this.isViteClientSource(sourcePath);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** True when some client source of the package rooted at `root` imports an SVG component. */
|
|
55
|
+
usesSvgr(root: string | undefined): boolean {
|
|
56
|
+
return [...this.svgComponentFiles].some(path => this.isClientSourceOf(root, path));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
mayMigrate(root: string): boolean {
|
|
60
|
+
return this.viteRoots.has(root) && (this.allowedRoots === undefined || this.allowedRoots.has(root));
|
|
38
61
|
}
|
|
39
62
|
|
|
40
63
|
has(root: string, name: string): boolean {
|
|
@@ -61,9 +84,23 @@ export function scanCraProjects(acc: CraProjects): TreeVisitor<any, ExecutionCon
|
|
|
61
84
|
const sourcePath = (tree as { sourcePath?: string }).sourcePath;
|
|
62
85
|
if (sourcePath === undefined) return tree as R;
|
|
63
86
|
acc.paths.add(sourcePath);
|
|
87
|
+
if (tree.kind === JS.Kind.CompilationUnit && (tree as JS.CompilationUnit).statements.some(rp => {
|
|
88
|
+
if (rp.element.kind !== JS.Kind.Import) return false;
|
|
89
|
+
const imp = rp.element as JS.Import;
|
|
90
|
+
const path = (imp.moduleSpecifier?.element as {value?: unknown} | undefined)?.value;
|
|
91
|
+
return !!svgComponentName(imp) || typeof path === "string" && path.endsWith(".svg?react");
|
|
92
|
+
})) acc.svgComponentFiles.add(sourcePath);
|
|
64
93
|
if (tree.kind === Json.Kind.Document && isPackageJson(sourcePath)) {
|
|
65
94
|
acc.packageDirs.add(dirName(sourcePath));
|
|
66
95
|
const pkg = rootObject(tree as Json.Document);
|
|
96
|
+
const resolution = findNodeResolutionResult(tree as Json.Document);
|
|
97
|
+
const react = [...resolution?.dependencies ?? [], ...resolution?.devDependencies ?? []].find(dep => dep.name === 'react');
|
|
98
|
+
const declared = pkg && (stringValue(valueAt(pkg, ['dependencies', 'react'])) ?? stringValue(valueAt(pkg, ['devDependencies', 'react'])));
|
|
99
|
+
const resolved = react?.resolved?.name === 'react' && react.resolved.version;
|
|
100
|
+
if (pkg) acc.configSettings.set(dirName(sourcePath), {
|
|
101
|
+
homepage: stringValue(valueAt(pkg, ["homepage"])), proxy: stringValue(valueAt(pkg, ["proxy"])),
|
|
102
|
+
reactVersion: resolved && valid(resolved) && (!declared || !validRange(declared) || satisfies(resolved, declared)) ? resolved : declared
|
|
103
|
+
});
|
|
67
104
|
if (pkg && isCraPackage(pkg)) acc.roots.add(dirName(sourcePath));
|
|
68
105
|
if (pkg && runsOnVite(pkg)) acc.viteRoots.add(dirName(sourcePath));
|
|
69
106
|
} else if (tree.kind === PlainText.Kind.PlainText && indexHtmlRoot(sourcePath) !== undefined) {
|
|
@@ -76,11 +113,25 @@ export function scanCraProjects(acc: CraProjects): TreeVisitor<any, ExecutionCon
|
|
|
76
113
|
|
|
77
114
|
/** A recipe that scans the whole repository for Create React App packages. Finders use `isCraFile`, edits `isViteFile`. */
|
|
78
115
|
export abstract class CraScanningRecipe extends ScanningRecipe<CraProjects> {
|
|
116
|
+
// Keep the framework's accumulator delegate, but expose its file gate at PrepareRecipe time too.
|
|
117
|
+
override async editor() { return craFilesOnly(await super.editor()); }
|
|
118
|
+
private allowedRoots?: ReadonlySet<string>;
|
|
119
|
+
|
|
120
|
+
/** Gate a composite step on a shared, later-populated native dependency decision. Standalone steps are unrestricted. */
|
|
121
|
+
restrictTo(roots: ReadonlySet<string>): this {
|
|
122
|
+
this.allowedRoots = roots;
|
|
123
|
+
return this;
|
|
124
|
+
}
|
|
125
|
+
|
|
79
126
|
initialValue(): CraProjects {
|
|
80
|
-
|
|
127
|
+
const acc = new CraProjects();
|
|
128
|
+
acc.allowedRoots = this.allowedRoots;
|
|
129
|
+
return acc;
|
|
81
130
|
}
|
|
82
131
|
|
|
83
132
|
async scanner(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
84
|
-
|
|
133
|
+
// PrepareRecipe asks for a scanner with no accumulator to infer its tree gate.
|
|
134
|
+
if (acc) acc.allowedRoots = this.allowedRoots;
|
|
135
|
+
return craFilesOnly(scanCraProjects(acc));
|
|
85
136
|
}
|
|
86
137
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {isStartOrBuildScript} from './cra-script';
|
|
1
2
|
import {elementsOf, findMember, getMemberKeyName, isLiteral, isObject, Json, membersOf, valueAt} from "@openrewrite/rewrite/json";
|
|
2
3
|
|
|
3
4
|
export const REACT_SCRIPTS = "react-scripts";
|
|
@@ -65,29 +66,38 @@ export function scriptsUseReactScripts(pkg: Json.Object): boolean {
|
|
|
65
66
|
|
|
66
67
|
/** A `package.json` that Create React App built: `react-scripts` is a dependency. */
|
|
67
68
|
export function isCraPackage(pkg: Json.Object): boolean {
|
|
68
|
-
return
|
|
69
|
+
return reactScriptsDependencies(pkg).length > 0;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Scoped forks keep CRA's command and project layout. */
|
|
73
|
+
export function reactScriptsDependencies(pkg: Json.Object): string[] {
|
|
74
|
+
return DEPENDENCY_SECTIONS.flatMap(section => {
|
|
75
|
+
const dependencies = memberObject(pkg, section);
|
|
76
|
+
return dependencies ? membersOf(dependencies).flatMap(m => {
|
|
77
|
+
const name = getMemberKeyName(m);
|
|
78
|
+
return name && /^(?:@[^/]+\/)?react-scripts$/.test(name) ? [name] : [];
|
|
79
|
+
}) : [];
|
|
80
|
+
});
|
|
69
81
|
}
|
|
70
82
|
|
|
71
83
|
/** Tools that wrap or replace `react-scripts`, and which Vite does not replace. */
|
|
72
84
|
const WRAPPER_DEPENDENCIES = ["@craco/craco", "craco", "react-app-rewired"];
|
|
73
85
|
const WRAPPER_COMMAND = /(^|[\s&;|])(craco|react-app-rewired)(\s|$)/;
|
|
86
|
+
const VITE_SCRIPT = /^(?:(?:tsc --noEmit|node scripts\/vite-typecheck\.cjs) && )?vite(?: build)?(?: --(?:host|base|outDir) "[\w./:@%+ -]+"| --port \d+)*$/;
|
|
74
87
|
const START_OR_BUILD = /(^|[\s&;|])react-scripts\s+(start|build)(\s|$)/;
|
|
75
|
-
/** The only commands the migration rewrites. */
|
|
76
|
-
export const EXACT_START_OR_BUILD = /^react-scripts (start|build)$/;
|
|
77
88
|
|
|
78
|
-
/**
|
|
79
|
-
* True when the package's `start` and `build` will run on Vite once the migration has edited it: it is a Create
|
|
80
|
-
* React App package that neither depends on `craco` or `react-app-rewired` nor has a script that wraps those or
|
|
81
|
-
* `react-scripts start|build` (`cross-env PORT=4000 react-scripts start`, `react-scripts build --profile`).
|
|
82
|
-
* Such a package is only found by the finders; editing it would leave `start` or `build` without a working tool.
|
|
83
|
-
*/
|
|
89
|
+
/** Admit standard CRA commands and literal host/port/base/output controls; custom wrappers stay for review. */
|
|
84
90
|
export function runsOnVite(pkg: Json.Object): boolean {
|
|
85
91
|
if (!isCraPackage(pkg) || WRAPPER_DEPENDENCIES.some(name => hasDependency(pkg, name))) return false;
|
|
86
92
|
const scripts = memberObject(pkg, "scripts");
|
|
87
93
|
return !scripts || membersOf(scripts).every(m => {
|
|
88
94
|
const command = stringValue(m.value)?.trim();
|
|
95
|
+
// Custom entry scripts can load react-scripts internally, e.g. responsive-viewer's scripts/build.js.
|
|
96
|
+
const name = getMemberKeyName(m);
|
|
97
|
+
if ((name === "start" || name === "build") && command &&
|
|
98
|
+
!isStartOrBuildScript(command) && !VITE_SCRIPT.test(command)) return false;
|
|
89
99
|
return command === undefined || (!WRAPPER_COMMAND.test(command) &&
|
|
90
|
-
(!START_OR_BUILD.test(command) ||
|
|
100
|
+
(!START_OR_BUILD.test(command) || isStartOrBuildScript(command)));
|
|
91
101
|
});
|
|
92
102
|
}
|
|
93
103
|
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import {JS} from "@openrewrite/rewrite/javascript";
|
|
2
|
+
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
3
|
+
import {TreePrinters} from '@openrewrite/rewrite';
|
|
4
|
+
|
|
5
|
+
export function importsSvgComponent(imp: JS.Import): boolean {
|
|
6
|
+
const module = imp.moduleSpecifier?.element as J.Literal | undefined;
|
|
7
|
+
const bindings = imp.importClause?.namedBindings;
|
|
8
|
+
if (typeof module?.value !== 'string' || !module.value.endsWith('.svg') || bindings?.kind !== JS.Kind.NamedImports) return false;
|
|
9
|
+
return (bindings as JS.NamedImports).elements.elements.some(element => {
|
|
10
|
+
const specifier = element.element.specifier;
|
|
11
|
+
const name = specifier.kind === JS.Kind.Alias ? (specifier as JS.Alias).propertyName.element : specifier;
|
|
12
|
+
return isIdentifier(name) && name.simpleName === 'ReactComponent';
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Parsed replacement imports cannot carry comments attached to the original inner tokens. */
|
|
17
|
+
export async function svgImportNeedsReview(imp: JS.Import): Promise<boolean> {
|
|
18
|
+
if (!importsSvgComponent(imp)) return false;
|
|
19
|
+
if (!svgComponentName(imp)) return true;
|
|
20
|
+
const printed = await TreePrinters.printer(JS.Kind.CompilationUnit).print(imp);
|
|
21
|
+
const withoutLeadingComments = printed.replace(/^(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*(?:\n|$))*/, '');
|
|
22
|
+
return /\/[*\/]/.test(withoutLeadingComments);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The unambiguous CRA form, with exactly one named export and a relative SVG path. */
|
|
26
|
+
export function svgComponentName(imp: JS.Import): string | undefined {
|
|
27
|
+
const module = imp.moduleSpecifier?.element as J.Literal | undefined;
|
|
28
|
+
const bindings = imp.importClause?.namedBindings;
|
|
29
|
+
if (typeof module?.value !== "string" || !/^\.{1,2}\/.*\.svg$/.test(module.value) ||
|
|
30
|
+
imp.importClause?.typeOnly || bindings?.kind !== JS.Kind.NamedImports) return undefined;
|
|
31
|
+
const elements = (bindings as JS.NamedImports).elements.elements;
|
|
32
|
+
if (elements.length !== 1) return undefined;
|
|
33
|
+
const specifier = elements[0].element.specifier;
|
|
34
|
+
if (isIdentifier(specifier)) return specifier.simpleName === "ReactComponent" ? specifier.simpleName : undefined;
|
|
35
|
+
if (specifier.kind !== JS.Kind.Alias) return undefined;
|
|
36
|
+
const alias = specifier as JS.Alias;
|
|
37
|
+
const property = alias.propertyName.element;
|
|
38
|
+
return isIdentifier(property) && property.simpleName === "ReactComponent" && isIdentifier(alias.alias) ? alias.alias.simpleName : undefined;
|
|
39
|
+
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import {ExecutionContext, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
-
import {JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
|
|
2
|
+
import {JavaScriptParser, JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
|
|
3
3
|
import {J} from "@openrewrite/rewrite/java";
|
|
4
4
|
import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
|
|
5
|
-
import {baseName} from "./shared";
|
|
5
|
+
import {baseName, nearestRoot} from "./shared";
|
|
6
6
|
|
|
7
7
|
/** The `///` of a triple-slash directive is parsed as the comment's `//`, leaving `/ <reference ... />` as its text. */
|
|
8
|
-
const REACT_SCRIPTS_REFERENCE =
|
|
8
|
+
const REACT_SCRIPTS_REFERENCE = /^\/\s*<reference\s+types=["'](?:@[^/"']+\/)?react-scripts["']\s*\/>$/;
|
|
9
9
|
const VITE_CLIENT_REFERENCE = '/ <reference types="vite/client" />';
|
|
10
10
|
|
|
11
11
|
/**
|
|
@@ -29,9 +29,16 @@ export class UpdateReactAppEnvTypes extends CraScanningRecipe {
|
|
|
29
29
|
return new class extends JavaScriptVisitor<ExecutionContext> {
|
|
30
30
|
override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
31
31
|
if (!baseName(cu.sourcePath).endsWith(".d.ts") || !acc.isViteFile(cu.sourcePath)) return cu;
|
|
32
|
-
|
|
32
|
+
let comments = cu.prefix.comments.map(c =>
|
|
33
33
|
c.kind === J.Kind.TextComment && REACT_SCRIPTS_REFERENCE.test((c as unknown as {text: string}).text) ?
|
|
34
34
|
{...c, text: VITE_CLIENT_REFERENCE} : c);
|
|
35
|
+
const owner = nearestRoot(acc.packageDirs, cu.sourcePath);
|
|
36
|
+
const svgr = acc.usesSvgr(owner);
|
|
37
|
+
if (svgr && baseName(cu.sourcePath) === "react-app-env.d.ts" && !comments.some(c =>
|
|
38
|
+
c.kind === J.Kind.TextComment && (c as unknown as {text: string}).text.includes('types="vite-plugin-svgr/client"'))) {
|
|
39
|
+
const parsed = await new JavaScriptParser().parseOne({text: '/// <reference types="vite-plugin-svgr/client" />\n', sourcePath: "svgr-env.d.ts"}) as JS.CompilationUnit;
|
|
40
|
+
comments = [...comments, ...parsed.prefix.comments];
|
|
41
|
+
}
|
|
35
42
|
if (comments.every((c, i) => c === cu.prefix.comments[i])) return super.visitJsCompilationUnit(cu, ctx);
|
|
36
43
|
return {...cu, prefix: {...cu.prefix, comments}} as JS.CompilationUnit;
|
|
37
44
|
}
|