@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
|
@@ -38,19 +38,21 @@ interface Plan {
|
|
|
38
38
|
const plans = new WeakMap<CraProjects, Plan>();
|
|
39
39
|
|
|
40
40
|
/** Roots whose `public/index.html` can move, and why the others stay. */
|
|
41
|
-
function plan(acc: CraProjects): Plan {
|
|
41
|
+
function plan(acc: CraProjects, renames: ReadonlySet<string>): Plan {
|
|
42
42
|
let cached = plans.get(acc);
|
|
43
|
-
if (!cached) plans.set(acc, cached = computePlan(acc));
|
|
43
|
+
if (!cached) plans.set(acc, cached = computePlan(acc, renames));
|
|
44
44
|
return cached;
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
function computePlan(acc: CraProjects): Plan {
|
|
47
|
+
function computePlan(acc: CraProjects, renames: ReadonlySet<string>): Plan {
|
|
48
48
|
const moved = new Map<string, string>();
|
|
49
49
|
const declined = new Map<string, {reason: string; entry?: string}>();
|
|
50
50
|
const missing = new Map<string, string>();
|
|
51
51
|
for (const root of acc.viteRoots) {
|
|
52
|
+
if (!acc.mayMigrate(root)) continue;
|
|
52
53
|
const html = acc.indexHtml.get(root);
|
|
53
|
-
const
|
|
54
|
+
const originalEntry = acc.firstExisting(root, ENTRY_FILES);
|
|
55
|
+
const entry = originalEntry && renames.has(joinPath(root, originalEntry)) ? originalEntry.replace(/\.js$/, '.jsx') : originalEntry;
|
|
54
56
|
if (html === undefined) {
|
|
55
57
|
if (!acc.has(root, "index.html")) missing.set(root, entry ?? "src/index.tsx");
|
|
56
58
|
continue;
|
|
@@ -87,12 +89,15 @@ function computePlan(acc: CraProjects): Plan {
|
|
|
87
89
|
* @see https://vite.dev/guide/#index-html-and-project-root
|
|
88
90
|
*/
|
|
89
91
|
export class MovePublicIndexHtml extends CraScanningRecipe {
|
|
92
|
+
private entryRenames: ReadonlySet<string> = new Set();
|
|
93
|
+
|
|
94
|
+
withRenamedEntries(paths: ReadonlySet<string>): this { this.entryRenames = paths; return this; }
|
|
90
95
|
readonly name = "org.openrewrite.react.cra-to-vite.move-public-index-html";
|
|
91
96
|
readonly displayName = "Move `public/index.html` to the project root for Vite";
|
|
92
97
|
readonly description = "Moves `public/index.html` of a Create React App project to the project root, replaces `%PUBLIC_URL%` and `%REACT_APP_*%` placeholders, and adds a module script for `src/index`. Pages that cannot be moved safely are left in place.";
|
|
93
98
|
|
|
94
99
|
async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
95
|
-
const {moved, declined} = plan(acc);
|
|
100
|
+
const {moved, declined} = plan(acc, this.entryRenames);
|
|
96
101
|
// The edit only asks which roots move, so it does not need to keep each page's migrated text.
|
|
97
102
|
const movedRoots = new Set(moved.keys());
|
|
98
103
|
const table = craToViteBlockersTable();
|
|
@@ -117,14 +122,14 @@ export class MovePublicIndexHtml extends CraScanningRecipe {
|
|
|
117
122
|
const parser = Parsers.createParser("plainText", {ctx});
|
|
118
123
|
const generated: SourceFile[] = [];
|
|
119
124
|
const table = craToViteBlockersTable();
|
|
120
|
-
for (const [root, entry] of plan(acc).missing) {
|
|
125
|
+
for (const [root, entry] of plan(acc, this.entryRenames).missing) {
|
|
121
126
|
// Only the path is recorded: the page may exist but not be in the LST, since `.html` is not always loaded.
|
|
122
127
|
table.insertRow(ctx, {
|
|
123
128
|
filePath: joinPath(root, "package.json"), category: "index-html", detail: "public/index.html was not found in the LST",
|
|
124
129
|
nextStep: `Vite needs index.html at the project root, and \`vite build\` fails without it. Move public/index.html there by hand and add <script type="module" src="/${entry}"></script>.`
|
|
125
130
|
});
|
|
126
131
|
}
|
|
127
|
-
for (const [root, html] of plan(acc).moved) {
|
|
132
|
+
for (const [root, html] of plan(acc, this.entryRenames).moved) {
|
|
128
133
|
generated.push(await parser.parseOne({text: html, sourcePath: joinPath(root, "index.html")}));
|
|
129
134
|
}
|
|
130
135
|
return generated;
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import {Cursor, ExecutionContext, SourceFile, Tree, TreeVisitor} from '@openrewrite/rewrite';
|
|
2
|
+
import {findNodeResolutionResult, JavaScriptVisitor, JS, JSX, namesDeclaredIn} from '@openrewrite/rewrite/javascript';
|
|
3
|
+
import {isIdentifier, J} from '@openrewrite/rewrite/java';
|
|
4
|
+
import {Json, isObject, membersOf, getMemberKeyName, valueAt} from '@openrewrite/rewrite/json';
|
|
5
|
+
import {PlainText} from '@openrewrite/rewrite/text';
|
|
6
|
+
import {posix} from 'node:path';
|
|
7
|
+
import {builtinModules} from 'node:module';
|
|
8
|
+
import {CraProjects, CraScanningRecipe, VITE_CONFIG_NAMES} from './scan-cra-projects';
|
|
9
|
+
import {baseName, dirName, isEnvFile, joinPath, memberObject, nearestRoot, rootObject, stringValue} from './shared';
|
|
10
|
+
import {viteIndexHtml} from './move-public-index-html';
|
|
11
|
+
import {craToViteBlockersTable} from './cra-blockers-table';
|
|
12
|
+
import {CRA_TYPECHECK_PATH} from './cra-typecheck';
|
|
13
|
+
import {svgImportNeedsReview} from './svg-component';
|
|
14
|
+
import {craFilesOnly} from './cra-file-gate';
|
|
15
|
+
import {originalCraDependencyVersion} from './resolved-cra-dependency';
|
|
16
|
+
import {PreservedCraDependency} from './prepare-cra-package';
|
|
17
|
+
|
|
18
|
+
const BUILTINS = new Set(builtinModules);
|
|
19
|
+
const CRA_WORKER_MODULE = /(?:^|\/)(?:registerServiceWorker|serviceWorker|serviceWorkerRegistration)(?:\.[cm]?[jt]sx?)?$/;
|
|
20
|
+
const WORKER_REVIEW = 'Active CRA service-worker registration requires an explicit Vite PWA configuration';
|
|
21
|
+
|
|
22
|
+
const isPostcssConfig = (path: string) => /^(?:postcss\.config|\.postcssrc)\.[cm]?[jt]s$/.test(baseName(path));
|
|
23
|
+
|
|
24
|
+
class MigrationProjects extends CraProjects {
|
|
25
|
+
readonly unsupported = new Map<string, string>();
|
|
26
|
+
readonly jsx = new Set<string>();
|
|
27
|
+
readonly requires = new Map<string, string[]>();
|
|
28
|
+
readonly env = new Map<string, Set<string>>();
|
|
29
|
+
readonly imports = new Map<string, string[]>();
|
|
30
|
+
readonly aliases = new Map<string, {baseUrl?: string; paths: string[]}>();
|
|
31
|
+
readonly dependencies = new Map<string, Set<string>>();
|
|
32
|
+
readonly resolvedVersions = new Map<string, Map<string, string>>();
|
|
33
|
+
readonly preservedDependencies = new Map<string, Map<string, PreservedCraDependency>>();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Plan the whole package before its native dependency transaction or source changes are admitted. */
|
|
37
|
+
export class PlanCraToVite extends CraScanningRecipe {
|
|
38
|
+
readonly ready: Set<string>;
|
|
39
|
+
readonly renamedFiles = new Set<string>();
|
|
40
|
+
readonly name: string = 'org.openrewrite.react.cra-to-vite.plan-migration';
|
|
41
|
+
readonly displayName: string = 'Check CRA projects before migrating to Vite';
|
|
42
|
+
readonly description: string = 'Declines packages with missing or conflicting HTML/configuration, custom proxies, JSX path collisions, unsupported webpack/env access or environment-name collisions. Records why each package needs manual review.';
|
|
43
|
+
constructor(readyOrOptions: Set<string> | {} = new Set<string>()) {
|
|
44
|
+
super(readyOrOptions instanceof Set ? undefined : readyOrOptions);
|
|
45
|
+
this.ready = readyOrOptions instanceof Set ? readyOrOptions : new Set<string>();
|
|
46
|
+
}
|
|
47
|
+
override initialValue(): MigrationProjects { this.ready.clear(); this.renamedFiles.clear(); return new MigrationProjects(); }
|
|
48
|
+
override async scanner(acc: MigrationProjects): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
49
|
+
const cra = await super.scanner(acc);
|
|
50
|
+
const js = new class extends JavaScriptVisitor<ExecutionContext> {
|
|
51
|
+
private path = '';
|
|
52
|
+
private globalProcess = true;
|
|
53
|
+
private workerFunctions = new Set<string>();
|
|
54
|
+
private workerNamespaces = new Set<string>();
|
|
55
|
+
private declared: ReadonlySet<string> = new Set<string>();
|
|
56
|
+
override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext) {
|
|
57
|
+
this.path = cu.sourcePath;
|
|
58
|
+
this.declared = namesDeclaredIn(cu);
|
|
59
|
+
this.globalProcess = !this.declared.has('process');
|
|
60
|
+
this.workerFunctions.clear(); this.workerNamespaces.clear();
|
|
61
|
+
for (const rp of cu.statements) {
|
|
62
|
+
if (rp.element.kind !== JS.Kind.Import) continue;
|
|
63
|
+
const imp = rp.element as JS.Import;
|
|
64
|
+
const module = (imp.moduleSpecifier?.element as J.Literal | undefined)?.value;
|
|
65
|
+
if (typeof module !== 'string' || !module.startsWith('.') || !CRA_WORKER_MODULE.test(module) || imp.importClause?.typeOnly) continue;
|
|
66
|
+
const clause = imp.importClause;
|
|
67
|
+
if (!clause) { acc.unsupported.set(this.path, WORKER_REVIEW); continue; }
|
|
68
|
+
if (clause.name) {
|
|
69
|
+
this.workerFunctions.add(clause.name.element.simpleName);
|
|
70
|
+
this.workerNamespaces.add(clause.name.element.simpleName);
|
|
71
|
+
}
|
|
72
|
+
const bindings = clause.namedBindings;
|
|
73
|
+
if (bindings?.kind === JS.Kind.Alias && isIdentifier((bindings as JS.Alias).alias)) this.workerNamespaces.add(((bindings as JS.Alias).alias as J.Identifier).simpleName);
|
|
74
|
+
if (bindings?.kind === JS.Kind.NamedImports) for (const named of (bindings as JS.NamedImports).elements.elements) {
|
|
75
|
+
const specifier = named.element.specifier;
|
|
76
|
+
const original = specifier.kind === JS.Kind.Alias ? (specifier as JS.Alias).propertyName.element : specifier;
|
|
77
|
+
const local = specifier.kind === JS.Kind.Alias ? (specifier as JS.Alias).alias : specifier;
|
|
78
|
+
if (isIdentifier(original) && original.simpleName === 'register' && isIdentifier(local)) this.workerFunctions.add(local.simpleName);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return super.visitJsCompilationUnit(cu, ctx);
|
|
82
|
+
}
|
|
83
|
+
override async visitJsxTag(tag: JSX.Tag, ctx: ExecutionContext) {
|
|
84
|
+
if (this.path.endsWith('.js')) acc.jsx.add(this.path);
|
|
85
|
+
return super.visitJsxTag(tag, ctx);
|
|
86
|
+
}
|
|
87
|
+
private recordModule(module: unknown): void {
|
|
88
|
+
if (typeof module !== 'string') return;
|
|
89
|
+
if (module.includes('!')) acc.unsupported.set(this.path, 'webpack loader imports require a Vite plugin');
|
|
90
|
+
if (module.startsWith('node:') || BUILTINS.has(module)) acc.unsupported.set(this.path, 'Node built-ins need an explicit browser implementation');
|
|
91
|
+
if (!module.startsWith('.') && !/^(?:https?:|data:)/.test(module)) {
|
|
92
|
+
const imports = acc.imports.get(this.path) ?? []; imports.push(module); acc.imports.set(this.path, imports);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
override async visitImportDeclaration(imp: JS.Import, ctx: ExecutionContext) {
|
|
96
|
+
const module = (imp.moduleSpecifier?.element as J.Literal | undefined)?.value;
|
|
97
|
+
if (typeof module === 'string' && module.endsWith('.svg') && imp.importClause?.namedBindings && imp.importClause.namedBindings.kind !== JS.Kind.NamedImports) acc.unsupported.set(this.path, 'SVG namespace imports require manual component migration');
|
|
98
|
+
if (await svgImportNeedsReview(imp)) acc.unsupported.set(this.path, 'SVG component import requires manual preservation of its path, bindings or comments');
|
|
99
|
+
this.recordModule(module);
|
|
100
|
+
return super.visitImportDeclaration(imp, ctx);
|
|
101
|
+
}
|
|
102
|
+
override async visitExportDeclaration(exp: JS.ExportDeclaration, ctx: ExecutionContext) {
|
|
103
|
+
const module = (exp.moduleSpecifier?.element as J.Literal | undefined)?.value;
|
|
104
|
+
if (typeof module === 'string' && module.startsWith('.') && CRA_WORKER_MODULE.test(module) && !exp.typeOnly.element) acc.unsupported.set(this.path, WORKER_REVIEW);
|
|
105
|
+
if (typeof module === 'string' && module.endsWith('.svg')) acc.unsupported.set(this.path, 'SVG re-exports require manual component migration');
|
|
106
|
+
this.recordModule(module);
|
|
107
|
+
return super.visitExportDeclaration(exp, ctx);
|
|
108
|
+
}
|
|
109
|
+
override async visitIdentifier(id: J.Identifier, ctx: ExecutionContext) {
|
|
110
|
+
if (isPostcssConfig(this.path) && ['autoprefixer', 'tailwindcss'].includes(id.simpleName)) this.recordModule(id.simpleName);
|
|
111
|
+
const parent = this.cursor.parentTree()?.value;
|
|
112
|
+
const propertyName = parent?.kind === J.Kind.FieldAccess && parent.name.element === id || parent?.kind === J.Kind.MethodInvocation && parent.name === id && !!parent.select;
|
|
113
|
+
const unregister = parent?.kind === J.Kind.MethodInvocation && parent.select?.element === id && parent.name.simpleName === 'unregister' || parent?.kind === J.Kind.FieldAccess && parent.target === id && parent.name.element.simpleName === 'unregister';
|
|
114
|
+
if (!propertyName && (this.workerFunctions.has(id.simpleName) || this.workerNamespaces.has(id.simpleName) && !unregister) && !this.cursor.asArray().some(node => node?.kind === JS.Kind.Import)) acc.unsupported.set(this.path, WORKER_REVIEW);
|
|
115
|
+
const selected = parent?.kind === J.Kind.FieldAccess && parent.target === id || parent?.kind === J.Kind.MethodInvocation && parent.select?.element === id;
|
|
116
|
+
const env = id.simpleName === 'process' && parent?.kind === J.Kind.FieldAccess && parent.name.element.simpleName === 'env';
|
|
117
|
+
if (selected && !env && ['Buffer', 'process', 'global'].includes(id.simpleName) && !this.declared.has(id.simpleName)) acc.unsupported.set(this.path, 'implicit Node browser shims require an explicit Vite implementation');
|
|
118
|
+
return super.visitIdentifier(id, ctx);
|
|
119
|
+
}
|
|
120
|
+
override async visitLiteral(literal: J.Literal, ctx: ExecutionContext) {
|
|
121
|
+
if (isPostcssConfig(this.path) && typeof literal.value === 'string' && ['autoprefixer', 'tailwindcss'].includes(literal.value)) this.recordModule(literal.value);
|
|
122
|
+
return super.visitLiteral(literal, ctx);
|
|
123
|
+
}
|
|
124
|
+
override async visitFunctionCall(call: JS.FunctionCall, ctx: ExecutionContext) {
|
|
125
|
+
const fn = call.function?.element;
|
|
126
|
+
if (fn && isIdentifier(fn) && fn.simpleName === 'import') {
|
|
127
|
+
const module = (call.arguments.elements[0]?.element as J.Literal | undefined)?.value;
|
|
128
|
+
if (typeof module !== 'string') acc.unsupported.set(this.path, 'computed webpack dynamic imports require a Vite import map');
|
|
129
|
+
else this.recordModule(module);
|
|
130
|
+
}
|
|
131
|
+
return super.visitFunctionCall(call, ctx);
|
|
132
|
+
}
|
|
133
|
+
override async visitMethodInvocation(call: J.MethodInvocation, ctx: ExecutionContext) {
|
|
134
|
+
const select = call.select?.element;
|
|
135
|
+
if (call.name.simpleName === 'register' && select?.kind === J.Kind.FieldAccess && (select as J.FieldAccess).name.element.simpleName === 'serviceWorker' && isIdentifier((select as J.FieldAccess).target) && ((select as J.FieldAccess).target as J.Identifier).simpleName === 'navigator' && !this.declared.has('navigator') && !CRA_WORKER_MODULE.test(this.path)) acc.unsupported.set(this.path, WORKER_REVIEW);
|
|
136
|
+
if (call.name.simpleName === 'context' && select && isIdentifier(select) && select.simpleName === 'require') acc.unsupported.set(this.path, 'require.context needs import.meta.glob');
|
|
137
|
+
if (call.name.simpleName === 'require' && !select) {
|
|
138
|
+
acc.unsupported.set(this.path, 'browser CommonJS requires an explicit ESM migration');
|
|
139
|
+
const arg = call.arguments.elements[0]?.element as J.Literal | undefined;
|
|
140
|
+
if (typeof arg?.value === 'string') {
|
|
141
|
+
this.recordModule(arg.value);
|
|
142
|
+
const values = acc.requires.get(this.path) ?? []; values.push(arg.value); acc.requires.set(this.path, values);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return super.visitMethodInvocation(call, ctx);
|
|
146
|
+
}
|
|
147
|
+
override async visitFieldAccess(field: J.FieldAccess, ctx: ExecutionContext) {
|
|
148
|
+
if (!this.globalProcess && field.name.element.simpleName === 'env' && isIdentifier(field.target) && field.target.simpleName === 'process') acc.unsupported.set(this.path, 'shadowed process environment access requires scope review');
|
|
149
|
+
if (field.name.element.simpleName === 'hot' && isIdentifier(field.target) && field.target.simpleName === 'module') acc.unsupported.set(this.path, 'webpack HMR requires manual migration');
|
|
150
|
+
if (this.globalProcess && field.name.element.simpleName === 'env' && isIdentifier(field.target) && field.target.simpleName === 'process') {
|
|
151
|
+
const parent = this.cursor.parentTree()?.value as J.FieldAccess | undefined;
|
|
152
|
+
const key = parent?.kind === J.Kind.FieldAccess ? parent.name.element.simpleName : undefined;
|
|
153
|
+
if (!key || !/^(?:REACT_APP_.+|NODE_ENV|PUBLIC_URL)$/.test(key)) acc.unsupported.set(this.path, 'computed, destructured or unsupported process.env access');
|
|
154
|
+
const assignment = this.cursor.parentTree()?.parentTree()?.value as J.Assignment | undefined;
|
|
155
|
+
if (assignment?.kind === J.Kind.Assignment && assignment.variable === parent) acc.unsupported.set(this.path, 'assigning to client environment variables requires review');
|
|
156
|
+
}
|
|
157
|
+
return super.visitFieldAccess(field, ctx);
|
|
158
|
+
}
|
|
159
|
+
}();
|
|
160
|
+
return craFilesOnly(new class extends TreeVisitor<Tree, ExecutionContext> {
|
|
161
|
+
override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
|
|
162
|
+
await cra.visit(tree, ctx, parent);
|
|
163
|
+
const path = (tree as SourceFile).sourcePath;
|
|
164
|
+
if (tree.kind === JS.Kind.CompilationUnit) await js.visit(tree as J, ctx, parent);
|
|
165
|
+
if (tree.kind === Json.Kind.Document && baseName(path) === 'package.json') {
|
|
166
|
+
const resolution = findNodeResolutionResult(tree as Json.Document);
|
|
167
|
+
if (resolution && acc.viteRoots.has(dirName(path))) {
|
|
168
|
+
const versions = new Map<string, string>();
|
|
169
|
+
for (const name of new Set(resolution.resolvedDependencies.map(dependency => dependency.name))) {
|
|
170
|
+
const version = originalCraDependencyVersion(resolution, name);
|
|
171
|
+
if (version) versions.set(name, version);
|
|
172
|
+
}
|
|
173
|
+
acc.resolvedVersions.set(dirName(path), versions);
|
|
174
|
+
}
|
|
175
|
+
const pkg = rootObject(tree as Json.Document);
|
|
176
|
+
if (pkg) acc.dependencies.set(dirName(path), new Set(['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'].flatMap(section => {
|
|
177
|
+
const deps = memberObject(pkg, section);
|
|
178
|
+
return deps ? membersOf(deps).flatMap(member => getMemberKeyName(member) ?? []) : [];
|
|
179
|
+
})));
|
|
180
|
+
}
|
|
181
|
+
if (tree.kind === Json.Kind.Document && ['tsconfig.json', 'jsconfig.json'].includes(baseName(path))) {
|
|
182
|
+
const config = rootObject(tree as Json.Document);
|
|
183
|
+
const paths = config && valueAt(config, ['compilerOptions', 'paths']);
|
|
184
|
+
acc.aliases.set(dirName(path), {baseUrl: config && stringValue(valueAt(config, ['compilerOptions', 'baseUrl'])),
|
|
185
|
+
paths: paths && isObject(paths) ? membersOf(paths).flatMap(m => getMemberKeyName(m) ?? []) : []});
|
|
186
|
+
}
|
|
187
|
+
if (tree.kind === PlainText.Kind.PlainText && isEnvFile(path)) {
|
|
188
|
+
const keys = new Set<string>();
|
|
189
|
+
for (const line of (tree as PlainText).text.split('\n')) {
|
|
190
|
+
const key = /^\s*(?:export\s+)?((?:REACT_APP_|VITE_)[A-Za-z0-9_]+)\s*=/.exec(line)?.[1];
|
|
191
|
+
if (key) keys.add(key);
|
|
192
|
+
}
|
|
193
|
+
acc.env.set(path, keys);
|
|
194
|
+
}
|
|
195
|
+
return tree as R;
|
|
196
|
+
}
|
|
197
|
+
}());
|
|
198
|
+
}
|
|
199
|
+
override async generate(acc: MigrationProjects, ctx: ExecutionContext): Promise<SourceFile[]> {
|
|
200
|
+
const table = craToViteBlockersTable();
|
|
201
|
+
const unresolved = new Map<string, Set<string>>();
|
|
202
|
+
const decline = (root: string, path: string, detail: string) => table.insertRow(ctx, {
|
|
203
|
+
filePath: path, category: 'migration-declined', detail,
|
|
204
|
+
nextStep: `Migrate ${joinPath(root, 'package.json')} manually after reviewing this configuration; the composite leaves the package unchanged.`
|
|
205
|
+
});
|
|
206
|
+
for (const root of acc.roots) if (!acc.viteRoots.has(root)) decline(root, joinPath(root, 'package.json'), 'custom CRA start/build scripts or wrapper dependencies require review');
|
|
207
|
+
for (const root of acc.viteRoots) {
|
|
208
|
+
const issues = new Map<string, string>();
|
|
209
|
+
if (acc.has(root, 'tsconfig.json') && acc.has(root, 'jsconfig.json')) issues.set(joinPath(root, 'jsconfig.json'),
|
|
210
|
+
'Coexisting TypeScript and JavaScript module configurations require review');
|
|
211
|
+
for (const path of acc.paths) {
|
|
212
|
+
if (nearestRoot(acc.packageDirs, path) !== root) continue;
|
|
213
|
+
if (VITE_CONFIG_NAMES.some(name => path === joinPath(root, name))) issues.set(path, 'existing Vite configuration requires review');
|
|
214
|
+
if (path === joinPath(root, CRA_TYPECHECK_PATH)) issues.set(path, 'TypeScript checker destination already exists');
|
|
215
|
+
if (/^setupProxy\.[cm]?[jt]s$/.test(baseName(path))) issues.set(path, 'custom CRA development proxy requires review');
|
|
216
|
+
if (/^(?:\.eslintrc(?:\..*)?|eslint\.config\.[cm]?[jt]s)$/.test(baseName(path))) issues.set(path, 'external ESLint configuration needs review before removing CRA');
|
|
217
|
+
}
|
|
218
|
+
const html = acc.indexHtml.get(root);
|
|
219
|
+
const entry = acc.firstExisting(root, ['src/index.tsx', 'src/index.ts', 'src/index.jsx', 'src/index.js']);
|
|
220
|
+
if (acc.has(root, 'index.html')) issues.set(joinPath(root, 'index.html'), 'root index.html already exists');
|
|
221
|
+
if (html === undefined || !entry || viteIndexHtml(html, entry) === undefined) issues.set(joinPath(root, 'public/index.html'), 'CRA HTML or entry point is missing or cannot be moved safely');
|
|
222
|
+
for (const [path, reason] of acc.unsupported) if (acc.isClientSourceOf(root, path)) issues.set(path, reason);
|
|
223
|
+
for (const path of acc.jsx) {
|
|
224
|
+
if (!acc.isClientSourceOf(root, path)) continue;
|
|
225
|
+
const destination = path.slice(0, -3) + '.jsx';
|
|
226
|
+
if ([...acc.paths].some(existing => existing.toLowerCase() === destination.toLowerCase() || existing.toLowerCase().startsWith(destination.toLowerCase() + '/'))) issues.set(path, 'JSX destination already exists');
|
|
227
|
+
}
|
|
228
|
+
for (const [path, refs] of acc.requires) {
|
|
229
|
+
if (!acc.isClientSourceOf(root, path)) continue;
|
|
230
|
+
if (refs.some(ref => ref.startsWith('.') && acc.jsx.has(posix.normalize(posix.join(dirName(path), ref))))) issues.set(path, 'CommonJS reference to a renamed JSX file requires review');
|
|
231
|
+
}
|
|
232
|
+
const aliases = acc.aliases.get(root);
|
|
233
|
+
if (aliases) for (const [path, imports] of acc.imports) {
|
|
234
|
+
if (!acc.isClientSourceOf(root, path)) continue;
|
|
235
|
+
const needsAlias = imports.some(module => aliases.paths.some(pattern => {
|
|
236
|
+
const star = pattern.indexOf('*');
|
|
237
|
+
return star < 0 ? module === pattern : module.startsWith(pattern.slice(0, star)) && module.endsWith(pattern.slice(star + 1));
|
|
238
|
+
}) || aliases.baseUrl && ['', '.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.tsx', '/index.js', '/index.jsx'].some(ext =>
|
|
239
|
+
acc.paths.has(posix.normalize(posix.join(root, aliases.baseUrl!, module + ext)))));
|
|
240
|
+
if (needsAlias) issues.set(path, 'Configured source aliases need a matching Vite resolver');
|
|
241
|
+
}
|
|
242
|
+
for (const [path, imports] of acc.imports) {
|
|
243
|
+
if ((!acc.isViteClientSource(path) && !isPostcssConfig(path)) || nearestRoot(acc.packageDirs, path) !== root) continue;
|
|
244
|
+
const declared = [...acc.dependencies].filter(([owner]) => owner === '' || owner === root || root.startsWith(owner + '/'));
|
|
245
|
+
for (const module of imports) {
|
|
246
|
+
if (module.startsWith('/') || !acc.isViteClientSource(path) && (module.startsWith('node:') || BUILTINS.has(module))) continue;
|
|
247
|
+
const name = module.startsWith('@') ? module.split('/').slice(0, 2).join('/') : module.split('/')[0];
|
|
248
|
+
if (declared.some(([, names]) => names.has(name))) continue;
|
|
249
|
+
const version = acc.resolvedVersions.get(root)?.get(name);
|
|
250
|
+
if (!version) {
|
|
251
|
+
const missing = unresolved.get(root) ?? new Set<string>();
|
|
252
|
+
missing.add(name); unresolved.set(root, missing);
|
|
253
|
+
issues.set(path, `Import or PostCSS plugin ${module} has no direct dependency declaration or unambiguous original registry version; removing CRA can remove its hoisted provider`);
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
const preserved = acc.preservedDependencies.get(root) ?? new Map<string, PreservedCraDependency>();
|
|
257
|
+
const developmentOnly = !acc.isViteClientSource(path) && preserved.get(name)?.developmentOnly !== false;
|
|
258
|
+
preserved.set(name, {version, developmentOnly});
|
|
259
|
+
acc.preservedDependencies.set(root, preserved);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
const keys = new Set<string>();
|
|
263
|
+
for (const [path, values] of acc.env) if (dirName(path) === root) for (const key of values) keys.add(key);
|
|
264
|
+
for (const key of keys) if (key.startsWith('REACT_APP_') && keys.has('VITE_' + key.slice('REACT_APP_'.length))) issues.set(joinPath(root, '.env'), `environment names collide: ${key} and VITE_${key.slice('REACT_APP_'.length)}`);
|
|
265
|
+
if (issues.size === 0) {
|
|
266
|
+
this.ready.add(root);
|
|
267
|
+
for (const path of acc.jsx) if (acc.isClientSourceOf(root, path)) this.renamedFiles.add(path);
|
|
268
|
+
}
|
|
269
|
+
else for (const [path, reason] of issues) decline(root, path, reason);
|
|
270
|
+
}
|
|
271
|
+
// An ancestor promotion must not make an unresolved child silently eligible on the next cycle.
|
|
272
|
+
for (const root of this.ready) {
|
|
273
|
+
const preserved = acc.preservedDependencies.get(root);
|
|
274
|
+
if (preserved && [...unresolved].some(([child, names]) => child !== root && (root === '' || child.startsWith(root + '/')) &&
|
|
275
|
+
[...names].some(name => preserved.has(name)))) {
|
|
276
|
+
this.ready.delete(root);
|
|
277
|
+
decline(root, joinPath(root, 'package.json'), 'Declaring a hoisted dependency would change resolution for an unresolved nested CRA package');
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
for (const path of this.renamedFiles) if (!this.ready.has(nearestRoot(acc.packageDirs, path) ?? '\0')) this.renamedFiles.delete(path);
|
|
281
|
+
return [];
|
|
282
|
+
}
|
|
283
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import {craScript} from './cra-script';
|
|
2
|
+
import {getMemberKeyName, Json, jsonLiteral, membersOf, removeAt, setAt, valueAt} from '@openrewrite/rewrite/json';
|
|
3
|
+
import {subset} from 'semver';
|
|
4
|
+
import {craViteNodeEngine} from './cra-runtime';
|
|
5
|
+
import {craEslintNeedsReview, removeCraConfiguration} from './remove-cra-configuration';
|
|
6
|
+
import {hasDependency, memberObject, newMemberPosition, reactScriptsDependencies, rootObject, runsOnVite, scriptsUseReactScripts, stringValue} from './shared';
|
|
7
|
+
|
|
8
|
+
export interface CraPackageOptions {
|
|
9
|
+
viteVersion?: string;
|
|
10
|
+
pluginReactVersion?: string;
|
|
11
|
+
vitest?: boolean;
|
|
12
|
+
svgr?: boolean;
|
|
13
|
+
typeCheck?: boolean;
|
|
14
|
+
preservedDependencies?: ReadonlyMap<string, PreservedCraDependency>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface PreservedCraDependency {version: string; developmentOnly: boolean}
|
|
18
|
+
|
|
19
|
+
/** Prepare the whole manifest before the native engine decides whether its lock can be committed. */
|
|
20
|
+
function addDependency(doc: Json.Document, section: string, name: string, version: string): Json.Document {
|
|
21
|
+
return setAt(doc, [section, name], jsonLiteral(version), {
|
|
22
|
+
createMissing: true, position: newMemberPosition(memberObject(rootObject(doc)!, section)), parentPosition: newMemberPosition(rootObject(doc)!)
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function prepareCraPackage(doc: Json.Document, options: CraPackageOptions): Json.Document {
|
|
27
|
+
const pkg = rootObject(doc);
|
|
28
|
+
if (!pkg || !runsOnVite(pkg) || craEslintNeedsReview(doc)) return doc;
|
|
29
|
+
try {
|
|
30
|
+
if (options.vitest && !subset(options.viteVersion ?? '^7.0.0', '>=7 <8')) return doc;
|
|
31
|
+
} catch { return doc; }
|
|
32
|
+
const engine = stringValue(valueAt(pkg, ['engines', 'node']));
|
|
33
|
+
const compatibleEngine = engine && craViteNodeEngine(engine, options.viteVersion, options.pluginReactVersion, options.vitest);
|
|
34
|
+
if (engine && !compatibleEngine) return doc;
|
|
35
|
+
let updated = removeCraConfiguration(doc);
|
|
36
|
+
if (compatibleEngine && compatibleEngine !== engine) updated = setAt(updated, ['engines', 'node'], jsonLiteral(compatibleEngine));
|
|
37
|
+
const scripts = memberObject(pkg, 'scripts');
|
|
38
|
+
if (scripts) for (const member of membersOf(scripts)) {
|
|
39
|
+
const name = getMemberKeyName(member);
|
|
40
|
+
const command = stringValue(member.value)?.trim();
|
|
41
|
+
if (name === undefined || command === undefined) continue;
|
|
42
|
+
const migrated = craScript(command, options.typeCheck);
|
|
43
|
+
if (!migrated || migrated.operation === 'test' && !options.vitest) continue;
|
|
44
|
+
updated = migrated.replacement === null ? removeAt(updated, ['scripts', name]) :
|
|
45
|
+
setAt(updated, ['scripts', name], jsonLiteral(migrated.replacement));
|
|
46
|
+
}
|
|
47
|
+
// A custom command still using CRA must retain the entire original project.
|
|
48
|
+
if (scriptsUseReactScripts(rootObject(updated)!)) return doc;
|
|
49
|
+
for (const [name, dependency] of options.preservedDependencies ?? []) {
|
|
50
|
+
if (hasDependency(pkg, name)) continue;
|
|
51
|
+
const section = dependency.developmentOnly ? 'devDependencies' : 'dependencies';
|
|
52
|
+
updated = addDependency(updated, section, name, dependency.version);
|
|
53
|
+
}
|
|
54
|
+
const additions: [string, string][] = [['vite', options.viteVersion ?? '^7.0.0'], ['@vitejs/plugin-react', options.pluginReactVersion ?? '^5.2.0']];
|
|
55
|
+
if (options.vitest) additions.push(['vitest', '~4.0.18'], ['jsdom', '^26.1.0']);
|
|
56
|
+
if (options.svgr) additions.push(['vite-plugin-svgr', '^4.5.0']);
|
|
57
|
+
for (const section of ['dependencies', 'devDependencies']) {
|
|
58
|
+
const current = stringValue(valueAt(pkg, [section, '@types/node']));
|
|
59
|
+
if (!current) continue;
|
|
60
|
+
try {
|
|
61
|
+
if (subset(options.viteVersion ?? '^7.0.0', '>=7') && !subset(current, '^20.19.0 || >=22.12.0')) {
|
|
62
|
+
let compatible = craViteNodeEngine(current);
|
|
63
|
+
if (/^\^20\.\d+\.\d+$/.test(current)) compatible = '^20.19.0';
|
|
64
|
+
else if (/^\^22\.\d+\.\d+$/.test(current)) compatible = '^22.12.0';
|
|
65
|
+
if (compatible) updated = setAt(updated, [section, '@types/node'], jsonLiteral(compatible));
|
|
66
|
+
}
|
|
67
|
+
} catch { /* Unknown protocols remain subject to the native engine's refusal policy. */ }
|
|
68
|
+
}
|
|
69
|
+
for (const [name, version] of additions) {
|
|
70
|
+
if (hasDependency(pkg, name)) continue;
|
|
71
|
+
updated = addDependency(updated, 'devDependencies', name, version);
|
|
72
|
+
}
|
|
73
|
+
if (options.vitest) for (const section of ['dependencies', 'devDependencies']) {
|
|
74
|
+
const current = stringValue(valueAt(pkg, [section, '@testing-library/jest-dom']));
|
|
75
|
+
if (current) {
|
|
76
|
+
try {
|
|
77
|
+
if (subset(current, '>=5 <6')) updated = setAt(updated, [section, '@testing-library/jest-dom'], jsonLiteral('^6.9.1'));
|
|
78
|
+
} catch { /* The test preflight declines non-semver declarations. */ }
|
|
79
|
+
}
|
|
80
|
+
updated = removeAt(updated, [section, '@types/jest']);
|
|
81
|
+
}
|
|
82
|
+
for (const name of new Set(reactScriptsDependencies(pkg))) {
|
|
83
|
+
for (const section of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) updated = removeAt(updated, [section, name]);
|
|
84
|
+
}
|
|
85
|
+
return updated;
|
|
86
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import {ExecutionContext, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {elementsOf, isArray, isObject, Json, JsonVisitor, membersOf, removeAt, valueAt} from "@openrewrite/rewrite/json";
|
|
3
|
+
import {hasDependency, isPackageJson, memberObject, rootObject, stringValue, stringValues} from "./shared";
|
|
4
|
+
import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
|
|
5
|
+
|
|
6
|
+
const STOCK_BROWSERS = {
|
|
7
|
+
production: [">0.2%", "not dead", "not op_mini all"],
|
|
8
|
+
development: ["last 1 chrome version", "last 1 firefox version", "last 1 safari version"]
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
/** Drop only CRA template settings whose consumer goes away with react-scripts. */
|
|
12
|
+
export class RemoveCraConfiguration extends CraScanningRecipe {
|
|
13
|
+
readonly name = "org.openrewrite.react.cra-to-vite.remove-cra-configuration";
|
|
14
|
+
readonly displayName = "Remove unused Create React App template configuration";
|
|
15
|
+
readonly description = "Removes the stock react-app ESLint configuration when no separate ESLint command or dependency uses it, and the stock CRA browserslist when no separately declared browser-targeting tool uses it. Custom rules, targets and configuration used by other tools are preserved.";
|
|
16
|
+
|
|
17
|
+
async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
18
|
+
return new class extends JsonVisitor<ExecutionContext> {
|
|
19
|
+
protected override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
|
|
20
|
+
const pkg = rootObject(doc);
|
|
21
|
+
if (!pkg || !isPackageJson(doc.sourcePath) || !acc.isViteFile(doc.sourcePath)) return doc;
|
|
22
|
+
return removeCraConfiguration(doc);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Shared by the atomic package transaction and the standalone cleanup recipe. */
|
|
29
|
+
export function removeCraConfiguration(doc: Json.Document): Json.Document {
|
|
30
|
+
const pkg = rootObject(doc);
|
|
31
|
+
if (!pkg) return doc;
|
|
32
|
+
let updated = doc;
|
|
33
|
+
const scripts = memberObject(pkg, "scripts");
|
|
34
|
+
const usesEslint = hasDependency(pkg, "eslint") || hasDependency(pkg, "eslint-config-react-app") ||
|
|
35
|
+
!!scripts && membersOf(scripts).some(m => /\beslint\b/.test(stringValue(m.value) ?? ""));
|
|
36
|
+
const eslint = valueAt(pkg, ["eslintConfig"]);
|
|
37
|
+
if (!usesEslint && eslint && isObject(eslint) && membersOf(eslint).length === 1) {
|
|
38
|
+
const ext = valueAt(eslint, ["extends"]);
|
|
39
|
+
const names = ext && isArray(ext) ? stringValues(ext) : [stringValue(ext) ?? ""];
|
|
40
|
+
if (names.length > 0 && names.every(name => name === "react-app" || name === "react-app/jest")) {
|
|
41
|
+
updated = removeAt(updated, ["eslintConfig"]);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const targets = valueAt(pkg, ["browserslist"]);
|
|
45
|
+
const consumers = ["browserslist", "autoprefixer", "postcss-preset-env", "@babel/preset-env", "babel-preset-env", "babel-preset-react-app"];
|
|
46
|
+
if (targets && isObject(targets) && membersOf(targets).length === 2 && !consumers.some(name => hasDependency(pkg, name)) &&
|
|
47
|
+
Object.entries(STOCK_BROWSERS).every(([mode, expected]) => {
|
|
48
|
+
const actual = valueAt(targets, [mode]);
|
|
49
|
+
return actual && isArray(actual) && elementsOf(actual).length === expected.length &&
|
|
50
|
+
stringValues(actual).every((value, i) => value === expected[i]);
|
|
51
|
+
})) updated = removeAt(updated, ["browserslist"]);
|
|
52
|
+
return updated;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** An independently used CRA preset must remain a declared dependency after CRA is removed. */
|
|
56
|
+
export function craEslintNeedsReview(doc: Json.Document): boolean {
|
|
57
|
+
const pkg = rootObject(removeCraConfiguration(doc));
|
|
58
|
+
if (!pkg || hasDependency(pkg, 'eslint-config-react-app')) return false;
|
|
59
|
+
const config = valueAt(pkg, ['eslintConfig']);
|
|
60
|
+
if (!config || !isObject(config)) return false;
|
|
61
|
+
const ext = valueAt(config, ['extends']);
|
|
62
|
+
const names = ext && isArray(ext) ? stringValues(ext) : [stringValue(ext) ?? ''];
|
|
63
|
+
return names.some(name => name === 'react-app' || name === 'react-app/jest');
|
|
64
|
+
}
|