@openrewrite/recipes-react 0.16.0 → 0.18.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.
Files changed (244) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +10 -5
  4. package/dist/index.js.map +1 -1
  5. package/dist/migration/cra-to-vite/add-vite-config.d.ts +7 -0
  6. package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -1
  7. package/dist/migration/cra-to-vite/add-vite-config.js +58 -1
  8. package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -1
  9. package/dist/migration/cra-to-vite/cra-file-gate.d.ts +3 -0
  10. package/dist/migration/cra-to-vite/cra-file-gate.d.ts.map +1 -0
  11. package/dist/migration/cra-to-vite/cra-file-gate.js +10 -0
  12. package/dist/migration/cra-to-vite/cra-file-gate.js.map +1 -0
  13. package/dist/migration/cra-to-vite/cra-runtime.d.ts +2 -0
  14. package/dist/migration/cra-to-vite/cra-runtime.d.ts.map +1 -0
  15. package/dist/migration/cra-to-vite/cra-runtime.js +24 -0
  16. package/dist/migration/cra-to-vite/cra-runtime.js.map +1 -0
  17. package/dist/migration/cra-to-vite/cra-script.d.ts +8 -0
  18. package/dist/migration/cra-to-vite/cra-script.d.ts.map +1 -0
  19. package/dist/migration/cra-to-vite/cra-script.js +82 -0
  20. package/dist/migration/cra-to-vite/cra-script.js.map +1 -0
  21. package/dist/migration/cra-to-vite/cra-to-vite.d.ts +2 -1
  22. package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -1
  23. package/dist/migration/cra-to-vite/cra-to-vite.js +23 -16
  24. package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -1
  25. package/dist/migration/cra-to-vite/cra-typecheck.d.ts +4 -0
  26. package/dist/migration/cra-to-vite/cra-typecheck.d.ts.map +1 -0
  27. package/dist/migration/cra-to-vite/cra-typecheck.js +35 -0
  28. package/dist/migration/cra-to-vite/cra-typecheck.js.map +1 -0
  29. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
  30. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +5 -6
  31. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
  32. package/dist/migration/cra-to-vite/index.d.ts +8 -2
  33. package/dist/migration/cra-to-vite/index.d.ts.map +1 -1
  34. package/dist/migration/cra-to-vite/index.js +17 -2
  35. package/dist/migration/cra-to-vite/index.js.map +1 -1
  36. package/dist/migration/cra-to-vite/migrate-cra-package.d.ts +17 -0
  37. package/dist/migration/cra-to-vite/migrate-cra-package.d.ts.map +1 -0
  38. package/dist/migration/cra-to-vite/migrate-cra-package.js +181 -0
  39. package/dist/migration/cra-to-vite/migrate-cra-package.js.map +1 -0
  40. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts +9 -0
  41. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts.map +1 -0
  42. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js +66 -0
  43. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js.map +1 -0
  44. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts +49 -0
  45. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts.map +1 -0
  46. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js +506 -0
  47. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js.map +1 -0
  48. package/dist/migration/cra-to-vite/move-public-index-html.d.ts +2 -0
  49. package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -1
  50. package/dist/migration/cra-to-vite/move-public-index-html.js +12 -7
  51. package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -1
  52. package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts +30 -0
  53. package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts.map +1 -0
  54. package/dist/migration/cra-to-vite/plan-cra-to-vite.js +428 -0
  55. package/dist/migration/cra-to-vite/plan-cra-to-vite.js.map +1 -0
  56. package/dist/migration/cra-to-vite/prepare-cra-package.d.ts +15 -0
  57. package/dist/migration/cra-to-vite/prepare-cra-package.d.ts.map +1 -0
  58. package/dist/migration/cra-to-vite/prepare-cra-package.js +100 -0
  59. package/dist/migration/cra-to-vite/prepare-cra-package.js.map +1 -0
  60. package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts +12 -0
  61. package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts.map +1 -0
  62. package/dist/migration/cra-to-vite/remove-cra-configuration.js +85 -0
  63. package/dist/migration/cra-to-vite/remove-cra-configuration.js.map +1 -0
  64. package/dist/migration/cra-to-vite/rename-jsx-files.d.ts +20 -0
  65. package/dist/migration/cra-to-vite/rename-jsx-files.d.ts.map +1 -0
  66. package/dist/migration/cra-to-vite/rename-jsx-files.js +220 -0
  67. package/dist/migration/cra-to-vite/rename-jsx-files.js.map +1 -0
  68. package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -1
  69. package/dist/migration/cra-to-vite/rename-process-env-react-app.js +6 -3
  70. package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -1
  71. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +1 -1
  72. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -1
  73. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +11 -4
  74. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -1
  75. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +47 -30
  76. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -1
  77. package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts +3 -0
  78. package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts.map +1 -0
  79. package/dist/migration/cra-to-vite/resolved-cra-dependency.js +42 -0
  80. package/dist/migration/cra-to-vite/resolved-cra-dependency.js.map +1 -0
  81. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +13 -0
  82. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -1
  83. package/dist/migration/cra-to-vite/scan-cra-projects.js +52 -4
  84. package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -1
  85. package/dist/migration/cra-to-vite/shared.d.ts +1 -1
  86. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
  87. package/dist/migration/cra-to-vite/shared.js +19 -4
  88. package/dist/migration/cra-to-vite/shared.js.map +1 -1
  89. package/dist/migration/cra-to-vite/svg-component.d.ts +5 -0
  90. package/dist/migration/cra-to-vite/svg-component.d.ts.map +1 -0
  91. package/dist/migration/cra-to-vite/svg-component.js +60 -0
  92. package/dist/migration/cra-to-vite/svg-component.js.map +1 -0
  93. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
  94. package/dist/migration/cra-to-vite/update-react-app-env-types.js +12 -3
  95. package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
  96. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +3 -2
  97. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -1
  98. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +18 -14
  99. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -1
  100. package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
  101. package/dist/react18/replace-reactdom-render.js +16 -8
  102. package/dist/react18/replace-reactdom-render.js.map +1 -1
  103. package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
  104. package/dist/react18/replace-unmount-component-at-node.js +8 -1
  105. package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
  106. package/dist/react19/find-legacy-context-api.d.ts.map +1 -1
  107. package/dist/react19/find-legacy-context-api.js +21 -38
  108. package/dist/react19/find-legacy-context-api.js.map +1 -1
  109. package/dist/{react18 → react19}/remove-unstable-batched-updates.d.ts +2 -2
  110. package/dist/react19/remove-unstable-batched-updates.d.ts.map +1 -0
  111. package/dist/react19/remove-unstable-batched-updates.js +295 -0
  112. package/dist/react19/remove-unstable-batched-updates.js.map +1 -0
  113. package/dist/react19/replace-default-props.d.ts +1 -0
  114. package/dist/react19/replace-default-props.d.ts.map +1 -1
  115. package/dist/react19/replace-default-props.js +198 -151
  116. package/dist/react19/replace-default-props.js.map +1 -1
  117. package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
  118. package/dist/react19/replace-react-shallow-renderer.js +10 -25
  119. package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
  120. package/dist/refactoring/class-to-functional.d.ts.map +1 -1
  121. package/dist/refactoring/class-to-functional.js +2 -0
  122. package/dist/refactoring/class-to-functional.js.map +1 -1
  123. package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
  124. package/dist/refactoring/create-class-to-es6.js +14 -49
  125. package/dist/refactoring/create-class-to-es6.js.map +1 -1
  126. package/dist/search/find-function-component-default-props.d.ts.map +1 -1
  127. package/dist/search/find-function-component-default-props.js +6 -15
  128. package/dist/search/find-function-component-default-props.js.map +1 -1
  129. package/dist/search/find-redux-stores.d.ts +12 -0
  130. package/dist/search/find-redux-stores.d.ts.map +1 -0
  131. package/dist/search/find-redux-stores.js +87 -0
  132. package/dist/search/find-redux-stores.js.map +1 -0
  133. package/dist/simplify-object-pattern-property.d.ts.map +1 -1
  134. package/dist/simplify-object-pattern-property.js +14 -21
  135. package/dist/simplify-object-pattern-property.js.map +1 -1
  136. package/dist/simplify-react-imports.d.ts.map +1 -1
  137. package/dist/simplify-react-imports.js +10 -59
  138. package/dist/simplify-react-imports.js.map +1 -1
  139. package/dist/testing/enzyme-constant-strings.d.ts +12 -0
  140. package/dist/testing/enzyme-constant-strings.d.ts.map +1 -0
  141. package/dist/testing/enzyme-constant-strings.js +101 -0
  142. package/dist/testing/enzyme-constant-strings.js.map +1 -0
  143. package/dist/testing/enzyme-host-components.d.ts.map +1 -1
  144. package/dist/testing/enzyme-host-components.js +5 -2
  145. package/dist/testing/enzyme-host-components.js.map +1 -1
  146. package/dist/testing/enzyme-portals.d.ts +38 -0
  147. package/dist/testing/enzyme-portals.d.ts.map +1 -0
  148. package/dist/testing/enzyme-portals.js +226 -0
  149. package/dist/testing/enzyme-portals.js.map +1 -0
  150. package/dist/testing/enzyme-selector-names.d.ts +9 -0
  151. package/dist/testing/enzyme-selector-names.d.ts.map +1 -0
  152. package/dist/testing/enzyme-selector-names.js +50 -0
  153. package/dist/testing/enzyme-selector-names.js.map +1 -0
  154. package/dist/testing/enzyme-to-react-testing-library.d.ts +80 -8
  155. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  156. package/dist/testing/enzyme-to-react-testing-library.js +384 -40
  157. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  158. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  159. package/dist/testing/enzyme-usage.js +27 -4
  160. package/dist/testing/enzyme-usage.js.map +1 -1
  161. package/dist/testing/enzyme-wrapper-scope.d.ts +14 -6
  162. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  163. package/dist/testing/enzyme-wrapper-scope.js +143 -16
  164. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  165. package/dist/util/java-recipe-proxy.d.ts +18 -0
  166. package/dist/util/java-recipe-proxy.d.ts.map +1 -0
  167. package/dist/util/java-recipe-proxy.js +97 -0
  168. package/dist/util/java-recipe-proxy.js.map +1 -0
  169. package/dist/util/module-imports.d.ts +1 -0
  170. package/dist/util/module-imports.d.ts.map +1 -1
  171. package/dist/util/module-imports.js +5 -1
  172. package/dist/util/module-imports.js.map +1 -1
  173. package/dist/util/reindent.d.ts +5 -0
  174. package/dist/util/reindent.d.ts.map +1 -0
  175. package/dist/util/reindent.js +44 -0
  176. package/dist/util/reindent.js.map +1 -0
  177. package/dist/zustand/redux-stores.d.ts +74 -0
  178. package/dist/zustand/redux-stores.d.ts.map +1 -0
  179. package/dist/zustand/redux-stores.js +402 -0
  180. package/dist/zustand/redux-stores.js.map +1 -0
  181. package/dist/zustand/redux-to-zustand.d.ts +76 -0
  182. package/dist/zustand/redux-to-zustand.d.ts.map +1 -0
  183. package/dist/zustand/redux-to-zustand.js +653 -0
  184. package/dist/zustand/redux-to-zustand.js.map +1 -0
  185. package/dist/zustand/zustand-plan.d.ts +96 -0
  186. package/dist/zustand/zustand-plan.d.ts.map +1 -0
  187. package/dist/zustand/zustand-plan.js +822 -0
  188. package/dist/zustand/zustand-plan.js.map +1 -0
  189. package/package.json +2 -2
  190. package/src/index.ts +9 -4
  191. package/src/migration/cra-to-vite/add-vite-config.ts +53 -1
  192. package/src/migration/cra-to-vite/cra-file-gate.ts +8 -0
  193. package/src/migration/cra-to-vite/cra-runtime.ts +16 -0
  194. package/src/migration/cra-to-vite/cra-script.ts +61 -0
  195. package/src/migration/cra-to-vite/cra-to-vite.ts +25 -36
  196. package/src/migration/cra-to-vite/cra-typecheck.ts +33 -0
  197. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +5 -6
  198. package/src/migration/cra-to-vite/index.ts +10 -2
  199. package/src/migration/cra-to-vite/migrate-cra-package.ts +127 -0
  200. package/src/migration/cra-to-vite/migrate-cra-svg-imports.ts +41 -0
  201. package/src/migration/cra-to-vite/migrate-cra-tests-to-vitest.ts +376 -0
  202. package/src/migration/cra-to-vite/move-public-index-html.ts +12 -7
  203. package/src/migration/cra-to-vite/plan-cra-to-vite.ts +283 -0
  204. package/src/migration/cra-to-vite/prepare-cra-package.ts +86 -0
  205. package/src/migration/cra-to-vite/remove-cra-configuration.ts +64 -0
  206. package/src/migration/cra-to-vite/rename-jsx-files.ts +155 -0
  207. package/src/migration/cra-to-vite/rename-process-env-react-app.ts +6 -3
  208. package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +1 -1
  209. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +52 -33
  210. package/src/migration/cra-to-vite/resolved-cra-dependency.ts +41 -0
  211. package/src/migration/cra-to-vite/scan-cra-projects.ts +57 -6
  212. package/src/migration/cra-to-vite/shared.ts +20 -10
  213. package/src/migration/cra-to-vite/svg-component.ts +39 -0
  214. package/src/migration/cra-to-vite/update-react-app-env-types.ts +13 -6
  215. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +22 -28
  216. package/src/react18/replace-reactdom-render.ts +17 -8
  217. package/src/react18/replace-unmount-component-at-node.ts +13 -2
  218. package/src/react19/find-legacy-context-api.ts +21 -42
  219. package/src/react19/remove-unstable-batched-updates.ts +301 -0
  220. package/src/react19/replace-default-props.ts +212 -159
  221. package/src/react19/replace-react-shallow-renderer.ts +13 -36
  222. package/src/refactoring/class-to-functional.ts +3 -1
  223. package/src/refactoring/create-class-to-es6.ts +12 -63
  224. package/src/search/find-function-component-default-props.ts +8 -10
  225. package/src/search/find-redux-stores.ts +76 -0
  226. package/src/simplify-object-pattern-property.ts +22 -49
  227. package/src/simplify-react-imports.ts +12 -66
  228. package/src/testing/enzyme-constant-strings.ts +95 -0
  229. package/src/testing/enzyme-host-components.ts +6 -2
  230. package/src/testing/enzyme-portals.ts +279 -0
  231. package/src/testing/enzyme-selector-names.ts +59 -0
  232. package/src/testing/enzyme-to-react-testing-library.ts +517 -57
  233. package/src/testing/enzyme-usage.ts +29 -4
  234. package/src/testing/enzyme-wrapper-scope.ts +186 -30
  235. package/src/util/java-recipe-proxy.ts +94 -0
  236. package/src/util/module-imports.ts +6 -1
  237. package/src/util/reindent.ts +35 -0
  238. package/src/zustand/redux-stores.ts +409 -0
  239. package/src/zustand/redux-to-zustand.ts +657 -0
  240. package/src/zustand/zustand-plan.ts +843 -0
  241. package/dist/react18/remove-unstable-batched-updates.d.ts.map +0 -1
  242. package/dist/react18/remove-unstable-batched-updates.js +0 -170
  243. package/dist/react18/remove-unstable-batched-updates.js.map +0 -1
  244. package/src/react18/remove-unstable-batched-updates.ts +0 -192
@@ -0,0 +1,127 @@
1
+ import {Cursor, ExecutionContext, noopVisitor, Option, Recipe, SourceFile, Tree, TreePrinters, TreeVisitor} from '@openrewrite/rewrite';
2
+ import {DelegatingRecipe} from '@openrewrite/rewrite/rpc';
3
+ import {Json, valueAt} from '@openrewrite/rewrite/json';
4
+ import {isNodeDependencyInput} from '../../util/java-recipe-proxy';
5
+ import {PlanCraToVite} from './plan-cra-to-vite';
6
+ import {PlanVitest} from './migrate-cra-tests-to-vitest';
7
+ import {CraPackageOptions, prepareCraPackage} from './prepare-cra-package';
8
+ import {dirName, isPackageJson, joinPath, nearestRoot, rootObject, scriptsUseReactScripts, stringValue} from './shared';
9
+ import {craToViteBlockersTable} from './cra-blockers-table';
10
+ import {craViteNodeEngine} from './cra-runtime';
11
+ import {craEslintNeedsReview} from './remove-cra-configuration';
12
+ import {craFilesOnly} from './cra-file-gate';
13
+
14
+ type Projects = ReturnType<PlanCraToVite['initialValue']>;
15
+
16
+ /** Internal planner/transaction pair. Domain edits are prepared in TypeScript; Java owns native lock acceptance. */
17
+ class ApplyCraPackage extends PlanCraToVite {
18
+ override readonly name = 'org.openrewrite.react.cra-to-vite.apply-package';
19
+ override readonly displayName = 'Apply the complete CRA package migration with its native lock';
20
+ override readonly description = 'Commits scripts and all dependencies in one native lock transaction after project and test preflight.';
21
+ // Mutable holders survive the shallow copies the RPC host makes when preparing visitors.
22
+ private readonly state: {inputs: SourceFile[]; manifests: Json.Document[]; java?: DelegatingRecipe} = {inputs: [], manifests: []};
23
+ constructor(private readonly options: CraPackageOptions, private readonly testReady: ReadonlySet<string>,
24
+ private readonly landed: Set<string>, private readonly renames: Set<string>) { super(); }
25
+ override initialValue(): Projects {
26
+ this.state.inputs.length = 0;
27
+ this.state.manifests.length = 0;
28
+ this.state.java = undefined;
29
+ this.landed.clear(); this.renames.clear();
30
+ return super.initialValue();
31
+ }
32
+ override async scanner(acc: Projects): Promise<TreeVisitor<any, ExecutionContext>> {
33
+ const scanner = await super.scanner(acc); const state = this.state;
34
+ return craFilesOnly(new class extends TreeVisitor<Tree, ExecutionContext> {
35
+ override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
36
+ await scanner.visit(tree, ctx, parent);
37
+ const source = tree as SourceFile;
38
+ if (source.sourcePath && !source.sourcePath.split('/').includes('node_modules') && isNodeDependencyInput(source.sourcePath, true)) {
39
+ state.inputs.push(source);
40
+ if (tree.kind === Json.Kind.Document && isPackageJson(source.sourcePath)) state.manifests.push(tree as Json.Document);
41
+ }
42
+ return tree as R;
43
+ }
44
+ }());
45
+ }
46
+ override async generate(acc: Projects, ctx: ExecutionContext): Promise<SourceFile[]> {
47
+ await super.generate(acc, ctx);
48
+ const manifests: Record<string, string> = {};
49
+ const table = craToViteBlockersTable();
50
+ for (const doc of this.state.manifests) {
51
+ const root = dirName(doc.sourcePath);
52
+ if (!this.ready.has(root)) continue;
53
+ const pkg = rootObject(doc)!;
54
+ if (craEslintNeedsReview(doc)) {
55
+ table.insertRow(ctx, {filePath: doc.sourcePath, category: 'migration-declined', detail: 'Retained ESLint configuration depends on CRA transitive dependencies', nextStep: 'Declare eslint-config-react-app explicitly or migrate the independent linter before removing CRA.'});
56
+ continue;
57
+ }
58
+ const test = stringValue(valueAt(pkg, ['scripts', 'test']));
59
+ const vitest = !!test && /react-scripts\s+test/.test(test);
60
+ const engine = stringValue(valueAt(pkg, ['engines', 'node']));
61
+ if (engine && !craViteNodeEngine(engine, this.options.viteVersion, this.options.pluginReactVersion, vitest)) {
62
+ table.insertRow(ctx, {filePath: doc.sourcePath, category: 'migration-declined', detail: 'Declared Node engine does not support the Vite toolchain', nextStep: 'Upgrade the supported Node runtime before migrating this package.'});
63
+ continue;
64
+ }
65
+ if (vitest && !this.testReady.has(root)) {
66
+ table.insertRow(ctx, {filePath: doc.sourcePath, category: 'migration-declined', detail: 'CRA tests require manual Vitest migration',
67
+ nextStep: 'Review unsupported Jest configuration, APIs, dependencies and TypeScript settings before migrating this package.'});
68
+ continue;
69
+ }
70
+ const svgr = acc.usesSvgr(root);
71
+ const prepared = prepareCraPackage(doc, {...this.options, vitest, svgr, typeCheck: acc.has(root, 'tsconfig.json'),
72
+ preservedDependencies: acc.preservedDependencies.get(root)});
73
+ if (prepared === doc || scriptsUseReactScripts(rootObject(prepared)!)) {
74
+ table.insertRow(ctx, {filePath: doc.sourcePath, category: 'migration-declined', detail: 'A custom script still needs react-scripts', nextStep: 'Rewrite all CRA commands before removing react-scripts.'});
75
+ continue;
76
+ }
77
+ manifests[doc.sourcePath] = await TreePrinters.print(prepared);
78
+ }
79
+ if (Object.keys(manifests).length === 0) return [];
80
+ const java = this.state.java = new DelegatingRecipe('org.openrewrite.react.migrate.ApplyCraManifestEdits', {manifests});
81
+ const scanner = await java.scanner(0);
82
+ for (const input of this.state.inputs) await scanner.visit(input, ctx);
83
+ const generated = await java.generate(0, ctx);
84
+ const editor = await java.editorWithData(0);
85
+ for (const doc of this.state.manifests) {
86
+ const desired = manifests[doc.sourcePath]; if (desired === undefined) continue;
87
+ const edited = await editor.visit<Json.Document>(doc, ctx);
88
+ if (edited && await TreePrinters.print(edited) === desired) this.landed.add(dirName(doc.sourcePath));
89
+ else table.insertRow(ctx, {filePath: doc.sourcePath, category: 'migration-declined', detail: 'The native dependency engine declined the complete manifest/lock transaction', nextStep: 'Review dependency resolution and package-manager configuration; all source steps remain unchanged.'});
90
+ }
91
+ for (const path of this.renamedFiles) if (this.landed.has(nearestRoot(acc.packageDirs, path) ?? '\0')) this.renames.add(path);
92
+ return generated;
93
+ }
94
+ override async editorWithData(): Promise<TreeVisitor<any, ExecutionContext>> {
95
+ const state = this.state;
96
+ return new class extends TreeVisitor<Tree, ExecutionContext> {
97
+ override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
98
+ const path = (tree as SourceFile).sourcePath;
99
+ if (!state.java || !path || !isNodeDependencyInput(path, true)) return tree as R;
100
+ return (await state.java.editorWithData(0)).visit<R>(tree, ctx, parent);
101
+ }
102
+ }();
103
+ }
104
+ override async onComplete(ctx: ExecutionContext): Promise<void> { await this.state.java?.onComplete(ctx); }
105
+ }
106
+
107
+ /**
108
+ * The complete package.json change is one decision with the repository's npm/Yarn/pnpm lock.
109
+ * @see https://react.dev/blog/2025/02/14/sunsetting-create-react-app#how-to-migrate-to-a-build-tool
110
+ */
111
+ export class MigrateCraPackage extends Recipe {
112
+ override async editor() { return craFilesOnly(noopVisitor()); }
113
+ readonly name = 'org.openrewrite.react.cra-to-vite.migrate-package';
114
+ readonly displayName = 'Migrate CRA package configuration and native locks';
115
+ readonly description = 'Preflights CRA projects, prepares Vite/Vitest/SVGR dependencies and scripts, removes CRA-only defaults, and commits package.json with its native lock. Refused projects retain their scripts and dependencies.';
116
+ readonly landed = new Set<string>();
117
+ readonly renamedFiles = new Set<string>();
118
+ @Option({displayName: 'Vite version', description: 'Vite version range; defaults to ^7.0.0 (Node 20.19+).', required: false})
119
+ viteVersion?: string;
120
+ @Option({displayName: 'React plugin version', description: 'Compatible @vitejs/plugin-react version range; defaults to ^5.2.0.', required: false})
121
+ pluginReactVersion?: string;
122
+ constructor(options?: {viteVersion?: string; pluginReactVersion?: string}) { super(options); }
123
+ async recipeList(): Promise<Recipe[]> {
124
+ const tests = new Set<string>();
125
+ return [new PlanVitest(tests, true), new ApplyCraPackage({viteVersion: this.viteVersion, pluginReactVersion: this.pluginReactVersion}, tests, this.landed, this.renamedFiles)];
126
+ }
127
+ }
@@ -0,0 +1,41 @@
1
+ import {check, ExecutionContext, not, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {isVendoredOrBundled, JavaScriptParser, JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
3
+ import {J} from "@openrewrite/rewrite/java";
4
+ import {svgComponentName, svgImportNeedsReview} from "./svg-component";
5
+ import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
6
+
7
+ /** Component imports use SVGR's explicit query; ordinary SVG imports remain asset URLs. */
8
+ export class MigrateCraSvgImports extends CraScanningRecipe {
9
+ readonly name = "org.openrewrite.react.cra-to-vite.migrate-svg-imports";
10
+ readonly displayName = "Migrate CRA SVG component imports to Vite SVGR";
11
+ readonly description = "Changes `import {ReactComponent as Logo} from './logo.svg'` to `import Logo from './logo.svg?react'` in CRA client source. A combined URL/component import becomes two imports so both uses retain their meaning. Requires vite-plugin-svgr in the Vite configuration.";
12
+
13
+ async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
14
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
15
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
16
+ if (!acc.isViteClientSource(cu.sourcePath)) return cu;
17
+ let changed = false;
18
+ const statements: typeof cu.statements = [];
19
+ for (const rp of cu.statements) {
20
+ const statement = rp.element;
21
+ if (statement.kind !== JS.Kind.Import) { statements.push(rp); continue; }
22
+ const imp = statement as JS.Import;
23
+ const name = svgComponentName(imp);
24
+ if (!name || await svgImportNeedsReview(imp)) { statements.push(rp); continue; }
25
+ const module = imp.moduleSpecifier!.element as J.Literal;
26
+ const source = module.valueSource ? module.valueSource.slice(0, -1) + "?react" + module.valueSource.slice(-1) : JSON.stringify(module.value + "?react");
27
+ const parsed = await new JavaScriptParser().parseOne({text: `import ${name} from ${source};`, sourcePath: "svgr-import.ts"}) as JS.CompilationUnit;
28
+ const newImport = parsed.statements[0].element;
29
+ if (imp.importClause!.name) {
30
+ statements.push({...rp, element: {...imp, importClause: {...imp.importClause!, namedBindings: undefined}} as JS.Import});
31
+ statements.push({...rp, element: {...newImport, prefix: {...newImport.prefix, whitespace: "\n"}}});
32
+ } else {
33
+ statements.push({...rp, element: {...newImport, prefix: imp.prefix}});
34
+ }
35
+ changed = true;
36
+ }
37
+ return changed ? {...cu, statements} as JS.CompilationUnit : cu;
38
+ }
39
+ });
40
+ }
41
+ }
@@ -0,0 +1,376 @@
1
+ import {craScript} from './cra-script';
2
+ import {Cursor, ExecutionContext, noopVisitor, Recipe, SourceFile, Tree, TreeVisitor} from '@openrewrite/rewrite';
3
+ import {JavaScriptParser, JavaScriptVisitor, JS, raw, template} from '@openrewrite/rewrite/javascript';
4
+ import {J, isTextComment} from '@openrewrite/rewrite/java';
5
+ import {Json, appendElement, emptyArray, getMemberKeyName, isArray, jsonLiteral, membersOf, setAt, updateAt, valueAt} from '@openrewrite/rewrite/json';
6
+ import {subset} from 'semver';
7
+ import {CraProjects, CraScanningRecipe, VITE_CONFIG_NAMES} from './scan-cra-projects';
8
+ import {baseName, dirName, hasDependency, isPackageJson, joinPath, memberObject, nearestRoot, rootObject, stringValue, stringValues} from './shared';
9
+ import {craToViteBlockersTable} from './cra-blockers-table';
10
+ import {isNodeDependencyInput, JavaDependencyRecipe} from '../../util/java-recipe-proxy';
11
+ import {isIdentifierNamed} from '../../util/tree-search';
12
+ import {craFilesOnly} from './cra-file-gate';
13
+
14
+ // `.skip` and `.only` modifiers of a test API, which convert unchanged
15
+ const TEST_MODIFIERS = new Set(['skip', 'only']);
16
+ // These APIs differ in timer, snapshot, environment or matcher semantics and need review.
17
+ const REVIEW_APIS = new Set(['require', 'failing', 'each', 'getMockName', 'JEST_WORKER_ID', 'toMatchSnapshot', 'toMatchInlineSnapshot', 'toThrowErrorMatchingSnapshot', 'toThrowErrorMatchingInlineSnapshot']);
18
+ const SAFE_APIS = new Set(['fn', 'clearAllMocks', 'resetAllMocks', 'restoreAllMocks', 'isMockFunction']);
19
+ const HOOKS = new Set(['beforeAll', 'beforeEach', 'afterAll', 'afterEach']);
20
+ const TESTS = new Set(['test', 'it', ...HOOKS]);
21
+ const CONFIG = /^(?:vitest|jest)\.(?:config|workspace)\./;
22
+ const DEPENDENCIES = new Map([['vitest', '~4.0.18'], ['jsdom', '^26.1.0'], ['vite', '^7.0.0']]);
23
+
24
+ class TestProjects extends CraProjects {
25
+ readonly packages = new Map<string, {command?: string; compatible: boolean; installed: boolean; jestDom: boolean}>();
26
+ readonly unsafe = new Set<string>();
27
+ readonly unsafePaths = new Set<string>();
28
+ readonly jestDomPaths = new Set<string>();
29
+ readonly jestPaths = new Set<string>();
30
+ readonly eligible = new Set<string>();
31
+ readonly declaredTypes = new Map<string, string[]>();
32
+ }
33
+
34
+ function version(pkg: Json.Object, name: string): string | undefined {
35
+ return stringValue(valueAt(pkg, ['devDependencies', name])) ?? stringValue(valueAt(pkg, ['dependencies', name]));
36
+ }
37
+
38
+ function supports(pkg: Json.Object, name: string, range: string): boolean {
39
+ try {
40
+ return subset(version(pkg, name) ?? '', range);
41
+ } catch { return false; }
42
+ }
43
+
44
+ function supportsEngine(range: string | undefined): boolean {
45
+ try { return range !== undefined && subset(range, '^20.19 || ^22.12 || >=24'); }
46
+ catch { return false; }
47
+ }
48
+
49
+ /** Preflight is shared by dependency admission and source editing; no source changes occur during this scan. */
50
+ export class PlanVitest extends CraScanningRecipe {
51
+ private readonly ready: Set<string>;
52
+ readonly name: string = 'org.openrewrite.react.cra-to-vite.plan-vitest';
53
+ readonly displayName: string = 'Check Create React App tests for Vitest compatibility';
54
+ readonly description: string = 'Leaves packages with unsupported Jest usage or conflicting test configuration unchanged.';
55
+ constructor(readyOrOptions: Set<string> | {} = new Set<string>(), protected readonly integrated = false) {
56
+ super(readyOrOptions instanceof Set ? undefined : readyOrOptions);
57
+ this.ready = readyOrOptions instanceof Set ? readyOrOptions : new Set<string>();
58
+ }
59
+ override initialValue(): TestProjects { this.ready.clear(); return new TestProjects(); }
60
+ override async scanner(acc: TestProjects): Promise<TreeVisitor<any, ExecutionContext>> {
61
+ const cra = await super.scanner(acc);
62
+ const integrated = this.integrated;
63
+ const jestDomRange = integrated ? '>=5 <7' : '>=6 <7';
64
+ const js = new class extends JavaScriptVisitor<ExecutionContext> {
65
+ private path = '';
66
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext) {
67
+ this.path = cu.sourcePath;
68
+ if ((!integrated || baseName(cu.sourcePath) !== 'react-app-env.d.ts') && cu.prefix.comments.some(c => isTextComment(c) && /reference.*(?:jest|react-scripts)/.test(c.text))) acc.unsafePaths.add(this.path);
69
+ return super.visitJsCompilationUnit(cu, ctx);
70
+ }
71
+ override async visitIdentifier(id: J.Identifier, ctx: ExecutionContext) {
72
+ if (id.simpleName === 'jest') {
73
+ acc.jestPaths.add(this.path);
74
+ const parent = this.cursor.parentTree()?.value as J.MethodInvocation;
75
+ if (parent?.kind !== J.Kind.MethodInvocation || parent.select?.element !== id || !SAFE_APIS.has(parent.name.simpleName) || !!parent.typeParameters?.elements.length || (parent.name.simpleName === 'fn' && parent.arguments.elements.some(arg => arg.element.kind !== J.Kind.Empty))) acc.unsafePaths.add(this.path);
76
+ }
77
+ if (TESTS.has(id.simpleName)) {
78
+ const parent = this.cursor.parentTree()?.value;
79
+ const property = parent?.kind === J.Kind.FieldAccess && parent.name.element === id;
80
+ const call = parent?.kind === J.Kind.MethodInvocation && parent.name === id;
81
+ const selected = parent?.kind === J.Kind.MethodInvocation && parent.select?.element === id &&
82
+ TEST_MODIFIERS.has(parent.name.simpleName);
83
+ if (!property && !call && !selected) acc.unsafePaths.add(this.path);
84
+ }
85
+ if (REVIEW_APIS.has(id.simpleName)) acc.unsafePaths.add(this.path);
86
+ return super.visitIdentifier(id, ctx);
87
+ }
88
+ override async visitFieldAccess(field: J.FieldAccess, ctx: ExecutionContext) {
89
+ if (field.name.element.simpleName === 'getState' && isIdentifierNamed(field.target, 'expect')) acc.unsafePaths.add(this.path);
90
+ if (field.name.element.simpleName === 'mock') {
91
+ const parent = this.cursor.parentTree()?.value as J.FieldAccess;
92
+ if (parent?.kind !== J.Kind.FieldAccess || parent.target !== field) acc.unsafePaths.add(this.path);
93
+ }
94
+ return super.visitFieldAccess(field, ctx);
95
+ }
96
+ override async visitReturn(statement: J.Return, ctx: ExecutionContext) {
97
+ if (this.cursor.asArray().some(node => node?.kind === J.Kind.MethodInvocation && HOOKS.has(node.name.simpleName))) acc.unsafePaths.add(this.path);
98
+ return super.visitReturn(statement, ctx);
99
+ }
100
+ override async visitMethodInvocation(call: J.MethodInvocation, ctx: ExecutionContext) {
101
+ const select = call.select?.element;
102
+ const url = (call.arguments.elements[0]?.element as J.Literal | undefined)?.value;
103
+ if (!select && call.name.simpleName === 'fetch' && typeof url === 'string' && !/^[a-z][a-z0-9+.-]*:/i.test(url)) acc.unsafePaths.add(this.path);
104
+ if (call.name.simpleName === 'getState' && select && isIdentifierNamed(select, 'expect')) acc.unsafePaths.add(this.path);
105
+ const name = select?.kind === J.Kind.Identifier && TEST_MODIFIERS.has(call.name.simpleName) ?
106
+ (select as J.Identifier).simpleName : call.name.simpleName;
107
+ if (TESTS.has(name) && (!select || select.kind === J.Kind.Identifier && TEST_MODIFIERS.has(call.name.simpleName))) {
108
+ const callback = call.arguments.elements[HOOKS.has(name) ? 0 : 1]?.element;
109
+ const fn = callback?.kind === JS.Kind.ArrowFunction ? (callback as JS.ArrowFunction).lambda :
110
+ callback?.kind === JS.Kind.StatementExpression ? (callback as JS.StatementExpression).statement : callback;
111
+ const parameters = fn?.kind === J.Kind.Lambda ? (fn as J.Lambda).parameters.parameters :
112
+ fn?.kind === J.Kind.MethodDeclaration ? (fn as J.MethodDeclaration).parameters.elements : undefined;
113
+ if (!parameters || parameters.some(p => p.element.kind !== J.Kind.Empty) ||
114
+ (HOOKS.has(name) && fn?.kind === J.Kind.Lambda && (fn as J.Lambda).body.kind !== J.Kind.Block)) acc.unsafePaths.add(this.path);
115
+ }
116
+ return super.visitMethodInvocation(call, ctx);
117
+ }
118
+ override async visitLiteral(literal: J.Literal, ctx: ExecutionContext) {
119
+ if (literal.value === '@testing-library/jest-dom') {
120
+ acc.jestDomPaths.add(this.path);
121
+ const parent = this.cursor.parentTree()?.value as JS.Import;
122
+ if (parent?.kind !== JS.Kind.Import || parent.importClause) acc.unsafePaths.add(this.path);
123
+ }
124
+ if (typeof literal.value === 'string' && (/^@jest\//.test(literal.value) || /^@testing-library\/jest-dom\/(?!vitest$)/.test(literal.value) && !(integrated && literal.value === '@testing-library/jest-dom/extend-expect') || /jest-environment|jest-extended|enzyme|react-test-renderer/.test(literal.value))) acc.unsafePaths.add(this.path);
125
+ return super.visitLiteral(literal, ctx);
126
+ }
127
+ }();
128
+ return craFilesOnly(new class extends TreeVisitor<Tree, ExecutionContext> {
129
+ override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
130
+ await cra.visit(tree, ctx, parent);
131
+ const path = (tree as SourceFile).sourcePath;
132
+ if (tree.kind === Json.Kind.Document && isPackageJson(path)) {
133
+ const pkg = rootObject(tree as Json.Document);
134
+ if (pkg) acc.packages.set(dirName(path), {
135
+ command: stringValue(valueAt(pkg, ['scripts', 'test']))?.trim(),
136
+ compatible: !valueAt(pkg, ['jest']) &&
137
+ (integrated || !valueAt(pkg, ['engines', 'node']) || supportsEngine(stringValue(valueAt(pkg, ['engines', 'node'])))) &&
138
+ !['jest', 'ts-jest', 'babel-jest', 'enzyme', '@craco/craco', 'react-app-rewired'].some(name => hasDependency(pkg, name)) &&
139
+ (!hasDependency(pkg, '@testing-library/jest-dom') || supports(pkg, '@testing-library/jest-dom', jestDomRange)) &&
140
+ (!hasDependency(pkg, 'vite') || supports(pkg, 'vite', '>=7 <8')) &&
141
+ (!hasDependency(pkg, 'vitest') || supports(pkg, 'vitest', '>=4.0.18 <4.1')) &&
142
+ (!hasDependency(pkg, 'jsdom') || supports(pkg, 'jsdom', '>=26 <27')) &&
143
+ (!hasDependency(pkg, '@types/node') || supports(pkg, '@types/node', '^20 || ^22 || >=24')) &&
144
+ (!hasDependency(pkg, 'canvas') || supports(pkg, 'canvas', '^3')),
145
+ jestDom: supports(pkg, '@testing-library/jest-dom', jestDomRange),
146
+ installed: supports(pkg, 'vitest', '>=4 <5') && supports(pkg, 'jsdom', '>=26 <27') && supports(pkg, 'vite', '>=7 <8')
147
+ });
148
+ if (pkg) acc.declaredTypes.set(dirName(path), [...new Set(['dependencies', 'devDependencies'].flatMap(section => {
149
+ const deps = memberObject(pkg, section);
150
+ return deps ? membersOf(deps).flatMap(member => {
151
+ const name = getMemberKeyName(member);
152
+ return name?.startsWith('@types/') && name !== '@types/jest' ? [name.slice('@types/'.length)] : [];
153
+ }) : [];
154
+ }))]);
155
+ }
156
+ if (tree.kind === Json.Kind.Document && /^tsconfig.*\.json$/.test(baseName(path))) {
157
+ const pkg = rootObject(tree as Json.Document);
158
+ const types = pkg && valueAt(pkg, ['compilerOptions', 'types']);
159
+ // An absent list automatically includes every installed @types package. Replacing that
160
+ // implicit set would silently drop unrelated ambient types, so leave it for review.
161
+ if ((!integrated && !types) || types && (!isArray(types) || stringValues(types).length !== types.values.length) || (pkg && (valueAt(pkg, ['extends']) || !integrated && (valueAt(pkg, ['compilerOptions', 'baseUrl']) || valueAt(pkg, ['compilerOptions', 'paths']))))) acc.unsafePaths.add(path);
162
+ }
163
+ if (/\.[cm]?[jt]sx?$/.test(path) && tree.kind !== JS.Kind.CompilationUnit) acc.unsafePaths.add(path);
164
+ if (tree.kind === JS.Kind.CompilationUnit) await js.visit(tree, ctx, parent);
165
+ return tree as R;
166
+ }
167
+ }());
168
+ }
169
+ protected prepare(acc: TestProjects): void {
170
+ for (const path of acc.unsafePaths) {
171
+ const owner = nearestRoot(acc.packageDirs, path);
172
+ if (owner !== undefined && (path.startsWith(joinPath(owner, 'src/')) || path === joinPath(owner, 'tsconfig.json'))) acc.unsafe.add(owner);
173
+ }
174
+ for (const root of acc.viteRoots) {
175
+ if (!acc.mayMigrate(root)) continue;
176
+ const pkg = acc.packages.get(root)!;
177
+ const command = pkg.command;
178
+ const paths = [...acc.paths].filter(path => nearestRoot(acc.packageDirs, path) === root);
179
+ if ([...acc.jestPaths, ...acc.jestDomPaths].some(path => nearestRoot(acc.packageDirs, path) === root && !path.startsWith(joinPath(root, 'src/')))) continue;
180
+ if ([...acc.jestDomPaths].some(path => nearestRoot(acc.packageDirs, path) === root) && !pkg.jestDom) continue;
181
+ if (!command || craScript(command)?.operation !== 'test' || !pkg.compatible || acc.unsafe.has(root) ||
182
+ paths.some(path => CONFIG.test(baseName(path)) || !this.integrated && VITE_CONFIG_NAMES.includes(baseName(path)) || /(^|\/)__mocks__\//.test(path) || path.endsWith('.snap')) ||
183
+ paths.filter(path => /^src\/setupTests\.[jt]sx?$/.test(path.slice(root ? root.length + 1 : 0))).length > 1) continue;
184
+ acc.eligible.add(root);
185
+ this.ready.add(root);
186
+ }
187
+ }
188
+ override async generate(acc: TestProjects, _ctx: ExecutionContext): Promise<SourceFile[]> { this.prepare(acc); return []; }
189
+ }
190
+
191
+ class AddVitestDependency extends JavaDependencyRecipe {
192
+ readonly landed = new Set<string>();
193
+ private readonly inputs: SourceFile[] = [];
194
+ readonly name: string;
195
+ readonly displayName: string;
196
+ readonly description = 'Adds a test dependency only to Create React App packages admitted by the Vitest preflight.';
197
+ constructor(private readonly dependencyName: string, version: string, private readonly ready: Set<string>) {
198
+ super('org.openrewrite.javascript.AddDependency', {packageName: dependencyName, version, scope: 'devDependencies', onlyIfDeclaring: ['react-scripts']}, true);
199
+ const name = dependencyName;
200
+ this.name = `org.openrewrite.react.cra-to-vite.add-${name}`;
201
+ this.displayName = `Add ${name} for Create React App tests`;
202
+ }
203
+ override async editor() { return craFilesOnly(await super.editor()); }
204
+ protected override scanned(manifest: SourceFile): boolean {
205
+ return !isPackageJson(manifest.sourcePath) || this.ready.has(dirName(manifest.sourcePath));
206
+ }
207
+ override initialValue(): number {
208
+ this.inputs.length = 0;
209
+ this.landed.clear();
210
+ return super.initialValue();
211
+ }
212
+ override async scanner(): Promise<TreeVisitor<any, ExecutionContext>> {
213
+ const inputs = this.inputs;
214
+ return craFilesOnly(new class extends TreeVisitor<Tree, ExecutionContext> {
215
+ override async visit<R extends Tree>(tree: Tree): Promise<R | undefined> {
216
+ const source = tree as SourceFile;
217
+ if (source.sourcePath && isNodeDependencyInput(source.sourcePath, true)) inputs.push(source);
218
+ return tree as R;
219
+ }
220
+ }());
221
+ }
222
+ override async generate(acc: number, ctx: ExecutionContext): Promise<SourceFile[]> {
223
+ // All scanners finish before any generator. Admission is known only now.
224
+ const scanner = await super.scanner(acc);
225
+ for (const input of this.inputs) await scanner.visit(input, ctx);
226
+ const generated = await super.generate(acc, ctx);
227
+ const editor = await this.java.editorWithData(acc);
228
+ for (const input of this.inputs) {
229
+ if (input.kind !== Json.Kind.Document || !isPackageJson(input.sourcePath) || !this.ready.has(dirName(input.sourcePath))) continue;
230
+ const edited = await editor.visit<Json.Document>(input, ctx);
231
+ const pkg = edited && rootObject(edited);
232
+ if (pkg && hasDependency(pkg, this.dependencyName)) this.landed.add(dirName(input.sourcePath));
233
+ }
234
+ return generated;
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Converts `react-scripts test` to `vitest`, using a separate jsdom config and explicit `vi` imports.
240
+ * Dependencies must already support Vitest 4; the standalone composite installs them first.
241
+ * @see https://v4.vitest.dev/guide/migration.html#migrating-from-jest
242
+ */
243
+ export class MigrateCraTestsToVitestSources extends PlanVitest {
244
+ private dependencyRoots?: readonly ReadonlySet<string>[];
245
+
246
+ withDependencyRoots(...roots: ReadonlySet<string>[]): this { this.dependencyRoots = roots; return this; }
247
+ private renamedFiles: ReadonlySet<string> = new Set();
248
+ withRenamedFiles(paths: ReadonlySet<string>): this { this.renamedFiles = paths; return this; }
249
+ override readonly name = 'org.openrewrite.react.cra-to-vite.migrate-tests-to-vitest-sources';
250
+ override readonly displayName = 'Migrate Create React App test sources to Vitest';
251
+ override readonly description = 'Replaces supported `react-scripts test` scripts with Vitest, configures jsdom and setup files, and converts safe global `jest` calls to imported `vi` calls. Conflicting configuration and unsupported mocking leave the package unchanged.';
252
+ private readonly blockers = craToViteBlockersTable();
253
+
254
+ override async generate(acc: TestProjects, ctx: ExecutionContext): Promise<SourceFile[]> {
255
+ this.prepare(acc);
256
+ for (const root of acc.eligible) {
257
+ if (!acc.packages.get(root)!.installed && !this.dependencyRoots?.every(roots => roots.has(root))) acc.eligible.delete(root);
258
+ }
259
+ for (const root of acc.roots) {
260
+ if (!acc.eligible.has(root) && acc.packages.get(root)?.command?.includes('react-scripts test')) {
261
+ this.blockers.insertRow(ctx, {filePath: joinPath(root, 'package.json'), category: 'vitest',
262
+ detail: 'Vitest migration skipped: unsupported Jest usage, existing configuration, custom or implicit TypeScript ambient types, incompatible dependency versions or missing Vitest dependencies.',
263
+ nextStep: 'Review https://v4.vitest.dev/guide/migration.html#migrating-from-jest before replacing the CRA test runner.'});
264
+ }
265
+ }
266
+ const generated: SourceFile[] = [];
267
+ const parser = new JavaScriptParser({ctx});
268
+ for (const root of acc.eligible) {
269
+ let setup = ['js', 'jsx', 'ts', 'tsx'].map(ext => `src/setupTests.${ext}`).find(path => acc.has(root, path));
270
+ if (setup && this.renamedFiles.has(joinPath(root, setup))) setup += 'x';
271
+ const testOptions = `test: {environment: 'jsdom', globals: true, include: ['src/**/*.{test,spec}.{js,jsx,ts,tsx}', 'src/**/__tests__/**/*.{js,jsx,ts,tsx}'], setupFiles: [${setup ? `'./${setup}'` : ''}], mockReset: true, sequence: {hooks: 'list'}},`;
272
+ let text = `import {defineConfig} from 'vitest/config';
273
+ import {transformWithEsbuild} from 'vite';
274
+
275
+ export default defineConfig({
276
+ plugins: [{
277
+ name: 'cra-test-jsx',
278
+ enforce: 'pre',
279
+ transform(code, id) {
280
+ const file = id.split('?')[0];
281
+ if (file.includes('/src/') && file.endsWith('.js')) {
282
+ return transformWithEsbuild(code, file, {loader: 'jsx', jsx: 'automatic'});
283
+ }
284
+ },
285
+ }],
286
+ esbuild: {jsx: 'automatic'},
287
+ ${testOptions}
288
+ });
289
+ `;
290
+ if (this.integrated) text = `import {defineConfig, mergeConfig} from 'vitest/config';
291
+ import viteConfig from './vite.config';
292
+
293
+ export default mergeConfig(viteConfig, defineConfig({
294
+ ${testOptions}
295
+ }));
296
+ `;
297
+ generated.push(await parser.parseOne({text, sourcePath: joinPath(root, acc.has(root, 'tsconfig.json') ? 'vitest.config.ts' : 'vitest.config.js')}));
298
+ }
299
+ return generated;
300
+ }
301
+ override async editorWithData(acc: TestProjects): Promise<TreeVisitor<any, ExecutionContext>> {
302
+ const integrated = this.integrated;
303
+ const admitted = (path: string) => {
304
+ const root = nearestRoot(acc.packageDirs, path);
305
+ return root !== undefined && acc.eligible.has(root);
306
+ };
307
+ const js = new class extends JavaScriptVisitor<ExecutionContext> {
308
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext) {
309
+ return admitted(cu.sourcePath) && cu.sourcePath.startsWith(joinPath(nearestRoot(acc.packageDirs, cu.sourcePath)!, 'src/')) ? super.visitJsCompilationUnit(cu, ctx) : cu;
310
+ }
311
+ override async visitMethodInvocation(call: J.MethodInvocation, ctx: ExecutionContext) {
312
+ const updated = await super.visitMethodInvocation(call, ctx) as J.MethodInvocation;
313
+ const target = updated.select?.element;
314
+ if (!target || !isIdentifierNamed(target, 'jest') || !SAFE_APIS.has(updated.name.simpleName)) return updated;
315
+ const replacement = template`vi.${raw(updated.name.simpleName)}(${updated.arguments})`.configure({
316
+ context: ["import {vi} from 'vitest';"], dependencies: {vitest: '4.0.0'}
317
+ });
318
+ const result = await replacement.apply(updated, this.cursor, {bindings: await replacement.resolveBindings(this)});
319
+ return result ? {...result, prefix: updated.prefix} : updated;
320
+ }
321
+ override async visitLiteral(literal: J.Literal, ctx: ExecutionContext) {
322
+ if (!(literal.value === '@testing-library/jest-dom' || integrated && literal.value === '@testing-library/jest-dom/extend-expect') || this.cursor.parentTree()?.value.kind !== JS.Kind.Import) return super.visitLiteral(literal, ctx);
323
+ return {...literal, value: '@testing-library/jest-dom/vitest', valueSource: literal.valueSource?.replace(String(literal.value), '@testing-library/jest-dom/vitest')};
324
+ }
325
+ }();
326
+ return new class extends TreeVisitor<Tree, ExecutionContext> {
327
+ override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
328
+ const path = (tree as SourceFile).sourcePath;
329
+ if (!admitted(path)) return tree as R;
330
+ if (tree.kind === Json.Kind.Document && /^tsconfig.*\.json$/.test(baseName(path))) {
331
+ const original = tree as Json.Document;
332
+ if (integrated && valueAt(rootObject(original)!, ['compilerOptions', 'types']) === undefined) {
333
+ const root = nearestRoot(acc.packageDirs, path)!;
334
+ const names = [...acc.declaredTypes.get(root) ?? [], 'vite/client', 'vitest/globals'];
335
+ const array = [...new Set(names)].reduce((array, name) => appendElement(array, jsonLiteral(name)), emptyArray());
336
+ return setAt(original, ['compilerOptions', 'types'], array, {createMissing: true}) as unknown as R;
337
+ }
338
+ const doc = updateAt(tree as Json.Document, ['compilerOptions', 'types'], value => {
339
+ const types = value as Json.Array;
340
+ const entries = stringValues(types);
341
+ if (entries.includes('jest')) {
342
+ return {...types, values: types.values.map(rp => stringValue(rp.element) === 'jest' ?
343
+ {...rp, element: {...rp.element, value: 'vitest/globals', source: '"vitest/globals"'} as Json.Literal} : rp)};
344
+ }
345
+ return entries.includes('vitest/globals') ? types : appendElement(types, jsonLiteral('vitest/globals'));
346
+ });
347
+ return doc as unknown as R;
348
+ }
349
+ if (tree.kind === Json.Kind.Document && isPackageJson(path)) {
350
+ if (integrated) return tree as R; // Scripts and dependencies were committed together by the native transaction.
351
+ const doc = tree as Json.Document;
352
+ const command = stringValue(valueAt(rootObject(doc)!, ['scripts', 'test']))!;
353
+ return setAt(doc, ['scripts', 'test'], jsonLiteral(/--watchAll/.test(command) ? 'vitest run' : 'vitest')) as unknown as R;
354
+ }
355
+ return tree.kind === JS.Kind.CompilationUnit ? js.visit(tree as J, ctx, parent) as Promise<R | undefined> : tree as R;
356
+ }
357
+ }();
358
+ }
359
+ }
360
+
361
+ /**
362
+ * `react-scripts test --watchAll=false` becomes `vitest run` after native dependency installation.
363
+ * Requires Node 20.19+ (the Vite 7 baseline); jsdom 26 supports Node 20 without jsdom 27's higher patch floor.
364
+ * @see https://v4.vitest.dev/guide/migration.html#migrating-from-jest
365
+ */
366
+ export class MigrateCraTestsToVitest extends Recipe {
367
+ override async editor() { return craFilesOnly(noopVisitor()); }
368
+ readonly name = 'org.openrewrite.react.cra-to-vite.migrate-tests-to-vitest';
369
+ readonly displayName = 'Migrate Create React App tests to Vitest';
370
+ readonly description = 'Installs Vitest 4, jsdom 26 and Vite 7 and migrates supported Create React App tests with a separate Vitest config. Packages with conflicting test configuration or unsupported Jest mocking are left unchanged. Requires Node 20.19 or later.';
371
+ async recipeList(): Promise<Recipe[]> {
372
+ const ready = new Set<string>();
373
+ const dependencies = [...DEPENDENCIES].map(([name, version]) => new AddVitestDependency(name, version, ready));
374
+ return [new PlanVitest(ready), ...dependencies, new MigrateCraTestsToVitestSources().withDependencyRoots(...dependencies.map(recipe => recipe.landed))];
375
+ }
376
+ }
@@ -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 entry = acc.firstExisting(root, ENTRY_FILES);
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;