@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,657 @@
1
+ import {Cursor, DataTable, emptyMarkers, ExecutionContext, Markup, MarkersKind, or, randomId, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {
3
+ AddDependencyOptions, autoFormat, findNodeResolutionResult, isVendoredOrBundled, JavaScriptVisitor, JS, JSX, maybeAddImport, maybeRemoveImport, raw, template
4
+ } from "@openrewrite/rewrite/javascript";
5
+ import {isIdentifier, J, Statement} from "@openrewrite/rewrite/java";
6
+ import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
7
+ import {create} from "mutative";
8
+ import {minVersion, satisfies, valid, validRange} from "semver";
9
+ import {check, not} from "@openrewrite/rewrite";
10
+ import {JavaDependencyRecipe, treesOfType} from "../util/java-recipe-proxy";
11
+ import {importBindings, resolveRelative} from "../util/module-imports";
12
+ import {rewriteVersion, supportsResolvingGate} from "../testing/enzyme-to-react-testing-library";
13
+ import {caseReducers, Finding, localSlices, REDUX_STORES_TABLE, ReduxStoreRow, RTK, SliceModule, SUGGESTED_ACTIONS, TEST_SOURCE} from "./redux-stores";
14
+ import {
15
+ actionsExport, argumentsOf, dispatchedAction, getStateRead, isDispatcherDeclaration, isReactDependencies, isReducerExport, parentTree, Plan, planPackages, PlannedSlice, providerChild,
16
+ REACT_REDUX, relativeSpecifier, selectorRead, sliceSource, SliceSource, SourceFacts, sourceFacts, storeFacts
17
+ } from "./zustand-plan";
18
+
19
+ const ZUSTAND = "zustand";
20
+ const IMMER = "immer";
21
+
22
+ /** zustand 5 needs React 18; zustand 4 supports React 16.8 and up. */
23
+ const ZUSTAND_5: AddDependencyOptions = {
24
+ packageName: ZUSTAND, version: "^5.0.8", scope: "dependencies", onlyIfDeclaring: [RTK],
25
+ onlyIfResolving: ["react@>=18.0.0"]
26
+ };
27
+ const ZUSTAND_4: AddDependencyOptions = {...ZUSTAND_5, version: "^4.5.7", onlyIfResolving: ["react@>=16.8.0 <18"]};
28
+ const IMMER_10: AddDependencyOptions = {...ZUSTAND_5, packageName: IMMER, version: "^10.1.3", onlyIfResolving: ["react@>=16.8.0"]};
29
+
30
+ /** The package roots whose store converts, which the dependency steps read once the scan is done. Mutated in place. */
31
+ export interface ZustandForecast {
32
+ converting?: () => Promise<ReadonlySet<string>>;
33
+ /**
34
+ * The package roots whose lockfile the Java recipe couldn't regenerate for a dependency it declares, with its
35
+ * warning and the lockfile. Every step leaves their manifest and lockfile as they were. Mutated in place.
36
+ */
37
+ refused?: Map<string, {message: string, lock: string}>;
38
+ /** The React range a package root declares, which picks the zustand step as Java's resolution gate can't where nothing resolved. */
39
+ react?: (root: string) => string | undefined;
40
+ }
41
+
42
+ const LOCKFILE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lock)$/;
43
+
44
+ /** A package's dependencies, as far as the conversion needs them. */
45
+ interface PackageFacts {
46
+ react?: string;
47
+ zustand?: string;
48
+ immer?: string;
49
+ }
50
+
51
+ interface Scanned {
52
+ sources: Map<string, SourceFacts>;
53
+ modules: Map<string, SliceModule>;
54
+ sliceSources: Map<string, SliceSource>;
55
+ packages: Map<string, PackageFacts>;
56
+ }
57
+
58
+ /** Adds a dependency to the package whose Redux store converts, with the gates of Java's `AddDependency`. */
59
+ abstract class ZustandDependency extends JavaDependencyRecipe {
60
+ /** The package roots whose `package.json` declares the dependency once this run's edit lands. Mutated in place. */
61
+ readonly landed = new Set<string>();
62
+ private readonly held: Json.Document[] = [];
63
+ private readonly locks: SourceFile[] = [];
64
+ /** The converting package roots whose declared React this step's version doesn't support, left alone. */
65
+ private readonly unfit = new Set<string>();
66
+
67
+ protected constructor(private readonly addition: AddDependencyOptions, private readonly forecast: ZustandForecast) {
68
+ super("org.openrewrite.javascript.AddDependency", addition);
69
+ }
70
+
71
+ override initialValue(): number {
72
+ this.landed.clear();
73
+ this.unfit.clear();
74
+ this.held.length = 0;
75
+ this.locks.length = 0;
76
+ this.forecast.refused?.clear();
77
+ return super.initialValue();
78
+ }
79
+
80
+ protected override scanned(manifest: SourceFile): boolean {
81
+ if (manifest.kind === Json.Kind.Document && /(^|\/)package\.json$/.test(manifest.sourcePath)) {
82
+ this.held.push(manifest as Json.Document);
83
+ return false;
84
+ }
85
+ if (LOCKFILE.test(manifest.sourcePath)) this.locks.push(manifest);
86
+ return true;
87
+ }
88
+
89
+ protected override edits(manifest: SourceFile): boolean {
90
+ if (/(^|\/)package\.json$/.test(manifest.sourcePath) && this.unfit.has(packageRoot(manifest.sourcePath))) return false;
91
+ // The package's own lockfile stays too; a workspace's lockfile is the other packages' as well
92
+ if (LOCKFILE.test(manifest.sourcePath) && this.unfit.has(manifest.sourcePath.slice(0, manifest.sourcePath.lastIndexOf("/") + 1))) return false;
93
+ const refused = this.forecast.refused;
94
+ if (!refused?.size) return true;
95
+ if (/(^|\/)package\.json$/.test(manifest.sourcePath)) return !refused.has(packageRoot(manifest.sourcePath));
96
+ return ![...refused.values()].some(refusal => refusal.lock === manifest.sourcePath);
97
+ }
98
+
99
+ /** Whether the React range the package at `root` declares is one this step's version supports, as `onlyIfResolving` asks. */
100
+ private fits(root: string): boolean {
101
+ const declared = this.forecast.react?.(root);
102
+ const gate = this.addition.onlyIfResolving?.find(gate => gate.startsWith("react@"))?.slice("react@".length);
103
+ if (!declared || !gate || !validRange(declared)) return true;
104
+ const lowest = minVersion(declared);
105
+ return !lowest || satisfies(lowest, gate);
106
+ }
107
+
108
+ /** The lockfile that installs the package at `root`: its own, or that of the workspace it is in. */
109
+ private lockOf(root: string): SourceFile | undefined {
110
+ const directory = (path: string) => path.slice(0, path.lastIndexOf("/") + 1);
111
+ return this.locks.filter(lock => root.startsWith(directory(lock.sourcePath)))
112
+ .sort((a, b) => b.sourcePath.length - a.sourcePath.length)[0];
113
+ }
114
+
115
+ override async generate(acc: number, ctx: ExecutionContext): Promise<SourceFile[]> {
116
+ const converting = await this.forecast.converting?.() ?? new Set<string>();
117
+ // NOTE: Java's `onlyIfResolving` passes where nothing resolved React, such as a package without a lockfile
118
+ for (const root of converting) if (!this.fits(root)) this.unfit.add(root);
119
+ const forwarded = this.held.filter(manifest => converting.has(packageRoot(manifest.sourcePath)) && !this.unfit.has(packageRoot(manifest.sourcePath)));
120
+ const scanner = await this.java.scanner(acc);
121
+ for (const manifest of forwarded) await scanner.visit(manifest, ctx);
122
+ const generated = await super.generate(acc, ctx);
123
+ const editor = await this.java.editorWithData(acc);
124
+ for (const manifest of forwarded) {
125
+ const edited = await editor.visit<Json.Document>(manifest, ctx);
126
+ if (!edited || edited === manifest || !await declares(edited, this.addition.packageName)) continue;
127
+ // NOTE: where the package manager's lock can't be reproduced, `AddDependency` still declares the package
128
+ // and only warns on the lockfile, which an install from the lockfile, as in CI, would then refuse
129
+ const root = packageRoot(manifest.sourcePath);
130
+ const lock = this.lockOf(root);
131
+ const regenerated = lock ? await editor.visit<SourceFile>(lock, ctx) : undefined;
132
+ const warning = regenerated?.markers.markers.find(marker => marker.kind === MarkersKind.MarkupWarn || marker.kind === MarkersKind.MarkupError) as Markup | undefined;
133
+ if (warning) this.forecast.refused?.set(root, {message: warning.message, lock: lock!.sourcePath});
134
+ else this.landed.add(root);
135
+ }
136
+ this.held.length = 0;
137
+ return generated;
138
+ }
139
+ }
140
+
141
+ /** Adds zustand 5 where a store of a package on React 18 or later converts. */
142
+ export class AddZustand extends ZustandDependency {
143
+ readonly name = "org.openrewrite.react.migrate.add-zustand";
144
+ readonly displayName = "Add `zustand` where a Redux store is migrated";
145
+ readonly description = "Adds `zustand` 5 to packages that declare `@reduxjs/toolkit` and resolve React 18 or later, where a Redux store moves to zustand.";
146
+
147
+ constructor(forecast: ZustandForecast = {}) {
148
+ super(ZUSTAND_5, forecast);
149
+ }
150
+ }
151
+
152
+ /** Adds zustand 4 where a store of a package on React 16.8 to 17 converts. */
153
+ export class AddZustand4 extends ZustandDependency {
154
+ readonly name = "org.openrewrite.react.migrate.add-zustand-4";
155
+ readonly displayName = "Add `zustand` 4 where a Redux store is migrated on React 16.8 to 17";
156
+ readonly description = "Adds `zustand` 4 to packages that declare `@reduxjs/toolkit` and resolve React 16.8 to 17, where a Redux store moves to zustand.";
157
+
158
+ constructor(forecast: ZustandForecast = {}) {
159
+ super(ZUSTAND_4, forecast);
160
+ }
161
+ }
162
+
163
+ /** Adds immer, whose `produce` runs the slices' reducers as Redux Toolkit did. */
164
+ export class AddImmer extends ZustandDependency {
165
+ readonly name = "org.openrewrite.react.migrate.add-immer";
166
+ readonly displayName = "Add `immer` where a Redux store is migrated";
167
+ readonly description = "Adds `immer` 10 to packages that declare `@reduxjs/toolkit` and resolve React 16.8 or later, where a Redux store moves to zustand and its slices' reducers run through `produce`.";
168
+
169
+ constructor(forecast: ZustandForecast = {}) {
170
+ super(IMMER_10, forecast);
171
+ }
172
+ }
173
+
174
+ /** Older hosts drop `onlyIfResolving`, which would add zustand 5 to packages on React 17, so the steps run only where the host has it. */
175
+ const ADDS_DEPENDENCIES = (() => {
176
+ try {
177
+ return supportsResolvingGate(rewriteVersion(require.resolve("@openrewrite/rewrite"), require.cache));
178
+ } catch {
179
+ return false;
180
+ }
181
+ })();
182
+
183
+ /**
184
+ * Moves a repository's Redux Toolkit store to zustand, all or nothing. The repository's one store converts when it is
185
+ * a `configureStore` of `createSlice` reducers and nothing else (see `FindReduxStores`), its sources are JavaScript,
186
+ * and every use of it converts:
187
+ *
188
+ * - each slice becomes a zustand store, `useCounterStore` for the `counter` key, whose state is the slice's state,
189
+ * frozen as Redux Toolkit freezes it; each exported action creator becomes a function of the same name that runs
190
+ * the slice's reducer through immer's `produce`, as Redux Toolkit does;
191
+ * - `useSelector(state => state.counter.value)` becomes `useCounterStore(state => state.value)`;
192
+ * - `dispatch(increment())` and `store.dispatch(increment())`, whose result is unused, become `increment()`, and
193
+ * `const dispatch = useDispatch()` goes;
194
+ * - `store.getState().counter` becomes `useCounterStore.getState()`;
195
+ * - `<Provider store={store}>` is replaced with its one child, and the store's source is removed.
196
+ *
197
+ * Any other use, such as `connect`, a thunk, a selector that builds a value, or a dispatch whose result is used, keeps
198
+ * the store in Redux, recorded in the `ReduxStores` table with the reason.
199
+ *
200
+ * @see https://zustand.docs.pmnd.rs/guides/migrating-to-zustand
201
+ */
202
+ export class ReduxToZustand extends ScanningRecipe<Scanned> {
203
+ readonly name = "org.openrewrite.react.migrate.redux-to-zustand";
204
+ readonly displayName = "Migrate Redux Toolkit slices to zustand";
205
+ readonly description = "Moves a repository's one Redux Toolkit store to zustand when it is a `configureStore` of `createSlice` reducers with no other option, its sources are JavaScript, and every use of it converts: each slice becomes a zustand store whose action creators keep their names and run the slice's reducers through immer's `produce`, `useSelector` reads of one slice become the slice's zustand hook, `dispatch` and `store.dispatch` of the slices' action creators become calls of them, `store.getState()` reads become the slice store's `getState()`, and the react-redux `Provider` and the store's source are removed. Adds `zustand` and `immer` where they are missing. Stores with any other use, such as `connect`, thunks, selectors that build values or several stores, stay in Redux and are recorded for review.";
206
+
207
+ private readonly forecast: ZustandForecast = {refused: new Map()};
208
+ private readonly storeSources: JS.CompilationUnit[] = [];
209
+ /** The packages the dependency steps were asked to change, once they ask. */
210
+ private asked?: ReadonlySet<string>;
211
+ private readonly steps = ADDS_DEPENDENCIES ? {zustand: new AddZustand(this.forecast), zustand4: new AddZustand4(this.forecast), immer: new AddImmer(this.forecast)} : undefined;
212
+
213
+ private readonly stores = new DataTable<ReduxStoreRow>(
214
+ REDUX_STORES_TABLE, "Redux stores",
215
+ "The Redux stores of the repository and whether each one's setup can move to zustand, with one row for each reason it can't.",
216
+ ReduxStoreRow
217
+ );
218
+
219
+ initialValue(): Scanned {
220
+ this.storeSources.length = 0;
221
+ return {sources: new Map(), modules: new Map(), sliceSources: new Map(), packages: new Map()};
222
+ }
223
+
224
+ async scanner(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
225
+ const storeSources = this.storeSources;
226
+ let forecast: Promise<ReadonlySet<string>> | undefined;
227
+ this.asked = undefined;
228
+ this.forecast.react = root => scanned.packages.get(root)?.react;
229
+ this.forecast.converting = () => forecast ??= this.planned(scanned, true)
230
+ .then(plans => this.asked = new Set(plans.filter(p => p.store).map(p => packageOf(scanned.packages, p.store!.path)!)));
231
+ const sources = await check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
232
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
233
+ const {reducers, slices} = localSlices(cu);
234
+ scanned.modules.set(cu.sourcePath, {reducers, slices});
235
+ scanned.sources.set(cu.sourcePath, await sourceFacts(cu));
236
+ const slice = sliceSource(cu);
237
+ if (slice) scanned.sliceSources.set(cu.sourcePath, slice);
238
+ if (importBindings(cu).some(b => (b.module === RTK || b.module === "redux") && /^(configureStore|createStore|legacy_createStore)$/.test(b.name))) storeSources.push(cu);
239
+ return cu;
240
+ }
241
+ }());
242
+ const manifests = new class extends JsonVisitor<ExecutionContext> {
243
+ override async visitDocument(doc: Json.Document): Promise<Json | undefined> {
244
+ if (/(^|\/)package\.json$/.test(doc.sourcePath)) {
245
+ const declared = findNodeResolutionResult(doc) ? undefined : await declaredDependencies(doc);
246
+ const get = (name: string) => declared ? declared[name] : version(doc, name);
247
+ scanned.packages.set(packageRoot(doc.sourcePath), {react: get("react"), zustand: get(ZUSTAND), immer: get(IMMER)});
248
+ }
249
+ return doc;
250
+ }
251
+ }();
252
+ const scan = new class extends TreeVisitor<any, ExecutionContext> {
253
+ override async isAcceptable(sourceFile: SourceFile): Promise<boolean> {
254
+ return sourceFile.kind === Json.Kind.Document || sourceFile.kind === JS.Kind.CompilationUnit;
255
+ }
256
+
257
+ override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
258
+ if (tree.kind === Json.Kind.Document) return await manifests.visit(tree, ctx, parent) as R | undefined;
259
+ return tree.kind === JS.Kind.CompilationUnit ? await sources.visit(tree, ctx, parent) as R | undefined : tree as R;
260
+ }
261
+ }();
262
+ // HACK: the host infers which trees to send only from a typed visitor, as for the Enzyme migration
263
+ return check(or(treesOfType("org.openrewrite.json.tree.Json"), treesOfType("org.openrewrite.javascript.tree.JS")), scan);
264
+ }
265
+
266
+ /** The plan, once every source is scanned. `forecast` assumes that zustand and immer land wherever they're missing. */
267
+ private plans = new WeakMap<Scanned, Promise<Plan[]>>();
268
+
269
+ /** A plan for each package that creates a store. */
270
+ private async planned(scanned: Scanned, forecast = false): Promise<Plan[]> {
271
+ if (!forecast) {
272
+ const cached = this.plans.get(scanned);
273
+ if (cached) return cached;
274
+ }
275
+ const result = (async () => {
276
+ for (const cu of this.storeSources) {
277
+ const facts = scanned.sources.get(cu.sourcePath);
278
+ if (facts) facts.stores = await storeFacts(cu, scanned.modules);
279
+ }
280
+ return planPackages(scanned.sources, scanned.sliceSources, path => packageOf(scanned.packages, path),
281
+ storePath => this.dependencies(scanned, storePath, forecast));
282
+ })();
283
+ if (!forecast) this.plans.set(scanned, result);
284
+ return result;
285
+ }
286
+
287
+ /** Why the package of the store can't take zustand and immer, if it can't. */
288
+ private dependencies(scanned: Scanned, storePath: string, forecast: boolean): Finding | undefined {
289
+ const root = packageOf(scanned.packages, storePath);
290
+ const facts = root !== undefined ? scanned.packages.get(root) : undefined;
291
+ if (root === undefined || !facts) return {reason: "NO_PACKAGE", detail: storePath};
292
+ const react = major(facts.react);
293
+ if (react === undefined || react < 16 || react === 16 && (minVersion(facts.react!)?.minor ?? 0) < 8) return {reason: "REACT_VERSION", detail: facts.react ?? "react not declared"};
294
+ // A package the steps weren't asked to change keeps its store for another reason, recorded already
295
+ const refusal = !forecast ? this.forecast.refused?.get(root) : undefined;
296
+ if (refusal) return {reason: "DEPENDENCY", detail: `zustand isn't added: ${refusal.message}`};
297
+ const landed = (step: ZustandDependency | undefined) => forecast || !this.asked?.has(root) && this.asked !== undefined ? !!this.steps : !!step?.landed.has(root);
298
+ const zustand = facts.zustand !== undefined ? (major(facts.zustand) ?? 0) >= (react >= 18 ? 4 : 4) && (react >= 18 || major(facts.zustand) === 4)
299
+ : landed(react >= 18 ? this.steps?.zustand : this.steps?.zustand4);
300
+ if (!zustand) return {reason: "DEPENDENCY", detail: facts.zustand ? `zustand ${facts.zustand} doesn't support React ${react}` : "zustand can't be added"};
301
+ const immer = facts.immer !== undefined ? (major(facts.immer) ?? 0) >= 9 : landed(this.steps?.immer);
302
+ if (!immer) return {reason: "DEPENDENCY", detail: facts.immer ? `immer ${facts.immer} is older than 9` : "immer can't be added"};
303
+ return undefined;
304
+ }
305
+
306
+ async editorWithData(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
307
+ const recipe = this;
308
+ const stores = this.stores;
309
+ const reported = new Set<string>();
310
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
311
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
312
+ const plans = await recipe.planned(scanned);
313
+ const facts = scanned.sources.get(cu.sourcePath);
314
+ for (const store of facts?.stores ?? []) {
315
+ const key = `${store.path}\0${store.store}\0${store.api}`;
316
+ if (reported.has(key)) continue;
317
+ reported.add(key);
318
+ const p = plans.find(candidate => candidate.store === store) ?? plans.find(candidate => candidate.blocked.has(store));
319
+ const findings = p?.store === store ? [] : p?.blocked.get(store) ?? store.findings;
320
+ const rows = findings.length === 0 ? [{reason: "SLICE_STORE", detail: ""}] : findings;
321
+ for (const {reason, detail} of rows) {
322
+ stores.insertRow(ctx, {
323
+ sourcePath: store.path, store: store.store, api: store.api,
324
+ status: p?.store === store ? "CONVERTED" : "REVIEW", reason, detail,
325
+ testSource: TEST_SOURCE.test(store.path), suggestedAction: SUGGESTED_ACTIONS[reason] ?? CONVERSION_ACTIONS[reason] ?? ""
326
+ });
327
+ }
328
+ }
329
+ const p = plans.find(candidate => candidate.store && candidate.sources.has(cu.sourcePath));
330
+ if (!p?.store) return cu;
331
+ if (cu.sourcePath === p.store.path) return undefined;
332
+ const slice = [...p.slices.values()].find(s => s.path === cu.sourcePath);
333
+ const converted = slice ? await convertSlice(this, cu, slice, scanned, ctx) : cu;
334
+ return convertConsumer(converted, p, scanned, ctx);
335
+ }
336
+ }());
337
+ }
338
+
339
+ async recipeList() {
340
+ const steps = this.steps;
341
+ return steps ? [steps.zustand, steps.zustand4, steps.immer] : [];
342
+ }
343
+ }
344
+
345
+ const CONVERSION_ACTIONS: Readonly<Record<string, string>> = {
346
+ MULTIPLE_STORES: "Convert by hand, or one store at a time: the uses of react-redux can't be told apart by store.",
347
+ STORE_NOT_MODULE_LEVEL: "Create the store once at the top level of its module; a zustand store is a module-level singleton.",
348
+ STORE_SOURCE: "Move what else the store's source declares, such as types or helpers, to another module.",
349
+ SLICE_SOURCE: "Declare each slice in a source of its own, held in a `const` of its own.",
350
+ SLICE_KEY: "Use a reducer key that is a JavaScript identifier, which names the zustand hook.",
351
+ NAME_TAKEN: "Rename what already uses the name the conversion would give the zustand store or its helpers.",
352
+ SLICE_OPTION: "Remove the `createSlice` option, or convert the slice by hand.",
353
+ SLICE_NAME: "Write the slice's `name` as a string literal.",
354
+ INITIAL_STATE: "Write the initial state as a value, or a `const` holding one, rather than a function.",
355
+ REDUCER: "Write each reducer as a function; `prepare` callbacks and reducers that use `this` are converted by hand.",
356
+ ACTIONS_EXPORT: "Export the action creators as `export const {a, b} = slice.actions`, under their own names.",
357
+ UNKNOWN_ACTION: "Remove the import of an action creator that has no reducer, which is `undefined`.",
358
+ SLICE_USE: "Use the slice only through its action creators and the store; other uses of the slice object are converted by hand.",
359
+ STORE_USE: "Use the store only in `<Provider store>`, `store.getState().key` and `store.dispatch(action())`.",
360
+ REACT_REDUX_USE: "Replace `connect`, `useStore` and other react-redux APIs with `useSelector` and `useDispatch`, or convert by hand.",
361
+ DISPATCH: "Dispatch only the slices' action creators, as a statement of its own; thunks and dispatches whose result is used are converted by hand.",
362
+ SELECTOR: "Read one slice's state in each selector, such as `state => state.counter.value`; selectors that build a value are converted by hand.",
363
+ UNFOLLOWED_IMPORT: "Import the store, its slices and react-redux with named or default imports; namespace imports, re-exports and module mocks are converted by hand.",
364
+ TYPESCRIPT: "TypeScript sources are not converted yet.",
365
+ NO_PACKAGE: "Add a `package.json` for the store's package.",
366
+ REACT_VERSION: "zustand needs React 16.8 or later.",
367
+ DEPENDENCY: "Add `zustand` and `immer` to the package, in versions that support its React."
368
+ };
369
+
370
+ function packageRoot(manifestPath: string): string {
371
+ return manifestPath.slice(0, -"package.json".length);
372
+ }
373
+
374
+ /** The root of the innermost package that holds `sourcePath`. */
375
+ function packageOf(packages: ReadonlyMap<string, PackageFacts>, sourcePath: string): string | undefined {
376
+ return [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length)[0];
377
+ }
378
+
379
+ /** Whether a manifest declares `name`, by its resolution or, where an edit left it none, by its JSON. */
380
+ async function declares(manifest: Json.Document, name: string): Promise<boolean> {
381
+ if (declaration(manifest, name)) return true;
382
+ return name in await declaredDependencies(manifest);
383
+ }
384
+
385
+ function declaration(manifest: Json.Document, name: string) {
386
+ const resolution = findNodeResolutionResult(manifest);
387
+ return [...resolution?.dependencies ?? [], ...resolution?.devDependencies ?? [], ...resolution?.optionalDependencies ?? [],
388
+ ...resolution?.peerDependencies ?? []].find(dep => dep.name === name);
389
+ }
390
+
391
+ /** The version a package resolves `name` at, or the range it declares. */
392
+ function version(manifest: Json.Document, name: string): string | undefined {
393
+ const dependency = declaration(manifest, name);
394
+ const resolved = dependency?.resolved;
395
+ if (resolved?.name === name && valid(resolved.version) && (!validRange(dependency!.versionConstraint) || satisfies(resolved.version, dependency!.versionConstraint))) {
396
+ return resolved.version;
397
+ }
398
+ return dependency?.versionConstraint;
399
+ }
400
+
401
+ /** The ranges a manifest without a resolution declares, read from its JSON. */
402
+ async function declaredDependencies(doc: Json.Document): Promise<Record<string, string>> {
403
+ try {
404
+ const manifest = JSON.parse(await TreePrinters.print(doc));
405
+ return {...manifest.peerDependencies, ...manifest.optionalDependencies, ...manifest.devDependencies, ...manifest.dependencies};
406
+ } catch {
407
+ return {};
408
+ }
409
+ }
410
+
411
+ function major(range: string | undefined): number | undefined {
412
+ if (!range || !validRange(range)) return undefined;
413
+ return minVersion(range)?.major;
414
+ }
415
+
416
+ function space(whitespace: string): J.Space {
417
+ return {kind: J.Kind.Space, comments: [], whitespace};
418
+ }
419
+
420
+ /** Rewrites a slice's source: the slice becomes a zustand store, its action creators functions that run its reducers. */
421
+ async function convertSlice(visitor: JavaScriptVisitor<ExecutionContext>, cu: JS.CompilationUnit, slice: PlannedSlice, scanned: Scanned,
422
+ ctx: ExecutionContext): Promise<JS.CompilationUnit> {
423
+ const local = localSlices(cu);
424
+ const cursor = new Cursor(cu, undefined);
425
+ const statements: J.RightPadded<Statement>[] = [];
426
+ const facts = local.localSlices.get(slice.variable);
427
+ for (const padded of cu.statements) {
428
+ const statement = padded.element;
429
+ const thunk = statement.kind === J.Kind.VariableDeclarations ? (statement as J.VariableDeclarations).variables[0].element : undefined;
430
+ const kept = thunk && isIdentifier(thunk.name) ? slice.thunkVariables.get(thunk.name.simpleName) : undefined;
431
+ if (thunk && kept) {
432
+ // RTK's thunk runs as before, its stages dispatched to the slice's cases rather than to the Redux store
433
+ const name = (thunk.name as J.Identifier).simpleName;
434
+ const exported = (statement as J.VariableDeclarations).modifiers.some(m => m.keyword === "export");
435
+ const statementCursor = new Cursor(statement, cursor);
436
+ const rtk = await template`const ${raw(kept)} = ${thunk.initializer!.element};`.apply(statement, statementCursor);
437
+ const run = await template`${raw(exported ? "export " : "")}const ${raw(name)} = arg => ${raw(kept)}(arg)(${raw(slice.dispatch)}, ${raw(slice.hook)}.getState, undefined);`
438
+ .apply(statement, statementCursor);
439
+ statements.push({...padded, element: withPrefix(rtk as Statement, statement.prefix)});
440
+ statements.push({...padded, element: withPrefix(run as Statement, space("\n"))});
441
+ continue;
442
+ }
443
+ if (statement.kind === J.Kind.VariableDeclarations && (statement as J.VariableDeclarations).variables.some(v =>
444
+ isIdentifier(v.element.name) && v.element.name.simpleName === slice.variable)) {
445
+ const call = (statement as J.VariableDeclarations).variables[0].element.initializer!.element as J.MethodInvocation;
446
+ const options = new Map(((argumentsOf(call)[0] as J.NewClass).body!.statements.map(s => s.element as JS.PropertyAssignment))
447
+ .map(p => [(p.name.element as J.Identifier).simpleName ?? String((p.name.element as J.Literal).value), p.initializer ?? p.name.element]));
448
+ const name = String((options.get("name") as J.Literal).value);
449
+ const statementCursor = new Cursor(statement, cursor);
450
+ const hook = await template`export const ${raw(slice.hook)} = create(() => freeze(${options.get("initialState")!}, true));`.apply(statement, statementCursor);
451
+ const reducers = options.get("reducers");
452
+ const reducerObject = reducers ? await template`const ${raw(slice.reducers)} = ${reducers};`.apply(statement, statementCursor) :
453
+ await template`const ${raw(slice.reducers)} = {};`.apply(statement, statementCursor);
454
+ const action = await template`const ${raw(slice.action)} = type => payload => ${raw(slice.hook)}.setState(state => produce(state, draft => ${raw(slice.reducers)}[type](draft, {type: ${raw(JSON.stringify(name + "/"))} + type, payload})), true);`
455
+ .apply(statement, statementCursor);
456
+ const generatedStatements = [reducerObject, action];
457
+ const cases = facts?.cases?.length ? caseReducers(cu, slice.variable) : [];
458
+ if (cases.length > 0) {
459
+ // `addCase` reducers run as RTK runs them, through immer, on actions RTK's thunks create
460
+ const parts = [`const ${slice.caseObject} = {\n`, ...cases.slice(1).map(() => ",\n"), "\n};"];
461
+ const keyed = parts.map((part, i) => i < cases.length ? `${part}${JSON.stringify(`${facts!.thunks!.get(cases[i].thunk)!.typePrefix}/${cases[i].stage}`)}: ` : part);
462
+ const strings = Object.assign([...keyed], {raw: [...keyed]}) as unknown as TemplateStringsArray;
463
+ generatedStatements.push(await template(strings, ...cases.map(c => c.reducer)).apply(statement, statementCursor));
464
+ generatedStatements.push(await template`const ${raw(slice.dispatch)} = action => {
465
+ if (${raw(slice.caseObject)}[action.type]) ${raw(slice.hook)}.setState(state => produce(state, draft => ${raw(slice.caseObject)}[action.type](draft, action)), true);
466
+ };`.apply(statement, statementCursor));
467
+ }
468
+ statements.push({...padded, element: withPrefix(hook as Statement, statement.prefix)});
469
+ for (const generated of generatedStatements) {
470
+ const formatted = await autoFormat(withPrefix(generated as Statement, space("\n\n")), ctx, undefined, cursor);
471
+ statements.push({...padded, element: formatted as Statement});
472
+ }
473
+ continue;
474
+ }
475
+ const actions = actionsExport(statement, slice.variable);
476
+ if (actions) {
477
+ let first = true;
478
+ for (const {name} of actions) {
479
+ // RTK has no action creator for a name without a reducer, so the export is `undefined` there too
480
+ const generated = slice.unknown.has(name) ?
481
+ await template`export const ${raw(name)} = undefined;`.apply(statement, new Cursor(statement, cursor)) :
482
+ await template`export const ${raw(name)} = ${raw(slice.action)}(${raw(JSON.stringify(name))});`.apply(statement, new Cursor(statement, cursor));
483
+ statements.push({...padded, element: withPrefix(generated as Statement, first ? statement.prefix : space("\n"))});
484
+ first = false;
485
+ }
486
+ continue;
487
+ }
488
+ if (isReducerExport(statement, slice.variable, local.localReducers)) continue;
489
+ statements.push(padded);
490
+ }
491
+ let result = {...cu, statements} as JS.CompilationUnit;
492
+ result = await new class extends JavaScriptVisitor<ExecutionContext> {
493
+ override async visitJsCompilationUnit(unit: JS.CompilationUnit, p: ExecutionContext): Promise<J | undefined> {
494
+ const quoteStyle = quoteOf(cu);
495
+ maybeRemoveImport(this, RTK, "createSlice");
496
+ maybeAddImport(this, {module: ZUSTAND, member: "create", onlyIfReferenced: false, quoteStyle});
497
+ maybeAddImport(this, {module: IMMER, member: "freeze", onlyIfReferenced: false, quoteStyle});
498
+ maybeAddImport(this, {module: IMMER, member: "produce", onlyIfReferenced: false, quoteStyle});
499
+ return super.visitJsCompilationUnit(unit, p);
500
+ }
501
+ }().visit(result, ctx) as JS.CompilationUnit;
502
+ void visitor;
503
+ void scanned;
504
+ return result;
505
+ }
506
+
507
+ /** The quote of the source's first import, which the imports the conversion adds follow. */
508
+ function quoteOf(cu: JS.CompilationUnit): "'" | '"' | undefined {
509
+ for (const {element} of cu.statements) {
510
+ const specifier = element.kind === JS.Kind.Import ? (element as JS.Import).moduleSpecifier?.element : undefined;
511
+ const source = specifier?.kind === J.Kind.Literal ? (specifier as J.Literal).valueSource : undefined;
512
+ if (source?.startsWith("'")) return "'";
513
+ if (source?.startsWith('"')) return '"';
514
+ }
515
+ return undefined;
516
+ }
517
+
518
+ function withPrefix<T extends J>(node: T, prefix: J.Space): T {
519
+ return {...node, prefix} as T;
520
+ }
521
+
522
+ /** Rewrites the uses of react-redux, the store and its slices in a source. */
523
+ async function convertConsumer(cu: JS.CompilationUnit, p: Plan, scanned: Scanned, ctx: ExecutionContext): Promise<J | undefined> {
524
+ const bindings = importBindings(cu);
525
+ const followed = new Map(bindings.filter(b => b.module === REACT_REDUX || b.module.startsWith(".")).map(b => [b.local, b]));
526
+ const isStore = (name: string) => {
527
+ const binding = followed.get(name);
528
+ return !!binding && binding.module !== REACT_REDUX && resolveRelative(cu.sourcePath, binding.module, scanned.sources) === p.store!.path &&
529
+ binding.name === p.store!.exportedAs;
530
+ };
531
+ const reactRedux = (name: string, member: string) => followed.get(name)?.module === REACT_REDUX && followed.get(name)?.name === member;
532
+ const dispatchers = new Set<string>();
533
+ const hooks = new Set<PlannedSlice>();
534
+ const removed = new Set<string>();
535
+ const result = await new class extends JavaScriptVisitor<ExecutionContext> {
536
+ override async visitVariableDeclarations(declarations: J.VariableDeclarations, q: ExecutionContext): Promise<J | undefined> {
537
+ const variable = declarations.variables.length === 1 ? declarations.variables[0].element : undefined;
538
+ if (variable && isDispatcherDeclaration(variable, followed)) {
539
+ dispatchers.add((variable.name as J.Identifier).simpleName);
540
+ removed.add("useDispatch");
541
+ return undefined;
542
+ }
543
+ return super.visitVariableDeclarations(declarations, q);
544
+ }
545
+
546
+ override async visitMethodInvocation(call: J.MethodInvocation, q: ExecutionContext): Promise<J | undefined> {
547
+ const visited = await super.visitMethodInvocation(call, q) as J.MethodInvocation;
548
+ // `dispatch(x())` and `store.dispatch(x())`, which are statements, become `x()`
549
+ const action = dispatchedAction(visited);
550
+ if (action && (!visited.select && dispatchers.has(visited.name.simpleName) ||
551
+ visited.select && isIdentifier(visited.select.element) && isStore(visited.select.element.simpleName) && visited.name.simpleName === "dispatch")) {
552
+ if (visited.select) removed.add("store");
553
+ return withPrefix(action, visited.prefix);
554
+ }
555
+ if (!visited.select && reactRedux(visited.name.simpleName, "useSelector")) {
556
+ const read = selectorRead(argumentsOf(visited)[0]);
557
+ const slice = read && p.slices.get(read.key);
558
+ if (!read || !slice) return visited;
559
+ hooks.add(slice);
560
+ removed.add("useSelector");
561
+ // `state => state.counter` is the whole slice store
562
+ if ((read.lambda.body as J) === read.read) {
563
+ return withPrefix(await template`${raw(slice.hook)}()`.apply(visited, this.cursor) as J, visited.prefix);
564
+ }
565
+ const lambda = read.lambda;
566
+ const body = replaceTree(lambda.body as J, read.read, read.read.target) as J;
567
+ const arg = argumentsOf(visited)[0];
568
+ const rewritten = arg.kind === JS.Kind.ArrowFunction ? {...arg, lambda: {...lambda, body}} : {...lambda, body};
569
+ return create(visited, draft => {
570
+ draft.name = {...draft.name, simpleName: slice.hook, fieldType: undefined, type: undefined} as any;
571
+ draft.methodType = undefined;
572
+ draft.arguments.elements[0].element = rewritten as any;
573
+ }) as J.MethodInvocation;
574
+ }
575
+ return visited;
576
+ }
577
+
578
+ override async visitFieldAccess(access: J.FieldAccess, q: ExecutionContext): Promise<J | undefined> {
579
+ const target = access.target;
580
+ if (target.kind === J.Kind.MethodInvocation) {
581
+ const call = target as J.MethodInvocation;
582
+ const read = call.select && isIdentifier(call.select.element) && isStore(call.select.element.simpleName) ? getStateRead(call, access) : undefined;
583
+ const slice = read && p.slices.get(read.key);
584
+ if (slice) {
585
+ hooks.add(slice);
586
+ removed.add("store");
587
+ return withPrefix(await template`${raw(slice.hook)}.getState()`.apply(access, this.cursor) as J, access.prefix);
588
+ }
589
+ }
590
+ return super.visitFieldAccess(access, q);
591
+ }
592
+
593
+ override async visitNewArray(array: J.NewArray, q: ExecutionContext): Promise<J | undefined> {
594
+ const visited = await super.visitNewArray(array, q) as J.NewArray;
595
+ if (!visited.initializer || !isReactDependencies(array, parentTree(this.cursor), bindings)) return visited;
596
+ const elements = visited.initializer.elements;
597
+ const kept = elements.filter(({element}) => !(isIdentifier(element) && dispatchers.has(element.simpleName)));
598
+ if (kept.length === elements.length) return visited;
599
+ return create(visited, draft => {
600
+ draft.initializer!.elements = (kept.length === 0
601
+ ? [{...elements[elements.length - 1], element: {kind: J.Kind.Empty, id: randomId(), prefix: space(""), markers: emptyMarkers}}]
602
+ : kept.map((padded, i) => ({
603
+ ...padded,
604
+ element: i === 0 ? {...padded.element, prefix: elements[0].element.prefix} : padded.element,
605
+ after: i === kept.length - 1 ? elements[elements.length - 1].after : padded.after
606
+ }))) as any;
607
+ }) as J.NewArray;
608
+ }
609
+
610
+ override async visitJsxTag(tag: JSX.Tag, q: ExecutionContext): Promise<J | undefined> {
611
+ const name = tag.openName.element;
612
+ if (isIdentifier(name) && reactRedux(name.simpleName, "Provider")) {
613
+ const child = providerChild(tag);
614
+ if (child) {
615
+ removed.add("Provider");
616
+ removed.add("store");
617
+ return withPrefix(await this.visit(child, q, this.cursor) as JSX.Tag, tag.prefix);
618
+ }
619
+ }
620
+ return super.visitJsxTag(tag, q);
621
+ }
622
+ }().visit(cu, ctx) as JS.CompilationUnit;
623
+ return await new class extends JavaScriptVisitor<ExecutionContext> {
624
+ override async visitJsCompilationUnit(unit: JS.CompilationUnit, q: ExecutionContext): Promise<J | undefined> {
625
+ for (const member of ["useSelector", "useDispatch", "Provider"]) {
626
+ if (removed.has(member)) maybeRemoveImport(this, REACT_REDUX, member);
627
+ }
628
+ // The store's source is removed, so no import of it may stay, even one nothing here used
629
+ for (const binding of bindings) {
630
+ if (binding.module !== REACT_REDUX && isStore(binding.local)) maybeRemoveImport(this, binding.module, binding.name);
631
+ }
632
+ for (const slice of hooks) {
633
+ maybeAddImport(this, {module: relativeSpecifier(cu.sourcePath, slice.path), member: slice.hook, onlyIfReferenced: false, quoteStyle: quoteOf(cu)});
634
+ }
635
+ return super.visitJsCompilationUnit(unit, q);
636
+ }
637
+ }().visit(result, ctx);
638
+ }
639
+
640
+ /** `root` with the tree `target` replaced by `replacement`, keeping the target's prefix. */
641
+ function replaceTree(root: J, target: J, replacement: J): J {
642
+ if (root === target) return {...replacement, prefix: target.prefix} as J;
643
+ return create(root, draft => {
644
+ const replace = (node: any): boolean => {
645
+ if (!node || typeof node !== "object") return false;
646
+ for (const [key, value] of Object.entries(node)) {
647
+ if (value && typeof value === "object" && (value as any).id === target.id) {
648
+ node[key] = {...replacement, prefix: target.prefix};
649
+ return true;
650
+ }
651
+ if (value && typeof value === "object" && replace(value)) return true;
652
+ }
653
+ return false;
654
+ };
655
+ replace(draft);
656
+ }) as J;
657
+ }