@openrewrite/recipes-react 0.15.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 +22 -29
- 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 -50
- 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 +2 -15
- package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/shared.js +32 -130
- 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 +28 -29
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -1
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js +4 -13
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js.map +1 -1
- package/dist/react17/migrate-deprecated-lifecycles.js +1 -1
- package/dist/react17/migrate-deprecated-lifecycles.js.map +1 -1
- package/dist/react17/use-new-jsx-transform.d.ts.map +1 -1
- package/dist/react17/use-new-jsx-transform.js +30 -78
- package/dist/react17/use-new-jsx-transform.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/react18/replace-unmount-component-at-node.d.ts.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.js +62 -20
- package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
- package/dist/react19/replace-default-props.d.ts.map +1 -1
- package/dist/react19/replace-default-props.js +10 -13
- package/dist/react19/replace-default-props.js.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.js +1 -6
- package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
- package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
- package/dist/refactoring/create-class-to-es6.js +4 -7
- package/dist/refactoring/create-class-to-es6.js.map +1 -1
- package/dist/refactoring/create-element-to-jsx.d.ts.map +1 -1
- package/dist/refactoring/create-element-to-jsx.js +3 -4
- package/dist/refactoring/create-element-to-jsx.js.map +1 -1
- package/dist/refactoring/prop-types-to-typescript.js +2 -3
- package/dist/refactoring/prop-types-to-typescript.js.map +1 -1
- package/dist/refactoring/pure-render-mixin.d.ts.map +1 -1
- package/dist/refactoring/pure-render-mixin.js +3 -6
- package/dist/refactoring/pure-render-mixin.js.map +1 -1
- package/dist/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 +14 -0
- package/dist/testing/enzyme-host-components.d.ts.map +1 -0
- package/dist/testing/enzyme-host-components.js +248 -0
- package/dist/testing/enzyme-host-components.js.map +1 -0
- 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 +80 -12
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +447 -135
- 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 +23 -8
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +291 -169
- 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 +13 -0
- package/dist/util/module-imports.d.ts.map +1 -0
- package/dist/util/module-imports.js +60 -0
- package/dist/util/module-imports.js.map +1 -0
- package/dist/util/react-class.d.ts +1 -0
- package/dist/util/react-class.d.ts.map +1 -1
- package/dist/util/react-class.js +3 -2
- package/dist/util/react-class.js.map +1 -1
- package/package.json +4 -4
- 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 +23 -28
- 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 +48 -54
- 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 +35 -146
- 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 +30 -41
- package/src/migration/cra-to-vite/update-tsconfig-for-vite.ts +6 -13
- package/src/react17/migrate-deprecated-lifecycles.ts +2 -2
- package/src/react17/use-new-jsx-transform.ts +30 -72
- package/src/react18/replace-reactdom-render.ts +17 -8
- package/src/react18/replace-unmount-component-at-node.ts +78 -32
- package/src/react19/replace-default-props.ts +11 -15
- package/src/react19/replace-react-shallow-renderer.ts +2 -7
- package/src/refactoring/create-class-to-es6.ts +6 -9
- package/src/refactoring/create-element-to-jsx.ts +4 -6
- package/src/refactoring/prop-types-to-typescript.ts +4 -4
- package/src/refactoring/pure-render-mixin.ts +4 -7
- package/src/testing/enzyme-constant-strings.ts +95 -0
- package/src/testing/enzyme-host-components.ts +287 -0
- 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 +584 -140
- package/src/testing/enzyme-usage.ts +29 -4
- package/src/testing/enzyme-wrapper-scope.ts +309 -151
- package/src/util/java-recipe-proxy.ts +81 -0
- package/src/util/module-imports.ts +60 -0
- package/src/util/react-class.ts +2 -1
|
@@ -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
|
+
}
|
|
@@ -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.
|