@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
@@ -1,8 +1,7 @@
1
- import {ExecutionContext, Option, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
- import {Json, jsonLiteral, JsonVisitor, removeAt, setAt} from "@openrewrite/rewrite/json";
3
- import {
4
- hasDependency, memberObject, newMemberPosition, runsOnVite, isPackageJson, rootObject, scriptsKeepReactScripts, REACT_SCRIPTS, VITE, VITE_PLUGIN_REACT
5
- } from "./shared";
1
+ import {ExecutionContext, Option, SourceFile} from "@openrewrite/rewrite";
2
+ import {JavaDependencyRecipe} from "../../util/java-recipe-proxy";
3
+ import {getMemberKeyName, Json, membersOf} from "@openrewrite/rewrite/json";
4
+ import {hasDependency, memberObject, runsOnVite, isPackageJson, rootObject, stringValue, VITE, VITE_PLUGIN_REACT} from "./shared";
6
5
 
7
6
  /**
8
7
  * Adds `vite` and `@vitejs/plugin-react` to `devDependencies` of a package that depends on `react-scripts`,
@@ -13,16 +12,15 @@ import {
13
12
  * ```
14
13
  *
15
14
  * The default versions are a peer-consistent pair that both need Node 20.19 or later. `react-scripts` stays
16
- * while a script such as `test` still runs it, because it provides Jest. The `eject` script does not count, and
17
- * `UpdateReactScriptsScripts` removes it. A package that `craco`, `react-app-rewired` or a wrapped `start` or
18
- * `build` script still depends on `react-scripts` is left to the finders.
15
+ * while a script such as `test` still runs it, because it provides Jest. The `eject` script also retains the dependency until script migration removes it.
16
+ * Packages using `craco`, `react-app-rewired` or wrapped `start` or `build` scripts are left to the finders.
19
17
  *
20
18
  * @see https://react.dev/blog/2025/02/14/sunsetting-create-react-app#how-to-migrate-to-a-build-tool
21
19
  */
22
- export class ReplaceReactScriptsDependency extends Recipe {
20
+ export class ReplaceReactScriptsDependency extends JavaDependencyRecipe {
23
21
  readonly name = "org.openrewrite.react.cra-to-vite.replace-react-scripts-dependency";
24
22
  readonly displayName = "Replace `react-scripts` dependency with Vite";
25
- readonly description = "Adds `vite` and `@vitejs/plugin-react` as dev dependencies of projects that depend on `react-scripts`, and removes `react-scripts` unless a script other than `eject` still invokes it (for example `react-scripts test`, which the stock Create React App template keeps, so the dependency usually stays until the tests move to Vitest). Packages that use `craco`, `react-app-rewired` or wrapped `start` or `build` scripts are left unchanged. The lock file is not regenerated; run your package manager afterwards.";
23
+ readonly description = "Adds `vite` and `@vitejs/plugin-react` together as dev dependencies and removes `react-scripts` or scoped forks only when no script still invokes them. Regenerates the lock natively; declined dependency edits leave the manifest and lock consistent. Wrapped CRA packages are left unchanged.";
26
24
 
27
25
  @Option({
28
26
  displayName: "Vite version",
@@ -40,32 +38,53 @@ export class ReplaceReactScriptsDependency extends Recipe {
40
38
  })
41
39
  pluginReactVersion?: string;
42
40
 
43
- constructor(options?: { viteVersion?: string; pluginReactVersion?: string }) {
44
- super(options);
45
- this.viteVersion ??= "^7.0.0";
46
- this.pluginReactVersion ??= "^5.2.0";
41
+ /** Package directories (with a trailing slash, or an empty string at root) accepted by the native engine. Known after generate. */
42
+ readonly landed = new Set<string>();
43
+ private readonly manifests: Json.Document[] = [];
44
+
45
+ constructor(options?: { viteVersion?: string; pluginReactVersion?: string; addSvgr?: boolean }) {
46
+ const {viteVersion = "^7.0.0", pluginReactVersion = "^5.2.0", addSvgr = false} = options ?? {};
47
+ super("org.openrewrite.react.migrate.ReplaceReactScriptsDependency", {viteVersion, pluginReactVersion, addSvgr}, true);
48
+ this.viteVersion = viteVersion;
49
+ this.pluginReactVersion = pluginReactVersion;
50
+ this.addSvgr = addSvgr;
47
51
  }
48
52
 
49
- async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
50
- const viteVersion = this.viteVersion!;
51
- const pluginVersion = this.pluginReactVersion!;
52
- return new class extends JsonVisitor<ExecutionContext> {
53
- protected override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
54
- const pkg = rootObject(doc);
55
- if (!pkg || !isPackageJson(doc.sourcePath) || !runsOnVite(pkg)) return doc;
53
+ @Option({displayName: "Add SVGR", description: "Also add `vite-plugin-svgr` when the caller migrates SVG ReactComponent imports in this package.", required: false})
54
+ addSvgr?: boolean;
55
+
56
+ override initialValue(): number {
57
+ this.landed.clear();
58
+ this.manifests.length = 0;
59
+ return super.initialValue();
60
+ }
61
+
62
+ protected override scanned(manifest: SourceFile): boolean {
63
+ if (manifest.kind !== Json.Kind.Document || !isPackageJson(manifest.sourcePath)) return true;
64
+ const pkg = rootObject(manifest as Json.Document);
65
+ if (pkg && runsOnVite(pkg)) this.manifests.push(manifest as Json.Document);
66
+ return true;
67
+ }
56
68
 
57
- const position = newMemberPosition(memberObject(pkg, "devDependencies"));
58
- const parentPosition = newMemberPosition(pkg);
59
- let updated = doc;
60
- for (const [name, version] of [[VITE, viteVersion], [VITE_PLUGIN_REACT, pluginVersion]]) {
61
- if (hasDependency(pkg, name)) continue;
62
- updated = setAt(updated, ["devDependencies", name], jsonLiteral(version), {createMissing: true, position, parentPosition});
63
- }
64
- if (!scriptsKeepReactScripts(pkg)) {
65
- for (const section of ["dependencies", "devDependencies"]) updated = removeAt(updated, [section, REACT_SCRIPTS]);
66
- }
67
- return updated;
69
+ override async generate(acc: number, ctx: ExecutionContext): Promise<SourceFile[]> {
70
+ const generated = await super.generate(acc, ctx);
71
+ const editor = await this.java.editorWithData(acc);
72
+ for (const manifest of this.manifests) {
73
+ const edited = await editor.visit<Json.Document>(manifest, ctx);
74
+ const pkg = edited && rootObject(edited);
75
+ const before = rootObject(manifest)!;
76
+ const scripts = memberObject(before, "scripts");
77
+ const keepCra = scripts && membersOf(scripts).some(member => stringValue(member.value)?.includes("react-scripts"));
78
+ const removed = keepCra || ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"].every(section => {
79
+ const deps = pkg && memberObject(pkg, section);
80
+ return !deps || membersOf(deps).every(member => !/^(?:@[^/]+\/)?react-scripts$/.test(getMemberKeyName(member) ?? ""));
81
+ });
82
+ // A warning-only result from a declined removal is not a landed dependency edit.
83
+ if (edited !== manifest && removed && pkg && hasDependency(pkg, VITE) && hasDependency(pkg, VITE_PLUGIN_REACT) &&
84
+ (!this.addSvgr || hasDependency(pkg, "vite-plugin-svgr"))) {
85
+ this.landed.add(manifest.sourcePath.slice(0, -"package.json".length));
68
86
  }
69
- };
87
+ }
88
+ return generated;
70
89
  }
71
90
  }
@@ -0,0 +1,41 @@
1
+ import {isBuiltin} from 'node:module';
2
+ import {satisfies, valid, validRange} from 'semver';
3
+ import {NodeResolutionResult, NodeResolutionResultQueries} from '@openrewrite/rewrite/javascript';
4
+
5
+ /** Select an installed version only when the original requests establish ordinary semver provenance. */
6
+ export function originalCraDependencyVersion(
7
+ resolution: NodeResolutionResult | undefined,
8
+ packageName: string,
9
+ ): string | undefined {
10
+ if (!resolution?.resolvedDependencies || isBuiltin(packageName) || packageName.startsWith('node:')) {
11
+ return undefined;
12
+ }
13
+ const installed = NodeResolutionResultQueries.getAllResolvedVersions(resolution, packageName);
14
+ const versions = new Set(installed.map(dependency => dependency.version));
15
+ if (versions.size !== 1) return undefined;
16
+ const version = installed[0].version;
17
+ if (!version || !valid(version) || !/^\d/.test(version) || version.trim() !== version) return undefined;
18
+
19
+ let hasProvenance = false;
20
+ // Inspect every original request: a semver-looking fork can share the registry package's version.
21
+ for (const owner of [resolution, ...resolution.resolvedDependencies]) {
22
+ for (const scope of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies', 'bundledDependencies'] as const) {
23
+ const requests = scope === 'bundledDependencies'
24
+ ? ('bundledDependencies' in owner ? owner.bundledDependencies : undefined)
25
+ : owner[scope];
26
+ for (const request of requests ?? []) {
27
+ const targetsAlias = request.versionConstraint === `npm:${packageName}` ||
28
+ request.versionConstraint?.startsWith(`npm:${packageName}@`);
29
+ if (request.name !== packageName && request.resolved?.name !== packageName && !targetsAlias) continue;
30
+ if (request.name !== packageName || !request.versionConstraint?.trim() ||
31
+ !validRange(request.versionConstraint) ||
32
+ !satisfies(version, request.versionConstraint) ||
33
+ (request.resolved && (request.resolved.name !== packageName || request.resolved.version !== version))) {
34
+ return undefined;
35
+ }
36
+ hasProvenance = true;
37
+ }
38
+ }
39
+ }
40
+ return hasProvenance ? version : undefined;
41
+ }
@@ -1,10 +1,16 @@
1
1
  import {ExecutionContext, ScanningRecipe, Tree, TreeVisitor} from "@openrewrite/rewrite";
2
- import {Json} from "@openrewrite/rewrite/json";
2
+ import {Json, valueAt} from "@openrewrite/rewrite/json";
3
3
  import {PlainText} from "@openrewrite/rewrite/text";
4
- import {baseName, dirName, isCraPackage, runsOnVite, nearestRoot, isPackageJson, joinPath, rootObject} from "./shared";
4
+ import {findNodeResolutionResult, JS} from "@openrewrite/rewrite/javascript";
5
+ import {satisfies, valid, validRange} from 'semver';
6
+ import {craFilesOnly} from './cra-file-gate';
7
+ import {svgComponentName} from "./svg-component";
8
+ import {baseName, dirName, isCraPackage, runsOnVite, nearestRoot, isPackageJson, joinPath, rootObject, stringValue} from "./shared";
5
9
 
6
10
  /** What the recipes that add or move files need to know about the whole repository before they edit it. */
7
11
  export class CraProjects {
12
+ /** Optional admission decision populated before generators run, after all scanners have completed. */
13
+ allowedRoots?: ReadonlySet<string>;
8
14
  /** Directories of the `package.json` files that Create React App built; `''` is the repository root. */
9
15
  readonly roots = new Set<string>();
10
16
  /** The subset of `roots` whose `start` and `build` will run on Vite, the only ones the edit recipes change. */
@@ -13,8 +19,11 @@ export class CraProjects {
13
19
  readonly packageDirs = new Set<string>();
14
20
  /** Every source path in the repository, to tell whether a file already exists. */
15
21
  readonly paths = new Set<string>();
22
+ readonly svgComponentFiles = new Set<string>();
16
23
  /** The `public/index.html` text of each directory. */
17
24
  readonly indexHtml = new Map<string, string>();
25
+ /** Original manifests used to carry CRA's configuration into generated files. */
26
+ readonly configSettings = new Map<string, {homepage?: string; proxy?: string; reactVersion?: string}>();
18
27
 
19
28
  /**
20
29
  * True when the file belongs to a Create React App package: the nearest `package.json` above it, not any
@@ -28,13 +37,27 @@ export class CraProjects {
28
37
  /** True when the file belongs to a package whose `start` and `build` will run on Vite, so the edit recipes may change it. */
29
38
  isViteFile(sourcePath: string): boolean {
30
39
  const owner = nearestRoot(this.packageDirs, sourcePath);
31
- return owner !== undefined && this.viteRoots.has(owner);
40
+ return owner !== undefined && this.mayMigrate(owner);
32
41
  }
33
42
 
34
43
  /** True when the file is client code that CRA bundled: below the `src/` of a package that runs on Vite. */
35
44
  isViteClientSource(sourcePath: string): boolean {
36
45
  const owner = nearestRoot(this.packageDirs, sourcePath);
37
- return owner !== undefined && this.viteRoots.has(owner) && sourcePath.startsWith(joinPath(owner, "src/"));
46
+ return owner !== undefined && this.mayMigrate(owner) && sourcePath.startsWith(joinPath(owner, "src/"));
47
+ }
48
+
49
+ /** True when the file is client code (see isViteClientSource) of the package rooted at `root`. */
50
+ isClientSourceOf(root: string | undefined, sourcePath: string): boolean {
51
+ return nearestRoot(this.packageDirs, sourcePath) === root && this.isViteClientSource(sourcePath);
52
+ }
53
+
54
+ /** True when some client source of the package rooted at `root` imports an SVG component. */
55
+ usesSvgr(root: string | undefined): boolean {
56
+ return [...this.svgComponentFiles].some(path => this.isClientSourceOf(root, path));
57
+ }
58
+
59
+ mayMigrate(root: string): boolean {
60
+ return this.viteRoots.has(root) && (this.allowedRoots === undefined || this.allowedRoots.has(root));
38
61
  }
39
62
 
40
63
  has(root: string, name: string): boolean {
@@ -61,9 +84,23 @@ export function scanCraProjects(acc: CraProjects): TreeVisitor<any, ExecutionCon
61
84
  const sourcePath = (tree as { sourcePath?: string }).sourcePath;
62
85
  if (sourcePath === undefined) return tree as R;
63
86
  acc.paths.add(sourcePath);
87
+ if (tree.kind === JS.Kind.CompilationUnit && (tree as JS.CompilationUnit).statements.some(rp => {
88
+ if (rp.element.kind !== JS.Kind.Import) return false;
89
+ const imp = rp.element as JS.Import;
90
+ const path = (imp.moduleSpecifier?.element as {value?: unknown} | undefined)?.value;
91
+ return !!svgComponentName(imp) || typeof path === "string" && path.endsWith(".svg?react");
92
+ })) acc.svgComponentFiles.add(sourcePath);
64
93
  if (tree.kind === Json.Kind.Document && isPackageJson(sourcePath)) {
65
94
  acc.packageDirs.add(dirName(sourcePath));
66
95
  const pkg = rootObject(tree as Json.Document);
96
+ const resolution = findNodeResolutionResult(tree as Json.Document);
97
+ const react = [...resolution?.dependencies ?? [], ...resolution?.devDependencies ?? []].find(dep => dep.name === 'react');
98
+ const declared = pkg && (stringValue(valueAt(pkg, ['dependencies', 'react'])) ?? stringValue(valueAt(pkg, ['devDependencies', 'react'])));
99
+ const resolved = react?.resolved?.name === 'react' && react.resolved.version;
100
+ if (pkg) acc.configSettings.set(dirName(sourcePath), {
101
+ homepage: stringValue(valueAt(pkg, ["homepage"])), proxy: stringValue(valueAt(pkg, ["proxy"])),
102
+ reactVersion: resolved && valid(resolved) && (!declared || !validRange(declared) || satisfies(resolved, declared)) ? resolved : declared
103
+ });
67
104
  if (pkg && isCraPackage(pkg)) acc.roots.add(dirName(sourcePath));
68
105
  if (pkg && runsOnVite(pkg)) acc.viteRoots.add(dirName(sourcePath));
69
106
  } else if (tree.kind === PlainText.Kind.PlainText && indexHtmlRoot(sourcePath) !== undefined) {
@@ -76,11 +113,25 @@ export function scanCraProjects(acc: CraProjects): TreeVisitor<any, ExecutionCon
76
113
 
77
114
  /** A recipe that scans the whole repository for Create React App packages. Finders use `isCraFile`, edits `isViteFile`. */
78
115
  export abstract class CraScanningRecipe extends ScanningRecipe<CraProjects> {
116
+ // Keep the framework's accumulator delegate, but expose its file gate at PrepareRecipe time too.
117
+ override async editor() { return craFilesOnly(await super.editor()); }
118
+ private allowedRoots?: ReadonlySet<string>;
119
+
120
+ /** Gate a composite step on a shared, later-populated native dependency decision. Standalone steps are unrestricted. */
121
+ restrictTo(roots: ReadonlySet<string>): this {
122
+ this.allowedRoots = roots;
123
+ return this;
124
+ }
125
+
79
126
  initialValue(): CraProjects {
80
- return new CraProjects();
127
+ const acc = new CraProjects();
128
+ acc.allowedRoots = this.allowedRoots;
129
+ return acc;
81
130
  }
82
131
 
83
132
  async scanner(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
84
- return scanCraProjects(acc);
133
+ // PrepareRecipe asks for a scanner with no accumulator to infer its tree gate.
134
+ if (acc) acc.allowedRoots = this.allowedRoots;
135
+ return craFilesOnly(scanCraProjects(acc));
85
136
  }
86
137
  }
@@ -1,3 +1,4 @@
1
+ import {isStartOrBuildScript} from './cra-script';
1
2
  import {elementsOf, findMember, getMemberKeyName, isLiteral, isObject, Json, membersOf, valueAt} from "@openrewrite/rewrite/json";
2
3
 
3
4
  export const REACT_SCRIPTS = "react-scripts";
@@ -65,29 +66,38 @@ export function scriptsUseReactScripts(pkg: Json.Object): boolean {
65
66
 
66
67
  /** A `package.json` that Create React App built: `react-scripts` is a dependency. */
67
68
  export function isCraPackage(pkg: Json.Object): boolean {
68
- return hasDependency(pkg, REACT_SCRIPTS);
69
+ return reactScriptsDependencies(pkg).length > 0;
70
+ }
71
+
72
+ /** Scoped forks keep CRA's command and project layout. */
73
+ export function reactScriptsDependencies(pkg: Json.Object): string[] {
74
+ return DEPENDENCY_SECTIONS.flatMap(section => {
75
+ const dependencies = memberObject(pkg, section);
76
+ return dependencies ? membersOf(dependencies).flatMap(m => {
77
+ const name = getMemberKeyName(m);
78
+ return name && /^(?:@[^/]+\/)?react-scripts$/.test(name) ? [name] : [];
79
+ }) : [];
80
+ });
69
81
  }
70
82
 
71
83
  /** Tools that wrap or replace `react-scripts`, and which Vite does not replace. */
72
84
  const WRAPPER_DEPENDENCIES = ["@craco/craco", "craco", "react-app-rewired"];
73
85
  const WRAPPER_COMMAND = /(^|[\s&;|])(craco|react-app-rewired)(\s|$)/;
86
+ const VITE_SCRIPT = /^(?:(?:tsc --noEmit|node scripts\/vite-typecheck\.cjs) && )?vite(?: build)?(?: --(?:host|base|outDir) "[\w./:@%+ -]+"| --port \d+)*$/;
74
87
  const START_OR_BUILD = /(^|[\s&;|])react-scripts\s+(start|build)(\s|$)/;
75
- /** The only commands the migration rewrites. */
76
- export const EXACT_START_OR_BUILD = /^react-scripts (start|build)$/;
77
88
 
78
- /**
79
- * True when the package's `start` and `build` will run on Vite once the migration has edited it: it is a Create
80
- * React App package that neither depends on `craco` or `react-app-rewired` nor has a script that wraps those or
81
- * `react-scripts start|build` (`cross-env PORT=4000 react-scripts start`, `react-scripts build --profile`).
82
- * Such a package is only found by the finders; editing it would leave `start` or `build` without a working tool.
83
- */
89
+ /** Admit standard CRA commands and literal host/port/base/output controls; custom wrappers stay for review. */
84
90
  export function runsOnVite(pkg: Json.Object): boolean {
85
91
  if (!isCraPackage(pkg) || WRAPPER_DEPENDENCIES.some(name => hasDependency(pkg, name))) return false;
86
92
  const scripts = memberObject(pkg, "scripts");
87
93
  return !scripts || membersOf(scripts).every(m => {
88
94
  const command = stringValue(m.value)?.trim();
95
+ // Custom entry scripts can load react-scripts internally, e.g. responsive-viewer's scripts/build.js.
96
+ const name = getMemberKeyName(m);
97
+ if ((name === "start" || name === "build") && command &&
98
+ !isStartOrBuildScript(command) && !VITE_SCRIPT.test(command)) return false;
89
99
  return command === undefined || (!WRAPPER_COMMAND.test(command) &&
90
- (!START_OR_BUILD.test(command) || EXACT_START_OR_BUILD.test(command)));
100
+ (!START_OR_BUILD.test(command) || isStartOrBuildScript(command)));
91
101
  });
92
102
  }
93
103
 
@@ -0,0 +1,39 @@
1
+ import {JS} from "@openrewrite/rewrite/javascript";
2
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
3
+ import {TreePrinters} from '@openrewrite/rewrite';
4
+
5
+ export function importsSvgComponent(imp: JS.Import): boolean {
6
+ const module = imp.moduleSpecifier?.element as J.Literal | undefined;
7
+ const bindings = imp.importClause?.namedBindings;
8
+ if (typeof module?.value !== 'string' || !module.value.endsWith('.svg') || bindings?.kind !== JS.Kind.NamedImports) return false;
9
+ return (bindings as JS.NamedImports).elements.elements.some(element => {
10
+ const specifier = element.element.specifier;
11
+ const name = specifier.kind === JS.Kind.Alias ? (specifier as JS.Alias).propertyName.element : specifier;
12
+ return isIdentifier(name) && name.simpleName === 'ReactComponent';
13
+ });
14
+ }
15
+
16
+ /** Parsed replacement imports cannot carry comments attached to the original inner tokens. */
17
+ export async function svgImportNeedsReview(imp: JS.Import): Promise<boolean> {
18
+ if (!importsSvgComponent(imp)) return false;
19
+ if (!svgComponentName(imp)) return true;
20
+ const printed = await TreePrinters.printer(JS.Kind.CompilationUnit).print(imp);
21
+ const withoutLeadingComments = printed.replace(/^(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*(?:\n|$))*/, '');
22
+ return /\/[*\/]/.test(withoutLeadingComments);
23
+ }
24
+
25
+ /** The unambiguous CRA form, with exactly one named export and a relative SVG path. */
26
+ export function svgComponentName(imp: JS.Import): string | undefined {
27
+ const module = imp.moduleSpecifier?.element as J.Literal | undefined;
28
+ const bindings = imp.importClause?.namedBindings;
29
+ if (typeof module?.value !== "string" || !/^\.{1,2}\/.*\.svg$/.test(module.value) ||
30
+ imp.importClause?.typeOnly || bindings?.kind !== JS.Kind.NamedImports) return undefined;
31
+ const elements = (bindings as JS.NamedImports).elements.elements;
32
+ if (elements.length !== 1) return undefined;
33
+ const specifier = elements[0].element.specifier;
34
+ if (isIdentifier(specifier)) return specifier.simpleName === "ReactComponent" ? specifier.simpleName : undefined;
35
+ if (specifier.kind !== JS.Kind.Alias) return undefined;
36
+ const alias = specifier as JS.Alias;
37
+ const property = alias.propertyName.element;
38
+ return isIdentifier(property) && property.simpleName === "ReactComponent" && isIdentifier(alias.alias) ? alias.alias.simpleName : undefined;
39
+ }
@@ -1,11 +1,11 @@
1
- import {ExecutionContext, TreeVisitor} from "@openrewrite/rewrite";
2
- import {JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
1
+ import {ExecutionContext, mapAsync, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {JavaScriptParser, JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
3
3
  import {J} from "@openrewrite/rewrite/java";
4
4
  import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
5
- import {baseName} from "./shared";
5
+ import {baseName, nearestRoot} from "./shared";
6
6
 
7
7
  /** The `///` of a triple-slash directive is parsed as the comment's `//`, leaving `/ <reference ... />` as its text. */
8
- const REACT_SCRIPTS_REFERENCE = /^\/ <reference types="react-scripts" \/>$/;
8
+ const REACT_SCRIPTS_REFERENCE = /^\/\s*<reference\s+types=["'](?:@[^/"']+\/)?react-scripts["']\s*\/>$/;
9
9
  const VITE_CLIENT_REFERENCE = '/ <reference types="vite/client" />';
10
10
 
11
11
  /**
@@ -29,10 +29,17 @@ export class UpdateReactAppEnvTypes extends CraScanningRecipe {
29
29
  return new class extends JavaScriptVisitor<ExecutionContext> {
30
30
  override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
31
31
  if (!baseName(cu.sourcePath).endsWith(".d.ts") || !acc.isViteFile(cu.sourcePath)) return cu;
32
- const comments = cu.prefix.comments.map(c =>
32
+ let comments = await mapAsync(cu.prefix.comments, async c =>
33
33
  c.kind === J.Kind.TextComment && REACT_SCRIPTS_REFERENCE.test((c as unknown as {text: string}).text) ?
34
34
  {...c, text: VITE_CLIENT_REFERENCE} : c);
35
- if (comments.every((c, i) => c === cu.prefix.comments[i])) return super.visitJsCompilationUnit(cu, ctx);
35
+ const owner = nearestRoot(acc.packageDirs, cu.sourcePath);
36
+ const svgr = acc.usesSvgr(owner);
37
+ if (svgr && baseName(cu.sourcePath) === "react-app-env.d.ts" && !comments.some(c =>
38
+ c.kind === J.Kind.TextComment && (c as unknown as {text: string}).text.includes('types="vite-plugin-svgr/client"'))) {
39
+ const parsed = await new JavaScriptParser().parseOne({text: '/// <reference types="vite-plugin-svgr/client" />\n', sourcePath: "svgr-env.d.ts"}) as JS.CompilationUnit;
40
+ comments = [...comments, ...parsed.prefix.comments];
41
+ }
42
+ if (comments === cu.prefix.comments) return super.visitJsCompilationUnit(cu, ctx);
36
43
  return {...cu, prefix: {...cu.prefix, comments}} as JS.CompilationUnit;
37
44
  }
38
45
  };
@@ -1,61 +1,55 @@
1
- import {ExecutionContext, TreeVisitor} from "@openrewrite/rewrite";
1
+ import {craScript} from './cra-script';
2
+ import {ExecutionContext, Parsers, SourceFile, TreeVisitor} from "@openrewrite/rewrite";
2
3
  import {getMemberKeyName, isObject, Json, jsonLiteral, JsonVisitor, membersOf, removeAt, setAt} from "@openrewrite/rewrite/json";
3
4
  import {CraProjects, CraScanningRecipe} from "./scan-cra-projects";
4
- import {dirName, isPackageJson, memberObject, runsOnVite, stringValue} from "./shared";
5
-
6
- /** Only an exact match is rewritten: extra flags or environment prefixes need a human. */
7
- const SCRIPT_REPLACEMENTS = new Map<string, string>([
8
- ["react-scripts start", "vite"],
9
- ["react-scripts build", "vite build"],
10
- ]);
11
-
12
- /** `react-scripts build` fails the build on type errors; `vite build` does not type-check, so a project with a tsconfig keeps the check. */
13
- const TYPE_CHECKED_BUILD = "tsc --noEmit && vite build";
5
+ import {dirName, isPackageJson, joinPath, memberObject, stringValue} from "./shared";
6
+ import {CRA_TYPECHECK_PATH, CRA_TYPECHECK_SCRIPT} from './cra-typecheck';
14
7
 
15
8
  /**
16
- * Rewrites scripts whose command is exactly `react-scripts start` and `react-scripts build`.
9
+ * Rewrites CRA start/build commands and literal HOST, PORT, PUBLIC_URL and BUILD_PATH controls.
17
10
  *
18
11
  * ```json
19
12
  * "start": "react-scripts start" -> "start": "vite"
20
13
  * "build": "react-scripts build" -> "build": "vite build"
21
- * "build": "react-scripts build" -> "build": "tsc --noEmit && vite build" (when there is a tsconfig.json)
14
+ * "build": "react-scripts build" -> "build": "node scripts/vite-typecheck.cjs && vite build" (when there is a tsconfig.json)
22
15
  * "eject": "react-scripts eject" -> (removed)
23
16
  * ```
24
17
  *
25
18
  * `react-scripts build` failed on type errors and `vite build` does not type-check, so a package with a `tsconfig.json`
26
- * keeps the check. `--noEmit` rather than `tsc -b`, because the CRA tsconfig sets `noEmit` and `tsc -b` rejects that before TypeScript 5.6.
19
+ * keeps a checker that reports production diagnostics under `src/`, matching CRA's scope.
27
20
  *
28
- * Only packages that depend on `react-scripts` change; in a workspace that hoists it the scripts are left alone. A package
29
- * with a script that wraps `react-scripts start|build` or runs `craco` is not edited at all, because a half-migrated
30
- * package has no working `start`. Scripts with extra flags (`cross-env PORT=4000 react-scripts start`) and `test` are left for
31
- * `FindCraToViteBlockers` to flag.
21
+ * Custom shell commands, HTTPS configuration, unknown flags and wrapper tools require manual review.
22
+ * Tests are left for the separate Vitest migration.
32
23
  *
33
24
  * @see https://react.dev/blog/2025/02/14/sunsetting-create-react-app#how-to-migrate-to-a-build-tool
34
25
  */
35
26
  export class UpdateReactScriptsScripts extends CraScanningRecipe {
36
27
  readonly name = "org.openrewrite.react.cra-to-vite.update-package-scripts";
37
28
  readonly displayName = "Replace `react-scripts` start and build scripts with Vite";
38
- readonly description = "Rewrites `package.json` scripts that are exactly `react-scripts start` or `react-scripts build` to `vite` and `vite build` (`tsc --noEmit && vite build` when there is a `tsconfig.json`), and removes the `react-scripts eject` script, in packages that depend on `react-scripts`. Packages with `craco`, `react-app-rewired` or wrapped `start` or `build` scripts are left unchanged, as is the `test` script.";
29
+ readonly description = "Replaces CRA start/build scripts with Vite, preserving literal HOST, PORT, PUBLIC_URL and BUILD_PATH settings as CLI options and retaining production TypeScript checking. Removes eject. Custom wrappers, unknown shell syntax and test scripts are left unchanged.";
30
+
31
+ override async generate(acc: CraProjects, ctx: ExecutionContext): Promise<SourceFile[]> {
32
+ const parser = Parsers.createParser('plainText', {ctx});
33
+ return Promise.all([...acc.viteRoots].filter(root => acc.mayMigrate(root) && acc.has(root, 'tsconfig.json') && !acc.has(root, CRA_TYPECHECK_PATH))
34
+ .map(root => parser.parseOne({text: CRA_TYPECHECK_SCRIPT, sourcePath: joinPath(root, CRA_TYPECHECK_PATH)})));
35
+ }
39
36
 
40
37
  async editorWithData(acc: CraProjects): Promise<TreeVisitor<any, ExecutionContext>> {
41
38
  return new class extends JsonVisitor<ExecutionContext> {
42
39
  protected override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
43
- if (!isPackageJson(doc.sourcePath) || !isObject(doc.value) || !runsOnVite(doc.value)) return doc;
40
+ if (!isPackageJson(doc.sourcePath) || !isObject(doc.value) || !acc.isViteFile(doc.sourcePath)) return doc;
41
+ if (acc.has(dirName(doc.sourcePath), 'tsconfig.json') && acc.has(dirName(doc.sourcePath), CRA_TYPECHECK_PATH)) return doc;
44
42
  const scripts = memberObject(doc.value, "scripts");
45
43
  if (!scripts) return doc;
46
- const build = acc.has(dirName(doc.sourcePath), "tsconfig.json") ? TYPE_CHECKED_BUILD : "vite build";
47
44
  let updated = doc;
48
45
  for (const m of membersOf(scripts)) {
49
46
  const name = getMemberKeyName(m);
50
47
  const command = stringValue(m.value)?.trim();
51
48
  if (name === undefined || command === undefined) continue;
52
- // `eject` has no Vite equivalent and is the last thing that keeps react-scripts installed.
53
- if (command === "react-scripts eject") {
54
- updated = removeAt(updated, ["scripts", name]);
55
- continue;
56
- }
57
- const replacement = SCRIPT_REPLACEMENTS.get(command);
58
- if (replacement) updated = setAt(updated, ["scripts", name], jsonLiteral(replacement === "vite build" ? build : replacement));
49
+ const migrated = craScript(command, acc.has(dirName(doc.sourcePath), 'tsconfig.json'));
50
+ if (!migrated || migrated.operation === 'test') continue;
51
+ updated = migrated.replacement === null ? removeAt(updated, ['scripts', name]) :
52
+ setAt(updated, ['scripts', name], jsonLiteral(migrated.replacement));
59
53
  }
60
54
  return updated;
61
55
  }
@@ -1,6 +1,7 @@
1
- import {check, ExecutionContext, foundSearchResult, not, printer, Recipe, TreeVisitor} from "@openrewrite/rewrite";
1
+ import {check, ExecutionContext, foundSearchResult, not, Recipe, TreeVisitor} from "@openrewrite/rewrite";
2
2
  import {
3
3
  capture,
4
+ isEqual,
4
5
  isVendoredOrBundled,
5
6
  JavaScriptVisitor,
6
7
  JS,
@@ -27,6 +28,7 @@ const RESULT_IS_USED = `\`root.render()\` returns \`void\`, not the component in
27
28
  * statement that renders a container once is rewritten. A call inside a function (it may run again
28
29
  * and would create a second root), a call whose result is used (`root.render()` returns `void`),
29
30
  * a container rendered twice, and a file that already uses the name `root` are marked instead.
31
+ * Only the first container in a file is rewritten, as the next one would redeclare `root`.
30
32
  *
31
33
  * Before:
32
34
  * ```tsx
@@ -46,7 +48,7 @@ const RESULT_IS_USED = `\`root.render()\` returns \`void\`, not the component in
46
48
  export class ReplaceReactDomRender extends Recipe {
47
49
  readonly name = "org.openrewrite.react.18.replace-reactdom-render";
48
50
  readonly displayName: string = "Replace `ReactDOM.render` with `createRoot`";
49
- readonly description: string = "Migrates a top-level `ReactDOM.render()` call to the `createRoot()` API from `react-dom/client` introduced in React 18, creating the root once. Calls inside functions, calls whose result is used and containers that are rendered more than once are marked for manual migration.";
51
+ readonly description: string = "Migrates a top-level `ReactDOM.render()` call to the `createRoot()` API from `react-dom/client` introduced in React 18, creating the root once. Calls inside functions, calls whose result is used and containers that are rendered more than once are marked for manual migration, as is every container after the first in a file, since each would redeclare `root`.";
50
52
 
51
53
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
52
54
  const element = capture<Expression>();
@@ -69,12 +71,12 @@ export class ReplaceReactDomRender extends Recipe {
69
71
  }));
70
72
 
71
73
  return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
72
- private containerCounts = new Map<string, number>();
74
+ private containers: Expression[] = [];
73
75
  private rootNameTaken = false;
74
76
  private inlinedBlocks = new Set<string>();
75
77
 
76
78
  override async visitJsCompilationUnit(cu: JS.CompilationUnit, p: ExecutionContext): Promise<J | undefined> {
77
- this.containerCounts = new Map();
79
+ this.containers = [];
78
80
  this.rootNameTaken = false;
79
81
  this.inlinedBlocks = new Set();
80
82
  await this.survey(cu);
@@ -94,8 +96,7 @@ export class ReplaceReactDomRender extends Recipe {
94
96
  if (position === "used") {
95
97
  return foundSearchResult(m, RESULT_IS_USED);
96
98
  }
97
- const containerSource = (await printer(this.cursor).print(match.get(container)!)).trim();
98
- if (position === "nested" || this.rootNameTaken || this.containerCounts.get(containerSource)! > 1) {
99
+ if (position === "nested" || this.rootNameTaken || await this.rendersInto(match.get(container)!) > 1) {
99
100
  return foundSearchResult(m, ONE_ROOT_PER_CONTAINER);
100
101
  }
101
102
 
@@ -104,6 +105,7 @@ export class ReplaceReactDomRender extends Recipe {
104
105
  return m;
105
106
  }
106
107
  maybeRemoveImport(this, "react-dom", "render");
108
+ this.rootNameTaken = true;
107
109
  this.inlinedBlocks.add(result.id);
108
110
  return result;
109
111
  }
@@ -134,6 +136,14 @@ export class ReplaceReactDomRender extends Recipe {
134
136
  return "used";
135
137
  }
136
138
 
139
+ private async rendersInto(target: Expression): Promise<number> {
140
+ let count = 0;
141
+ for (const c of this.containers) {
142
+ if (await isEqual(c, target)) count++;
143
+ }
144
+ return count;
145
+ }
146
+
137
147
  private async survey(cu: JS.CompilationUnit): Promise<void> {
138
148
  const outer = this;
139
149
  await new class extends JavaScriptVisitor<void> {
@@ -147,8 +157,7 @@ export class ReplaceReactDomRender extends Recipe {
147
157
  override async visitMethodInvocation(m: J.MethodInvocation, q: void): Promise<J | undefined> {
148
158
  const match = await renderPattern.match(m, this.cursor);
149
159
  if (match) {
150
- const source = (await printer(this.cursor).print(match.get(container)!)).trim();
151
- outer.containerCounts.set(source, (outer.containerCounts.get(source) ?? 0) + 1);
160
+ outer.containers.push(match.get(container)!);
152
161
  }
153
162
  return super.visitMethodInvocation(m, q);
154
163
  }
@@ -6,8 +6,10 @@ import {
6
6
  isVendoredOrBundled,
7
7
  JS,
8
8
  maybeRemoveImport,
9
+ namesReferencedWithin,
9
10
  pattern,
10
11
  raw,
12
+ scopeOf,
11
13
  template,
12
14
  usesMethod
13
15
  } from "@openrewrite/rewrite/javascript";
@@ -78,25 +80,34 @@ export class ReplaceUnmountComponentAtNode extends Recipe {
78
80
  return await template`${raw(root)}.unmount()`.apply(m, this.cursor);
79
81
  }
80
82
 
81
- /** The name of a `const root = createRoot(<container>)` in an enclosing scope. */
83
+ /**
84
+ * The name of a `const root = createRoot(<container>)` in an enclosing scope, where neither the root nor
85
+ * the names the container reads are rebound between that scope and the call.
86
+ */
82
87
  private async findRoot(containerArg: Expression): Promise<string | undefined> {
88
+ const scope = scopeOf(this.cursor);
89
+ const inner = new Set<unknown>();
90
+ const rebound = (name: string) => inner.has(scope.declaringScope(name, 'value'));
91
+ const containerNames = [...namesReferencedWithin(containerArg)];
83
92
  for (let c: Cursor | undefined = this.cursor; c; c = c.parent) {
84
93
  const statements: any[] | undefined = c.value?.kind === J.Kind.Block || c.value?.kind === JS.Kind.CompilationUnit
85
94
  ? c.value.statements
86
95
  : undefined;
96
+ if (containerNames.some(rebound)) return undefined;
87
97
  for (const statement of statements ?? []) {
88
98
  const decl = statement.element ?? statement;
89
99
  if (decl.kind !== J.Kind.VariableDeclarations) continue;
90
100
  for (const v of decl.variables) {
91
101
  const named = v.element;
92
102
  const init = named.initializer?.element;
93
- if (!init || !isIdentifier(named.name)) continue;
103
+ if (!init || !isIdentifier(named.name) || rebound(named.name.simpleName)) continue;
94
104
  const rootArg = (await createRootCall.match(init, this.cursor))?.get(rootContainer);
95
105
  if (rootArg && await isEqual(rootArg, containerArg)) {
96
106
  return named.name.simpleName;
97
107
  }
98
108
  }
99
109
  }
110
+ inner.add(c.value);
100
111
  }
101
112
  return undefined;
102
113
  }