@openrewrite/recipes-react 0.19.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/i18n/translate-hard-coded-strings.d.ts +67 -0
- package/dist/i18n/translate-hard-coded-strings.d.ts.map +1 -0
- package/dist/i18n/translate-hard-coded-strings.js +439 -0
- package/dist/i18n/translate-hard-coded-strings.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -1
- package/dist/index.js.map +1 -1
- package/dist/search/find-enzyme-usage.d.ts +4 -0
- package/dist/search/find-enzyme-usage.d.ts.map +1 -1
- package/dist/search/find-enzyme-usage.js +64 -4
- package/dist/search/find-enzyme-usage.js.map +1 -1
- package/dist/search/find-hard-coded-strings.d.ts +110 -0
- package/dist/search/find-hard-coded-strings.d.ts.map +1 -0
- package/dist/search/find-hard-coded-strings.js +987 -0
- package/dist/search/find-hard-coded-strings.js.map +1 -0
- package/dist/search/find-missing-use-client-directive.d.ts +2 -0
- package/dist/search/find-missing-use-client-directive.d.ts.map +1 -1
- package/dist/search/find-missing-use-client-directive.js +1 -0
- package/dist/search/find-missing-use-client-directive.js.map +1 -1
- package/dist/testing/enzyme-portals.d.ts +3 -5
- package/dist/testing/enzyme-portals.d.ts.map +1 -1
- package/dist/testing/enzyme-portals.js +8 -39
- package/dist/testing/enzyme-portals.js.map +1 -1
- package/dist/testing/enzyme-render-blockers.d.ts +10 -0
- package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
- package/dist/testing/enzyme-render-blockers.js +119 -0
- package/dist/testing/enzyme-render-blockers.js.map +1 -0
- package/dist/testing/enzyme-shared-wrapper.d.ts +26 -0
- package/dist/testing/enzyme-shared-wrapper.d.ts.map +1 -0
- package/dist/testing/enzyme-shared-wrapper.js +213 -0
- package/dist/testing/enzyme-shared-wrapper.js.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts +9 -2
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +355 -16
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts +5 -1
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +48 -6
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +7 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +24 -9
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/util/json-and-javascript.d.ts +4 -0
- package/dist/util/json-and-javascript.d.ts.map +1 -0
- package/dist/util/json-and-javascript.js +37 -0
- package/dist/util/json-and-javascript.js.map +1 -0
- package/dist/util/module-imports.d.ts +36 -0
- package/dist/util/module-imports.d.ts.map +1 -1
- package/dist/util/module-imports.js +216 -0
- package/dist/util/module-imports.js.map +1 -1
- package/dist/util/test-source.d.ts +2 -0
- package/dist/util/test-source.d.ts.map +1 -0
- package/dist/util/test-source.js +5 -0
- package/dist/util/test-source.js.map +1 -0
- package/dist/zustand/entry-store.d.ts +9 -0
- package/dist/zustand/entry-store.d.ts.map +1 -0
- package/dist/zustand/entry-store.js +136 -0
- package/dist/zustand/entry-store.js.map +1 -0
- package/dist/zustand/redux-stores.d.ts +15 -4
- package/dist/zustand/redux-stores.d.ts.map +1 -1
- package/dist/zustand/redux-stores.js +155 -10
- package/dist/zustand/redux-stores.js.map +1 -1
- package/dist/zustand/redux-to-zustand.d.ts +29 -5
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
- package/dist/zustand/redux-to-zustand.js +629 -42
- package/dist/zustand/redux-to-zustand.js.map +1 -1
- package/dist/zustand/zustand-plan.d.ts +31 -6
- package/dist/zustand/zustand-plan.d.ts.map +1 -1
- package/dist/zustand/zustand-plan.js +320 -31
- package/dist/zustand/zustand-plan.js.map +1 -1
- package/package.json +1 -1
- package/src/i18n/translate-hard-coded-strings.ts +442 -0
- package/src/index.ts +7 -0
- package/src/search/find-enzyme-usage.ts +59 -6
- package/src/search/find-hard-coded-strings.ts +1006 -0
- package/src/search/find-missing-use-client-directive.ts +1 -1
- package/src/testing/enzyme-portals.ts +4 -44
- package/src/testing/enzyme-render-blockers.ts +113 -0
- package/src/testing/enzyme-shared-wrapper.ts +224 -0
- package/src/testing/enzyme-to-react-testing-library.ts +354 -19
- package/src/testing/enzyme-usage.ts +62 -5
- package/src/testing/enzyme-wrapper-scope.ts +24 -6
- package/src/util/json-and-javascript.ts +26 -0
- package/src/util/module-imports.ts +223 -0
- package/src/util/test-source.ts +2 -0
- package/src/zustand/entry-store.ts +131 -0
- package/src/zustand/redux-stores.ts +171 -11
- package/src/zustand/redux-to-zustand.ts +689 -48
- package/src/zustand/zustand-plan.ts +350 -29
|
@@ -1,28 +1,31 @@
|
|
|
1
|
-
import {Cursor, DataTable, emptyMarkers, ExecutionContext, Markup, MarkersKind, or, randomId, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
1
|
+
import {Cursor, DataTable, emptyMarkers, ExecutionContext, Markup, MarkersKind, Option, or, randomId, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
2
|
import {
|
|
3
|
-
AddDependencyOptions, autoFormat, findNodeResolutionResult, isVendoredOrBundled, JavaScriptVisitor, JS, JSX, maybeAddImport, maybeRemoveImport, raw, template
|
|
3
|
+
AddDependencyOptions, autoFormat, ChangeImport, findNodeResolutionResult, isVendoredOrBundled, JavaScriptVisitor, JS, JSX, maybeAddImport, maybeRemoveImport, raw, template
|
|
4
4
|
} from "@openrewrite/rewrite/javascript";
|
|
5
|
-
import {isIdentifier, J, Statement} from "@openrewrite/rewrite/java";
|
|
5
|
+
import {emptySpace, isIdentifier, J, Statement} from "@openrewrite/rewrite/java";
|
|
6
6
|
import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
|
|
7
7
|
import {create} from "mutative";
|
|
8
8
|
import {minVersion, satisfies, valid, validRange} from "semver";
|
|
9
9
|
import {check, not} from "@openrewrite/rewrite";
|
|
10
10
|
import {JavaDependencyRecipe, treesOfType} from "../util/java-recipe-proxy";
|
|
11
|
-
import {importBindings,
|
|
11
|
+
import {addPathsConfig, importBindings, isAliasSpecifier, PathsConfigs, Resolve, resolveModule} from "../util/module-imports";
|
|
12
12
|
import {rewriteVersion, supportsResolvingGate} from "../testing/enzyme-to-react-testing-library";
|
|
13
|
-
import {
|
|
13
|
+
import {ENTRY_STORE_MODULE, EntrySplit, splitEntryStore} from "./entry-store";
|
|
14
|
+
import {caseReducers, Finding, importedAs, legacyEnhancer, localSlices, objectProperties, preloadedValue, REDUX_STORES_TABLE, ReduxStoreRow, REDUX, RTK, SliceModule, storeFunctions, SUGGESTED_ACTIONS, TEST_SOURCE} from "./redux-stores";
|
|
14
15
|
import {
|
|
15
|
-
actionsExport, argumentsOf, dispatchedAction, getStateRead, isDispatcherDeclaration, isReactDependencies, isReducerExport, parentTree, Plan, planPackages, PlannedSlice, providerChild,
|
|
16
|
-
REACT_REDUX, relativeSpecifier, selectorRead, sliceSource, SliceSource, SourceFacts, sourceFacts, storeFacts
|
|
16
|
+
actionsExport, argumentsOf, dispatchedAction, getStateRead, isDispatcherDeclaration, isReactDependencies, isReducerExport, parentTree, Plan, planPackages, PlannedSlice, providerChild, providerChildren,
|
|
17
|
+
REACT_REDUX, readSelector, relativeSpecifier, selectorRead, sliceSource, SliceSource, SourceFacts, sourceFacts, StoreFacts, storeFacts
|
|
17
18
|
} from "./zustand-plan";
|
|
18
19
|
|
|
19
20
|
const ZUSTAND = "zustand";
|
|
20
21
|
const IMMER = "immer";
|
|
21
22
|
|
|
22
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* zustand 5 needs React 18; zustand 4 supports React 16.8 and up. No `onlyIfDeclaring`: only a package whose store
|
|
25
|
+
* converts reaches the Java recipe, and one with a legacy `createStore`, or Redux from a workspace root, declares no RTK.
|
|
26
|
+
*/
|
|
23
27
|
const ZUSTAND_5: AddDependencyOptions = {
|
|
24
|
-
packageName: ZUSTAND, version: "^5.0.8", scope: "dependencies",
|
|
25
|
-
onlyIfResolving: ["react@>=18.0.0"]
|
|
28
|
+
packageName: ZUSTAND, version: "^5.0.8", scope: "dependencies", onlyIfResolving: ["react@>=18.0.0"]
|
|
26
29
|
};
|
|
27
30
|
const ZUSTAND_4: AddDependencyOptions = {...ZUSTAND_5, version: "^4.5.7", onlyIfResolving: ["react@>=16.8.0 <18"]};
|
|
28
31
|
const IMMER_10: AddDependencyOptions = {...ZUSTAND_5, packageName: IMMER, version: "^10.1.3", onlyIfResolving: ["react@>=16.8.0"]};
|
|
@@ -37,6 +40,8 @@ export interface ZustandForecast {
|
|
|
37
40
|
refused?: Map<string, {message: string, lock: string}>;
|
|
38
41
|
/** The React range a package root declares, which picks the zustand step as Java's resolution gate can't where nothing resolved. */
|
|
39
42
|
react?: (root: string) => string | undefined;
|
|
43
|
+
/** The converting package roots whose store moves whole, which need no immer. Filled as `converting` resolves. */
|
|
44
|
+
withoutImmer?: Set<string>;
|
|
40
45
|
}
|
|
41
46
|
|
|
42
47
|
const LOCKFILE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lock)$/;
|
|
@@ -44,8 +49,13 @@ const LOCKFILE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm
|
|
|
44
49
|
/** A package's dependencies, as far as the conversion needs them. */
|
|
45
50
|
interface PackageFacts {
|
|
46
51
|
react?: string;
|
|
52
|
+
reactDom?: string;
|
|
53
|
+
reactNative?: string;
|
|
47
54
|
zustand?: string;
|
|
48
55
|
immer?: string;
|
|
56
|
+
redux?: string;
|
|
57
|
+
toolkit?: string;
|
|
58
|
+
reactRedux?: string;
|
|
49
59
|
}
|
|
50
60
|
|
|
51
61
|
interface Scanned {
|
|
@@ -53,18 +63,38 @@ interface Scanned {
|
|
|
53
63
|
modules: Map<string, SliceModule>;
|
|
54
64
|
sliceSources: Map<string, SliceSource>;
|
|
55
65
|
packages: Map<string, PackageFacts>;
|
|
66
|
+
/** The `paths` of each directory's `tsconfig.json`, or else its `jsconfig.json`, by the directory. */
|
|
67
|
+
configs: PathsConfigs;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Resolves a specifier among the scanned sources, an alias through the nearest config's `paths`. */
|
|
71
|
+
function resolverOf(scanned: Scanned): Resolve {
|
|
72
|
+
return (from, specifier) => resolveModule(from, specifier, scanned.sources, scanned.configs);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Whether a source's import of a specifier is one the conversion follows: react-redux's, or one that may name a source. */
|
|
76
|
+
function followsImport(module: string): boolean {
|
|
77
|
+
return module === REACT_REDUX || module.startsWith(".") || isAliasSpecifier(module);
|
|
56
78
|
}
|
|
57
79
|
|
|
80
|
+
/** A source split so that the store it creates and doesn't export moves to `modulePath`. */
|
|
81
|
+
type Split = EntrySplit & {modulePath: string};
|
|
82
|
+
|
|
58
83
|
/** Adds a dependency to the package whose Redux store converts, with the gates of Java's `AddDependency`. */
|
|
59
84
|
abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
60
85
|
/** The package roots whose `package.json` declares the dependency once this run's edit lands. Mutated in place. */
|
|
61
86
|
readonly landed = new Set<string>();
|
|
62
87
|
private readonly held: Json.Document[] = [];
|
|
63
88
|
private readonly locks: SourceFile[] = [];
|
|
89
|
+
/** The lockfiles of the packages whose dependency is forwarded; the Java recipe's edit of any other lockfile is dropped. */
|
|
90
|
+
private readonly owned = new Set<string>();
|
|
91
|
+
/** Each workspace root's package globs, from `workspaces` in its `package.json` or from `pnpm-workspace.yaml`. */
|
|
92
|
+
private readonly workspaces = new Map<string, string[]>();
|
|
93
|
+
private readonly pending: SourceFile[] = [];
|
|
64
94
|
/** The converting package roots whose declared React this step's version doesn't support, left alone. */
|
|
65
95
|
private readonly unfit = new Set<string>();
|
|
66
96
|
|
|
67
|
-
protected constructor(private readonly addition: AddDependencyOptions,
|
|
97
|
+
protected constructor(private readonly addition: AddDependencyOptions, protected readonly forecast: ZustandForecast) {
|
|
68
98
|
super("org.openrewrite.javascript.AddDependency", addition);
|
|
69
99
|
}
|
|
70
100
|
|
|
@@ -73,6 +103,9 @@ abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
|
73
103
|
this.unfit.clear();
|
|
74
104
|
this.held.length = 0;
|
|
75
105
|
this.locks.length = 0;
|
|
106
|
+
this.owned.clear();
|
|
107
|
+
this.workspaces.clear();
|
|
108
|
+
this.pending.length = 0;
|
|
76
109
|
this.forecast.refused?.clear();
|
|
77
110
|
return super.initialValue();
|
|
78
111
|
}
|
|
@@ -82,6 +115,7 @@ abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
|
82
115
|
this.held.push(manifest as Json.Document);
|
|
83
116
|
return false;
|
|
84
117
|
}
|
|
118
|
+
if (/(^|\/)pnpm-workspace\.yaml$/.test(manifest.sourcePath)) this.pending.push(manifest);
|
|
85
119
|
if (LOCKFILE.test(manifest.sourcePath)) this.locks.push(manifest);
|
|
86
120
|
return true;
|
|
87
121
|
}
|
|
@@ -90,12 +124,20 @@ abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
|
90
124
|
if (/(^|\/)package\.json$/.test(manifest.sourcePath) && this.unfit.has(packageRoot(manifest.sourcePath))) return false;
|
|
91
125
|
// The package's own lockfile stays too; a workspace's lockfile is the other packages' as well
|
|
92
126
|
if (LOCKFILE.test(manifest.sourcePath) && this.unfit.has(manifest.sourcePath.slice(0, manifest.sourcePath.lastIndexOf("/") + 1))) return false;
|
|
127
|
+
// NOTE: Java's AddDependency regenerates the lockfile of the nearest directory above even where that lockfile
|
|
128
|
+
// installs a workspace the package isn't in, and the new lockfile then holds this package alone
|
|
129
|
+
if (LOCKFILE.test(manifest.sourcePath) && !this.owned.has(manifest.sourcePath)) return false;
|
|
93
130
|
const refused = this.forecast.refused;
|
|
94
131
|
if (!refused?.size) return true;
|
|
95
132
|
if (/(^|\/)package\.json$/.test(manifest.sourcePath)) return !refused.has(packageRoot(manifest.sourcePath));
|
|
96
133
|
return ![...refused.values()].some(refusal => refusal.lock === manifest.sourcePath);
|
|
97
134
|
}
|
|
98
135
|
|
|
136
|
+
/** The converting package roots this step leaves alone. */
|
|
137
|
+
protected skipped(): Iterable<string> {
|
|
138
|
+
return [];
|
|
139
|
+
}
|
|
140
|
+
|
|
99
141
|
/** Whether the React range the package at `root` declares is one this step's version supports, as `onlyIfResolving` asks. */
|
|
100
142
|
private fits(root: string): boolean {
|
|
101
143
|
const declared = this.forecast.react?.(root);
|
|
@@ -108,26 +150,49 @@ abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
|
108
150
|
/** The lockfile that installs the package at `root`: its own, or that of the workspace it is in. */
|
|
109
151
|
private lockOf(root: string): SourceFile | undefined {
|
|
110
152
|
const directory = (path: string) => path.slice(0, path.lastIndexOf("/") + 1);
|
|
111
|
-
return this.locks.filter(lock =>
|
|
112
|
-
|
|
153
|
+
return this.locks.filter(lock => {
|
|
154
|
+
const base = directory(lock.sourcePath);
|
|
155
|
+
return root === base || root.startsWith(base) && member(this.workspaces.get(base) ?? [], root.slice(base.length, -1));
|
|
156
|
+
}).sort((a, b) => b.sourcePath.length - a.sourcePath.length)[0];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Reads the workspace globs of each scanned `package.json` and `pnpm-workspace.yaml`. */
|
|
160
|
+
private async readWorkspaces(): Promise<void> {
|
|
161
|
+
for (const manifest of this.held) {
|
|
162
|
+
const globs = workspaceGlobs(await parsed(manifest));
|
|
163
|
+
if (globs.length) this.workspaces.set(packageRoot(manifest.sourcePath), globs);
|
|
164
|
+
}
|
|
165
|
+
for (const file of this.pending) {
|
|
166
|
+
const root = file.sourcePath.slice(0, -"pnpm-workspace.yaml".length);
|
|
167
|
+
this.workspaces.set(root, [...this.workspaces.get(root) ?? [], ...pnpmPackages(await TreePrinters.print(file))]);
|
|
168
|
+
}
|
|
113
169
|
}
|
|
114
170
|
|
|
115
171
|
override async generate(acc: number, ctx: ExecutionContext): Promise<SourceFile[]> {
|
|
116
|
-
const converting = await this.forecast.converting?.() ??
|
|
172
|
+
const converting = new Set(await this.forecast.converting?.() ?? []);
|
|
173
|
+
for (const root of this.skipped()) converting.delete(root);
|
|
117
174
|
// NOTE: Java's `onlyIfResolving` passes where nothing resolved React, such as a package without a lockfile
|
|
118
175
|
for (const root of converting) if (!this.fits(root)) this.unfit.add(root);
|
|
119
176
|
const forwarded = this.held.filter(manifest => converting.has(packageRoot(manifest.sourcePath)) && !this.unfit.has(packageRoot(manifest.sourcePath)));
|
|
177
|
+
await this.readWorkspaces();
|
|
120
178
|
const scanner = await this.java.scanner(acc);
|
|
121
179
|
for (const manifest of forwarded) await scanner.visit(manifest, ctx);
|
|
122
180
|
const generated = await super.generate(acc, ctx);
|
|
123
181
|
const editor = await this.java.editorWithData(acc);
|
|
124
182
|
for (const manifest of forwarded) {
|
|
125
183
|
const edited = await editor.visit<Json.Document>(manifest, ctx);
|
|
126
|
-
if (!edited || edited === manifest
|
|
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
|
|
184
|
+
if (!edited || edited === manifest) continue;
|
|
129
185
|
const root = packageRoot(manifest.sourcePath);
|
|
186
|
+
if (!await declares(edited, this.addition.packageName)) {
|
|
187
|
+
// NOTE: a current `AddDependency` takes its edit back where the lockfile can't be regenerated, and says why on the manifest
|
|
188
|
+
const warning = newWarning(manifest, edited);
|
|
189
|
+
if (warning) this.forecast.refused?.set(root, {message: warning.message, lock: this.lockOf(root)?.sourcePath ?? manifest.sourcePath});
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
// NOTE: where the package manager's lock can't be reproduced, `AddDependency` 8.94 still declares the package
|
|
193
|
+
// and only warns on the lockfile, which an install from the lockfile, as in CI, would then refuse
|
|
130
194
|
const lock = this.lockOf(root);
|
|
195
|
+
if (lock) this.owned.add(lock.sourcePath);
|
|
131
196
|
const regenerated = lock ? await editor.visit<SourceFile>(lock, ctx) : undefined;
|
|
132
197
|
const warning = regenerated?.markers.markers.find(marker => marker.kind === MarkersKind.MarkupWarn || marker.kind === MarkersKind.MarkupError) as Markup | undefined;
|
|
133
198
|
if (warning) this.forecast.refused?.set(root, {message: warning.message, lock: lock!.sourcePath});
|
|
@@ -138,11 +203,18 @@ abstract class ZustandDependency extends JavaDependencyRecipe {
|
|
|
138
203
|
}
|
|
139
204
|
}
|
|
140
205
|
|
|
206
|
+
/** The warning or error the Java recipe put on `after` that `before` didn't carry. */
|
|
207
|
+
function newWarning(before: SourceFile, after: SourceFile): Markup | undefined {
|
|
208
|
+
const had = new Set(before.markers.markers.map(marker => marker.id));
|
|
209
|
+
return after.markers.markers.find(marker => !had.has(marker.id) &&
|
|
210
|
+
(marker.kind === MarkersKind.MarkupWarn || marker.kind === MarkersKind.MarkupError)) as Markup | undefined;
|
|
211
|
+
}
|
|
212
|
+
|
|
141
213
|
/** Adds zustand 5 where a store of a package on React 18 or later converts. */
|
|
142
214
|
export class AddZustand extends ZustandDependency {
|
|
143
215
|
readonly name = "org.openrewrite.react.migrate.add-zustand";
|
|
144
216
|
readonly displayName = "Add `zustand` where a Redux store is migrated";
|
|
145
|
-
readonly description = "Adds `zustand` 5 to packages that
|
|
217
|
+
readonly description = "Adds `zustand` 5 to packages that resolve React 18 or later, where a Redux store moves to zustand.";
|
|
146
218
|
|
|
147
219
|
constructor(forecast: ZustandForecast = {}) {
|
|
148
220
|
super(ZUSTAND_5, forecast);
|
|
@@ -153,7 +225,7 @@ export class AddZustand extends ZustandDependency {
|
|
|
153
225
|
export class AddZustand4 extends ZustandDependency {
|
|
154
226
|
readonly name = "org.openrewrite.react.migrate.add-zustand-4";
|
|
155
227
|
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
|
|
228
|
+
readonly description = "Adds `zustand` 4 to packages that resolve React 16.8 to 17, where a Redux store moves to zustand.";
|
|
157
229
|
|
|
158
230
|
constructor(forecast: ZustandForecast = {}) {
|
|
159
231
|
super(ZUSTAND_4, forecast);
|
|
@@ -164,11 +236,15 @@ export class AddZustand4 extends ZustandDependency {
|
|
|
164
236
|
export class AddImmer extends ZustandDependency {
|
|
165
237
|
readonly name = "org.openrewrite.react.migrate.add-immer";
|
|
166
238
|
readonly displayName = "Add `immer` where a Redux store is migrated";
|
|
167
|
-
readonly description = "Adds `immer` 10 to packages that
|
|
239
|
+
readonly description = "Adds `immer` 10 to packages that resolve React 16.8 or later, where a Redux store moves to zustand and its slices' reducers run through `produce`.";
|
|
168
240
|
|
|
169
241
|
constructor(forecast: ZustandForecast = {}) {
|
|
170
242
|
super(IMMER_10, forecast);
|
|
171
243
|
}
|
|
244
|
+
|
|
245
|
+
protected override skipped(): Iterable<string> {
|
|
246
|
+
return this.forecast.withoutImmer ?? [];
|
|
247
|
+
}
|
|
172
248
|
}
|
|
173
249
|
|
|
174
250
|
/** Older hosts drop `onlyIfResolving`, which would add zustand 5 to packages on React 17, so the steps run only where the host has it. */
|
|
@@ -192,21 +268,67 @@ const ADDS_DEPENDENCIES = (() => {
|
|
|
192
268
|
* - `dispatch(increment())` and `store.dispatch(increment())`, whose result is unused, become `increment()`, and
|
|
193
269
|
* `const dispatch = useDispatch()` goes;
|
|
194
270
|
* - `store.getState().counter` becomes `useCounterStore.getState()`;
|
|
195
|
-
* - `<Provider store={store}>` is replaced with its one child, and the store's
|
|
271
|
+
* - `<Provider store={store}>` is replaced with its one child, or a fragment `<>` of its children, and the store's
|
|
272
|
+
* source is removed;
|
|
196
273
|
* - a `createAsyncThunk` of the slice's source whose stages `extraReducers` handles stays RTK's, and runs its actions
|
|
197
274
|
* through those cases on the slice's zustand store; a dispatch of it becomes a call.
|
|
198
275
|
*
|
|
199
|
-
*
|
|
200
|
-
*
|
|
276
|
+
* A `configureStore` of its `reducer` alone whose slices can't move one by one, such as one with a reducer that is no
|
|
277
|
+
* slice's, a thunk that reaches the rest of the store or a dispatch whose result is used, moves whole instead:
|
|
278
|
+
*
|
|
279
|
+
* - the store's reducer, combined as `configureStore` combines it, runs on one zustand store, `useAppStore`, whose
|
|
280
|
+
* `dispatch` runs a thunk as Redux Toolkit's default middleware does, and any other action through the reducer
|
|
281
|
+
* once it is a plain object with a `type`, a string on Redux 5, and throws otherwise, as Redux does;
|
|
282
|
+
* - the store's variable keeps the store's `getState` and `dispatch`, so their uses stay as they are, in the store's
|
|
283
|
+
* source too, as do the slices, their action creators and thunks;
|
|
284
|
+
* - where the store's source or another calls `store.subscribe(listener)`, the store keeps a `subscribe` too, whose
|
|
285
|
+
* listeners its `dispatch` calls after every action, changed state or not, as they were when the dispatch began, as
|
|
286
|
+
* Redux does. They are called before the components render, as Redux calls the listeners that subscribe before
|
|
287
|
+
* react-redux's `Provider` does; one that subscribes once they are mounted, which Redux calls after they render, is too;
|
|
288
|
+
* - `useSelector(state => state.counter.value)` becomes `useAppStore(state => state.counter.value)`, as does
|
|
289
|
+
* `useSelector(selectValue)` of a top-level `const selectValue = state => state.counter.value`, declared in the source
|
|
290
|
+
* or imported from another, `const dispatch = useDispatch()` becomes `const dispatch = useAppStore.dispatch`, and
|
|
291
|
+
* the `Provider` goes, as above;
|
|
292
|
+
* - any other `useSelector(selector)`, such as one that builds a value, becomes `useAppStore(selector)` on zustand 4,
|
|
293
|
+
* whose hook keeps the selection per state as react-redux's does, and on zustand 5, whose hook runs the selector on
|
|
294
|
+
* each read, `useAppStoreSelector(selector)`, a hook the store's source declares that keeps it.
|
|
295
|
+
*
|
|
296
|
+
* A legacy `createStore(reducer)` or `createStore(reducer, preloadedState)`, of a preloaded state written as a value,
|
|
297
|
+
* moves whole the same way. It has no middleware, so its `dispatch` runs no thunk, and its state starts from the
|
|
298
|
+
* preloaded state. One
|
|
299
|
+
* whose enhancer is `applyMiddleware(thunk)`, perhaps inside `compose` or Redux DevTools, also runs a function it is
|
|
300
|
+
* dispatched with `dispatch` and `getState`, as redux-thunk does; DevTools is dropped.
|
|
301
|
+
*
|
|
302
|
+
* A store that moves whole also takes its components connected with `connect`, with no `mergeProps` and no option
|
|
303
|
+
* but `forwardRef`: the store's source declares a `connect` that passes the props, copies the statics and skips the
|
|
304
|
+
* re-renders react-redux's does, reading the zustand store, and each source imports it from there. The store then
|
|
305
|
+
* batches its updates with `unstable_batchedUpdates`, as react-redux does, so that before React 18 a parent renders
|
|
306
|
+
* before a child it removes.
|
|
307
|
+
*
|
|
308
|
+
* Any other use, such as `connect` with `mergeProps`, `persistStore(store)`, or a selector with its own equality function, keeps the
|
|
309
|
+
* store in Redux, recorded in the `ReduxStores` table with the reason.
|
|
201
310
|
*
|
|
202
311
|
* @see https://zustand.docs.pmnd.rs/guides/migrating-to-zustand
|
|
203
312
|
*/
|
|
204
313
|
export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
205
314
|
readonly name = "org.openrewrite.react.migrate.redux-to-zustand";
|
|
206
315
|
readonly displayName = "Migrate Redux Toolkit slices to zustand";
|
|
207
|
-
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
|
|
316
|
+
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`, replaced with its children, and the store's source are removed. A slice's own `createAsyncThunk`s, whose stages its `extraReducers` handles, keep running on Redux Toolkit and send their actions to the slice's zustand store. A store of its `reducer` alone whose slices can't move one by one, such as one with a reducer that is no slice's, thunks that reach the rest of the store or dispatches whose result is used, moves whole: its reducer runs on one zustand store whose `dispatch` runs thunks as Redux Toolkit's default middleware does, its selectors run on that store, through a hook of the store's source that keeps each selection per state where zustand 5 would run the selector on each read, and the store keeps its `getState` and `dispatch`, and its `subscribe`, whose listeners its `dispatch` calls after every action as Redux does, where a source subscribes to it. A legacy `createStore` of a reducer, and perhaps a preloaded state, moves whole too, its `dispatch` taking plain actions only, as Redux's does without middleware, or thunks as well where its enhancer is `applyMiddleware(thunk)`, perhaps inside `compose` or Redux DevTools, which is dropped. Components connected with `connect`, with no `mergeProps` and no option but `forwardRef`, move with a store that moves whole: its source declares a `connect` for the zustand store that passes the same props, copies the same statics and skips the same re-renders as react-redux's, and the store batches its updates as react-redux does. A store that moves whole but is created, and not exported, at the top level of an application's entry source, such as the one that renders the `Provider`, moves to an `appStore` module beside that source, with the imports and top-level `const`s and `let`s only it uses, and the source imports back what it still uses. A store's source may export it in its declaration, as its default export or in an export list such as `export {store}`, and other sources may import it, and its slices, by relative paths or by aliases such as `@/store` that the `paths` of the nearest `tsconfig.json` or `jsconfig.json` declare. Adds `zustand`, and `immer` where slices move one by one, where they are missing. Stores with any other use, such as `connect` with `mergeProps`, other middleware or enhancers, other uses of the store object such as `persistStore(store)`, selectors with their own equality function or several stores, stay in Redux and are recorded for review.";
|
|
317
|
+
|
|
318
|
+
@Option({
|
|
319
|
+
displayName: "Move stores whole",
|
|
320
|
+
description: "Whether a store whose slices can't move to zustand one by one moves whole: one zustand store driven by the store's own reducer. Defaults to true.",
|
|
321
|
+
required: false,
|
|
322
|
+
type: "Boolean"
|
|
323
|
+
})
|
|
324
|
+
wholeStores?: boolean;
|
|
325
|
+
|
|
326
|
+
constructor(options?: {wholeStores?: boolean}) {
|
|
327
|
+
super(options);
|
|
328
|
+
this.wholeStores ??= true;
|
|
329
|
+
}
|
|
208
330
|
|
|
209
|
-
private readonly forecast: ZustandForecast = {refused: new Map()};
|
|
331
|
+
private readonly forecast: ZustandForecast = {refused: new Map(), withoutImmer: new Set()};
|
|
210
332
|
private readonly storeSources: JS.CompilationUnit[] = [];
|
|
211
333
|
/** The packages the dependency steps were asked to change, once they ask. */
|
|
212
334
|
private asked?: ReadonlySet<string>;
|
|
@@ -220,7 +342,7 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
220
342
|
|
|
221
343
|
initialValue(): Scanned {
|
|
222
344
|
this.storeSources.length = 0;
|
|
223
|
-
return {sources: new Map(), modules: new Map(), sliceSources: new Map(), packages: new Map()};
|
|
345
|
+
return {sources: new Map(), modules: new Map(), sliceSources: new Map(), packages: new Map(), configs: new Map()};
|
|
224
346
|
}
|
|
225
347
|
|
|
226
348
|
async scanner(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
@@ -228,8 +350,11 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
228
350
|
let forecast: Promise<ReadonlySet<string>> | undefined;
|
|
229
351
|
this.asked = undefined;
|
|
230
352
|
this.forecast.react = root => scanned.packages.get(root)?.react;
|
|
231
|
-
this.forecast.converting = () => forecast ??= this.planned(scanned, true)
|
|
232
|
-
|
|
353
|
+
this.forecast.converting = () => forecast ??= this.planned(scanned, true).then(plans => {
|
|
354
|
+
this.forecast.withoutImmer!.clear();
|
|
355
|
+
for (const p of plans) if (p.reducerStore) this.forecast.withoutImmer!.add(packageOf(scanned.packages, p.store!.path)!);
|
|
356
|
+
return this.asked = new Set(plans.filter(p => p.store).map(p => packageOf(scanned.packages, p.store!.path)!));
|
|
357
|
+
});
|
|
233
358
|
const sources = await check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
234
359
|
override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
|
|
235
360
|
const {reducers, slices} = localSlices(cu);
|
|
@@ -246,8 +371,9 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
246
371
|
if (/(^|\/)package\.json$/.test(doc.sourcePath)) {
|
|
247
372
|
const declared = findNodeResolutionResult(doc) ? undefined : await declaredDependencies(doc);
|
|
248
373
|
const get = (name: string) => declared ? declared[name] : version(doc, name);
|
|
249
|
-
scanned.packages.set(packageRoot(doc.sourcePath), {react: get("react"), zustand: get(ZUSTAND), immer: get(IMMER)});
|
|
374
|
+
scanned.packages.set(packageRoot(doc.sourcePath), {react: get("react"), reactDom: get("react-dom"), reactNative: get("react-native"), zustand: get(ZUSTAND), immer: get(IMMER), redux: get("redux"), toolkit: get(RTK), reactRedux: get("react-redux")});
|
|
250
375
|
}
|
|
376
|
+
await addPathsConfig(scanned.configs, doc);
|
|
251
377
|
return doc;
|
|
252
378
|
}
|
|
253
379
|
}();
|
|
@@ -265,6 +391,12 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
265
391
|
return check(or(treesOfType("org.openrewrite.json.tree.Json"), treesOfType("org.openrewrite.javascript.tree.JS")), scan);
|
|
266
392
|
}
|
|
267
393
|
|
|
394
|
+
/** The rows reported for each scan's stores. */
|
|
395
|
+
private reported = new WeakMap<Scanned, Set<string>>();
|
|
396
|
+
|
|
397
|
+
/** The sources split by `split`, by path, kept out of the accumulator, which keeps no trees. */
|
|
398
|
+
private splits = new WeakMap<Scanned, Map<string, Split>>();
|
|
399
|
+
|
|
268
400
|
/** The plan, once every source is scanned. `forecast` assumes that zustand and immer land wherever they're missing. */
|
|
269
401
|
private plans = new WeakMap<Scanned, Promise<Plan[]>>();
|
|
270
402
|
|
|
@@ -275,19 +407,72 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
275
407
|
if (cached) return cached;
|
|
276
408
|
}
|
|
277
409
|
const result = (async () => {
|
|
410
|
+
const splits = await this.split(scanned);
|
|
278
411
|
for (const cu of this.storeSources) {
|
|
279
|
-
const
|
|
280
|
-
|
|
412
|
+
const source = splits.get(cu.sourcePath)?.module ?? cu;
|
|
413
|
+
const facts = scanned.sources.get(source.sourcePath);
|
|
414
|
+
if (facts) facts.stores = await storeFacts(source, scanned.modules, resolverOf(scanned));
|
|
281
415
|
}
|
|
282
416
|
return planPackages(scanned.sources, scanned.sliceSources, path => packageOf(scanned.packages, path),
|
|
283
|
-
storePath => this.dependencies(scanned, storePath, forecast)
|
|
417
|
+
(storePath, immer) => this.dependencies(scanned, storePath, forecast, immer), this.wholeStores !== false, storePath => {
|
|
418
|
+
const facts = scanned.packages.get(packageOf(scanned.packages, storePath) ?? "");
|
|
419
|
+
return facts?.reactNative ? "react-native" : facts?.reactDom ? "react-dom" : undefined;
|
|
420
|
+
}, storePath => {
|
|
421
|
+
// zustand 5's hook, which the package declares or gets on React 18, runs the selector on each read
|
|
422
|
+
const facts = scanned.packages.get(packageOf(scanned.packages, storePath) ?? "");
|
|
423
|
+
return facts?.zustand !== undefined ? (major(facts.zustand) ?? 0) >= 5 : (major(facts?.react) ?? 0) >= 18;
|
|
424
|
+
}, resolverOf(scanned));
|
|
284
425
|
})();
|
|
285
426
|
if (!forecast) this.plans.set(scanned, result);
|
|
286
427
|
return result;
|
|
287
428
|
}
|
|
288
429
|
|
|
430
|
+
/**
|
|
431
|
+
* Splits each source that creates one store it doesn't export, at the top level of an application source, so that
|
|
432
|
+
* the store moves to a module of its own beside it, which its consumers can import, and the source imports it back.
|
|
433
|
+
* The split replaces the source's facts and adds the module's; the sources change only once the store converts.
|
|
434
|
+
*/
|
|
435
|
+
private async split(scanned: Scanned): Promise<Map<string, Split>> {
|
|
436
|
+
const known = this.splits.get(scanned);
|
|
437
|
+
if (known) return known;
|
|
438
|
+
const splits = new Map<string, Split>();
|
|
439
|
+
this.splits.set(scanned, splits);
|
|
440
|
+
const paths = [...scanned.sources.keys()];
|
|
441
|
+
const created = new Map<JS.CompilationUnit, Awaited<ReturnType<typeof storeFacts>>>();
|
|
442
|
+
for (const cu of this.storeSources) created.set(cu, await storeFacts(cu, scanned.modules, resolverOf(scanned)));
|
|
443
|
+
// A package with several stores keeps them in Redux, so none of its sources needs to split
|
|
444
|
+
const storesIn = (root: string | undefined) => [...created].filter(([cu]) => packageOf(scanned.packages, cu.sourcePath) === root).reduce((n, [, stores]) => n + stores.length, 0);
|
|
445
|
+
for (const [cu, stores] of created) {
|
|
446
|
+
if (/\.(?:ts|tsx|mts|cts)$/.test(cu.sourcePath) || TEST_SOURCE.test(cu.sourcePath)) continue;
|
|
447
|
+
if (stores.length !== 1 || stores[0].exportedAs || storesIn(packageOf(scanned.packages, cu.sourcePath)) !== 1) continue;
|
|
448
|
+
const directory = cu.sourcePath.includes("/") ? cu.sourcePath.slice(0, cu.sourcePath.lastIndexOf("/") + 1) : "";
|
|
449
|
+
const base = directory + ENTRY_STORE_MODULE;
|
|
450
|
+
// A module of that name, or a directory, would take the imports of the other
|
|
451
|
+
if (paths.some(path => path.startsWith(base + ".") || path.startsWith(base + "/"))) continue;
|
|
452
|
+
const split = await splitEntryStore(cu, stores[0].store, base + ".js", new ExecutionContext());
|
|
453
|
+
if (!split) continue;
|
|
454
|
+
splits.set(cu.sourcePath, {...split, modulePath: base + ".js"});
|
|
455
|
+
paths.push(base + ".js");
|
|
456
|
+
for (const source of [split.entry, split.module]) {
|
|
457
|
+
const {reducers, slices} = localSlices(source);
|
|
458
|
+
scanned.modules.set(source.sourcePath, {reducers, slices});
|
|
459
|
+
scanned.sources.set(source.sourcePath, await sourceFacts(source));
|
|
460
|
+
const slice = sliceSource(source);
|
|
461
|
+
if (slice) scanned.sliceSources.set(source.sourcePath, slice);
|
|
462
|
+
else scanned.sliceSources.delete(source.sourcePath);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
return splits;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
override async generate(scanned: Scanned, ctx: ExecutionContext): Promise<SourceFile[]> {
|
|
469
|
+
const plans = await this.planned(scanned, true);
|
|
470
|
+
// Slices that move one by one take the store's source with them, so only a store that moves whole needs the module
|
|
471
|
+
return [...(await this.split(scanned)).values()].filter(split => plans.some(p => p.store?.path === split.modulePath && p.reducerStore)).map(split => split.module);
|
|
472
|
+
}
|
|
473
|
+
|
|
289
474
|
/** Why the package of the store can't take zustand and immer, if it can't. */
|
|
290
|
-
private dependencies(scanned: Scanned, storePath: string, forecast: boolean): Finding | undefined {
|
|
475
|
+
private dependencies(scanned: Scanned, storePath: string, forecast: boolean, needsImmer = true): Finding | undefined {
|
|
291
476
|
const root = packageOf(scanned.packages, storePath);
|
|
292
477
|
const facts = root !== undefined ? scanned.packages.get(root) : undefined;
|
|
293
478
|
if (root === undefined || !facts) return {reason: "NO_PACKAGE", detail: storePath};
|
|
@@ -300,7 +485,7 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
300
485
|
const zustand = facts.zustand !== undefined ? (major(facts.zustand) ?? 0) >= (react >= 18 ? 4 : 4) && (react >= 18 || major(facts.zustand) === 4)
|
|
301
486
|
: landed(react >= 18 ? this.steps?.zustand : this.steps?.zustand4);
|
|
302
487
|
if (!zustand) return {reason: "DEPENDENCY", detail: facts.zustand ? `zustand ${facts.zustand} doesn't support React ${react}` : "zustand can't be added"};
|
|
303
|
-
const immer = facts.immer !== undefined ? (major(facts.immer) ?? 0) >= 9 : landed(this.steps?.immer);
|
|
488
|
+
const immer = !needsImmer || (facts.immer !== undefined ? (major(facts.immer) ?? 0) >= 9 : landed(this.steps?.immer));
|
|
304
489
|
if (!immer) return {reason: "DEPENDENCY", detail: facts.immer ? `immer ${facts.immer} is older than 9` : "immer can't be added"};
|
|
305
490
|
return undefined;
|
|
306
491
|
}
|
|
@@ -308,31 +493,41 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
308
493
|
async editorWithData(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
309
494
|
const recipe = this;
|
|
310
495
|
const stores = this.stores;
|
|
311
|
-
|
|
496
|
+
// The editor that visits a generated source may be another, which reports none of the same rows again
|
|
497
|
+
let reported = this.reported.get(scanned);
|
|
498
|
+
if (!reported) this.reported.set(scanned, reported = new Set<string>());
|
|
312
499
|
return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
313
500
|
override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
314
501
|
const plans = await recipe.planned(scanned);
|
|
315
502
|
const facts = scanned.sources.get(cu.sourcePath);
|
|
316
|
-
|
|
503
|
+
const splits = await recipe.split(scanned);
|
|
504
|
+
const split = splits.get(cu.sourcePath);
|
|
505
|
+
const entryOf = (path: string) => [...splits].find(([, s]) => s.modulePath === path)?.[0] ?? path;
|
|
506
|
+
// A store that moves to a module of its own is reported for the source it was created in
|
|
507
|
+
for (const store of [...facts?.stores ?? [], ...split ? scanned.sources.get(split.modulePath)?.stores ?? [] : []]) {
|
|
317
508
|
const key = `${store.path}\0${store.store}\0${store.api}`;
|
|
318
509
|
if (reported.has(key)) continue;
|
|
319
510
|
reported.add(key);
|
|
320
511
|
const p = plans.find(candidate => candidate.store === store) ?? plans.find(candidate => candidate.blocked.has(store));
|
|
321
512
|
const findings = p?.store === store ? [] : p?.blocked.get(store) ?? store.findings;
|
|
322
|
-
const rows = findings.length === 0 ? [{reason: "SLICE_STORE", detail: ""}] : findings;
|
|
323
|
-
for (const {reason, detail} of rows) {
|
|
513
|
+
const rows = findings.length === 0 ? [{reason: p?.reducerStore ? "REDUCER_STORE" : "SLICE_STORE", detail: ""}] : findings;
|
|
514
|
+
for (const {reason, detail, action} of rows as Finding[]) {
|
|
324
515
|
stores.insertRow(ctx, {
|
|
325
|
-
sourcePath: store.path, store: store.store, api: store.api,
|
|
516
|
+
sourcePath: entryOf(store.path), store: store.store, api: store.api,
|
|
326
517
|
status: p?.store === store ? "CONVERTED" : "REVIEW", reason, detail,
|
|
327
|
-
testSource: TEST_SOURCE.test(store.path), suggestedAction: SUGGESTED_ACTIONS[reason] ?? CONVERSION_ACTIONS[reason] ?? ""
|
|
518
|
+
testSource: TEST_SOURCE.test(entryOf(store.path)), suggestedAction: action ?? SUGGESTED_ACTIONS[reason] ?? CONVERSION_ACTIONS[reason] ?? ""
|
|
328
519
|
});
|
|
329
520
|
}
|
|
330
521
|
}
|
|
331
522
|
const p = plans.find(candidate => candidate.store && candidate.sources.has(cu.sourcePath));
|
|
332
|
-
|
|
523
|
+
// A module the store would have moved to goes again where the store stays
|
|
524
|
+
const generated = [...splits.values()].some(s => s.modulePath === cu.sourcePath);
|
|
525
|
+
if (!p?.store) return generated ? undefined : cu;
|
|
526
|
+
if (p.reducerStore) return cu.sourcePath === p.store.path ? convertReducerStore(cu, p, scanned.packages.get(packageOf(scanned.packages, cu.sourcePath) ?? ""), ctx) : convertReducerConsumer(split?.entry ?? cu, p, scanned, ctx);
|
|
333
527
|
if (cu.sourcePath === p.store.path) return undefined;
|
|
334
528
|
const slice = [...p.slices.values()].find(s => s.path === cu.sourcePath);
|
|
335
|
-
const
|
|
529
|
+
const source = split?.entry ?? cu;
|
|
530
|
+
const converted = slice ? await convertSlice(this, source, slice, scanned, ctx) : source;
|
|
336
531
|
return convertConsumer(converted, p, scanned, ctx);
|
|
337
532
|
}
|
|
338
533
|
}());
|
|
@@ -346,7 +541,7 @@ export class ReduxToZustand extends ScanningRecipe<Scanned> {
|
|
|
346
541
|
|
|
347
542
|
const CONVERSION_ACTIONS: Readonly<Record<string, string>> = {
|
|
348
543
|
MULTIPLE_STORES: "Convert by hand, or one store at a time: the uses of react-redux can't be told apart by store.",
|
|
349
|
-
STORE_NOT_MODULE_LEVEL: "Create the store once at the top level of its module; a zustand store is a module-level singleton.",
|
|
544
|
+
STORE_NOT_MODULE_LEVEL: "Create the store once at the top level of its module, and export it; a zustand store is a module-level singleton. A store its source creates at the top level moves to a module of its own where only imports and top-level `const`s and `let`s it uses move with it, nothing that stays uses them, and no `appStore` module is beside the source already.",
|
|
350
545
|
STORE_SOURCE: "Move what else the store's source declares, such as types or helpers, to another module.",
|
|
351
546
|
SLICE_SOURCE: "Declare each slice in a source of its own, held in a `const` of its own.",
|
|
352
547
|
SLICE_KEY: "Use a reducer key that is a JavaScript identifier, which names the zustand hook.",
|
|
@@ -359,10 +554,10 @@ const CONVERSION_ACTIONS: Readonly<Record<string, string>> = {
|
|
|
359
554
|
ACTIONS_EXPORT: "Export the action creators as `export const {a, b} = slice.actions`, under their own names.",
|
|
360
555
|
UNKNOWN_ACTION: "Remove the import of an action creator that has no reducer, which is `undefined`.",
|
|
361
556
|
SLICE_USE: "Use the slice only through its action creators and the store; other uses of the slice object are converted by hand.",
|
|
362
|
-
STORE_USE: "Use the store only in `<Provider store>`, `store.getState().key` and `store.dispatch(action())`.",
|
|
363
|
-
REACT_REDUX_USE: "Replace `
|
|
557
|
+
STORE_USE: "Use the store only in `<Provider store>`, `store.getState().key` and `store.dispatch(action())`, or, where it moves whole, in calls of its `getState`, `dispatch` and `subscribe`.",
|
|
558
|
+
REACT_REDUX_USE: "Replace `useStore`, `connect` with `mergeProps` or options other than `forwardRef`, and other react-redux APIs with `useSelector` and `useDispatch`, or convert by hand.",
|
|
364
559
|
DISPATCH: "Dispatch only the slices' action creators and their own thunks, as a statement of its own; other thunks and dispatches whose result is used are converted by hand.",
|
|
365
|
-
SELECTOR: "
|
|
560
|
+
SELECTOR: "Pass `useSelector` the selector alone, with no equality function or type arguments; where the slices would move one by one, read one slice's state in each selector, such as `state => state.counter.value` or a top-level `const` of one.",
|
|
366
561
|
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.",
|
|
367
562
|
TYPESCRIPT: "TypeScript sources are not converted yet.",
|
|
368
563
|
NO_PACKAGE: "Add a `package.json` for the store's package.",
|
|
@@ -374,6 +569,43 @@ function packageRoot(manifestPath: string): string {
|
|
|
374
569
|
return manifestPath.slice(0, -"package.json".length);
|
|
375
570
|
}
|
|
376
571
|
|
|
572
|
+
async function parsed(doc: Json.Document): Promise<any> {
|
|
573
|
+
try {
|
|
574
|
+
return JSON.parse(await TreePrinters.print(doc));
|
|
575
|
+
} catch {
|
|
576
|
+
return {};
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** The package globs of `workspaces`, as an array or as Yarn's `{packages: [...]}`. */
|
|
581
|
+
function workspaceGlobs(manifest: any): string[] {
|
|
582
|
+
const workspaces = Array.isArray(manifest?.workspaces) ? manifest.workspaces : manifest?.workspaces?.packages;
|
|
583
|
+
return Array.isArray(workspaces) ? workspaces.filter((glob: unknown): glob is string => typeof glob === "string") : [];
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** The entries of the `packages` list of a `pnpm-workspace.yaml`. */
|
|
587
|
+
function pnpmPackages(yaml: string): string[] {
|
|
588
|
+
const globs: string[] = [];
|
|
589
|
+
let inPackages = false;
|
|
590
|
+
for (const line of yaml.split(/\r?\n/)) {
|
|
591
|
+
if (/^\S/.test(line)) inPackages = /^packages\s*:/.test(line);
|
|
592
|
+
// REGEX: an indented `- entry`, the entry perhaps quoted, perhaps followed by a `# comment`
|
|
593
|
+
const entry = inPackages && /^\s+-\s*(?:'([^']*)'|"([^"]*)"|([^#\s]+))/.exec(line);
|
|
594
|
+
if (entry) globs.push(entry[1] ?? entry[2] ?? entry[3]);
|
|
595
|
+
}
|
|
596
|
+
return globs;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/** Whether `path`, relative to a workspace root, matches its globs, where a `!glob` excludes what it matches. */
|
|
600
|
+
function member(globs: string[], path: string): boolean {
|
|
601
|
+
const matches = (glob: string) => {
|
|
602
|
+
const pattern = glob.replace(/^\.\//, "").replace(/\/+$/, "").replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
603
|
+
.replace(/\*\*\/?|\*|\?/g, token => token.startsWith("**") ? "(?:.*/)?" + (token.endsWith("/") ? "" : ".*") : token === "*" ? "[^/]*" : "[^/]");
|
|
604
|
+
return new RegExp(`^${pattern}$`).test(path);
|
|
605
|
+
};
|
|
606
|
+
return globs.some(glob => !glob.startsWith("!") && matches(glob)) && !globs.some(glob => glob.startsWith("!") && matches(glob.slice(1)));
|
|
607
|
+
}
|
|
608
|
+
|
|
377
609
|
/** The root of the innermost package that holds `sourcePath`. */
|
|
378
610
|
function packageOf(packages: ReadonlyMap<string, PackageFacts>, sourcePath: string): string | undefined {
|
|
379
611
|
return [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length)[0];
|
|
@@ -525,10 +757,10 @@ function withPrefix<T extends J>(node: T, prefix: J.Space): T {
|
|
|
525
757
|
/** Rewrites the uses of react-redux, the store and its slices in a source. */
|
|
526
758
|
async function convertConsumer(cu: JS.CompilationUnit, p: Plan, scanned: Scanned, ctx: ExecutionContext): Promise<J | undefined> {
|
|
527
759
|
const bindings = importBindings(cu);
|
|
528
|
-
const followed = new Map(bindings.filter(b => b.module
|
|
760
|
+
const followed = new Map(bindings.filter(b => followsImport(b.module)).map(b => [b.local, b]));
|
|
529
761
|
const isStore = (name: string) => {
|
|
530
762
|
const binding = followed.get(name);
|
|
531
|
-
return !!binding && binding.module !== REACT_REDUX &&
|
|
763
|
+
return !!binding && binding.module !== REACT_REDUX && resolverOf(scanned)(cu.sourcePath, binding.module) === p.store!.path &&
|
|
532
764
|
binding.name === p.store!.exportedAs;
|
|
533
765
|
};
|
|
534
766
|
const reactRedux = (name: string, member: string) => followed.get(name)?.module === REACT_REDUX && followed.get(name)?.name === member;
|
|
@@ -619,6 +851,11 @@ async function convertConsumer(cu: JS.CompilationUnit, p: Plan, scanned: Scanned
|
|
|
619
851
|
removed.add("store");
|
|
620
852
|
return withPrefix(await this.visit(child, q, this.cursor) as JSX.Tag, tag.prefix);
|
|
621
853
|
}
|
|
854
|
+
if (providerChildren(tag)) {
|
|
855
|
+
removed.add("Provider");
|
|
856
|
+
removed.add("store");
|
|
857
|
+
return fragment(await super.visitJsxTag(tag, q) as JSX.Tag);
|
|
858
|
+
}
|
|
622
859
|
}
|
|
623
860
|
return super.visitJsxTag(tag, q);
|
|
624
861
|
}
|
|
@@ -658,3 +895,407 @@ function replaceTree(root: J, target: J, replacement: J): J {
|
|
|
658
895
|
replace(draft);
|
|
659
896
|
}) as J;
|
|
660
897
|
}
|
|
898
|
+
|
|
899
|
+
/** The statement of the store's source that creates the store, and the store's `reducer` option. */
|
|
900
|
+
function storeStatement(cu: JS.CompilationUnit, store: StoreFacts): {index: number, call: J.MethodInvocation, reducer: J, preloaded?: J, consts?: Set<string>} | undefined {
|
|
901
|
+
const legacy = store.reducerStore === "legacy" || store.reducerStore === "legacyThunk";
|
|
902
|
+
const functions = storeFunctions(cu);
|
|
903
|
+
const names = legacy ? functions.legacy : functions.configure;
|
|
904
|
+
const isStoreCall = (node: J | undefined): node is J.MethodInvocation => node?.kind === J.Kind.MethodInvocation &&
|
|
905
|
+
!(node as J.MethodInvocation).select && names.has((node as J.MethodInvocation).name.simpleName);
|
|
906
|
+
for (let index = 0; index < cu.statements.length; index++) {
|
|
907
|
+
const statement = cu.statements[index].element;
|
|
908
|
+
const call = statement.kind === JS.Kind.ExportAssignment ? (statement as JS.ExportAssignment).expression.element :
|
|
909
|
+
statement.kind === J.Kind.VariableDeclarations && (statement as J.VariableDeclarations).variables.length === 1 &&
|
|
910
|
+
isIdentifier((statement as J.VariableDeclarations).variables[0].element.name) &&
|
|
911
|
+
((statement as J.VariableDeclarations).variables[0].element.name as J.Identifier).simpleName === store.store
|
|
912
|
+
? (statement as J.VariableDeclarations).variables[0].element.initializer?.element : undefined;
|
|
913
|
+
if (!isStoreCall(call)) continue;
|
|
914
|
+
if (legacy) {
|
|
915
|
+
// The preloaded state is the second of three arguments, or the second of two that is no enhancer
|
|
916
|
+
const args = argumentsOf(call);
|
|
917
|
+
const preloaded = args.length === 3 || args.length === 2 && preloadedValue(args[1], cu) ? args[1] : undefined;
|
|
918
|
+
const enhancer = args.length === 3 || args.length === 2 && !preloaded ? legacyEnhancer(args[args.length - 1], cu) : undefined;
|
|
919
|
+
// NOTE: the arguments are moved into new calls, so they drop the line breaks they had in the store's call
|
|
920
|
+
return {index, call, reducer: {...args[0], prefix: emptySpace}, preloaded: preloaded && {...preloaded, prefix: emptySpace}, consts: enhancer && !("unsupported" in enhancer) ? enhancer.consts : new Set()};
|
|
921
|
+
}
|
|
922
|
+
const reducer = objectProperties(argumentsOf(call)[0])?.get("reducer");
|
|
923
|
+
return reducer ? {index, call, reducer} : undefined;
|
|
924
|
+
}
|
|
925
|
+
return undefined;
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* Removes the top-level `const`s among `names` that nothing else in the source refers to any more, such as those the
|
|
930
|
+
* store's enhancer was written with, and then those that only they referred to.
|
|
931
|
+
*/
|
|
932
|
+
async function withoutUnused(cu: JS.CompilationUnit, names: Set<string>): Promise<JS.CompilationUnit> {
|
|
933
|
+
const declared = (statement: J) => statement.kind === J.Kind.VariableDeclarations && (statement as J.VariableDeclarations).variables.length === 1 &&
|
|
934
|
+
isIdentifier((statement as J.VariableDeclarations).variables[0].element.name) ?
|
|
935
|
+
((statement as J.VariableDeclarations).variables[0].element.name as J.Identifier).simpleName : undefined;
|
|
936
|
+
for (let removed = true; removed;) {
|
|
937
|
+
const counts = new Map<string, number>();
|
|
938
|
+
await new class extends JavaScriptVisitor<undefined> {
|
|
939
|
+
override async visitIdentifier(identifier: J.Identifier, p: undefined): Promise<J | undefined> {
|
|
940
|
+
counts.set(identifier.simpleName, (counts.get(identifier.simpleName) ?? 0) + 1);
|
|
941
|
+
return super.visitIdentifier(identifier, p);
|
|
942
|
+
}
|
|
943
|
+
}().visit(cu, undefined);
|
|
944
|
+
// NOTE: a name counted once is the declaration's own; a property key of the same name only keeps the `const`
|
|
945
|
+
const statements = cu.statements.filter(padded => {
|
|
946
|
+
const name = declared(padded.element);
|
|
947
|
+
return !name || !names.has(name) || counts.get(name) !== 1;
|
|
948
|
+
});
|
|
949
|
+
removed = statements.length < cu.statements.length;
|
|
950
|
+
cu = {...cu, statements};
|
|
951
|
+
}
|
|
952
|
+
return cu;
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
/**
|
|
956
|
+
* react-redux's `connect` for a store that moves to zustand whole: the props it passes, the statics it copies and the
|
|
957
|
+
* re-renders it skips are react-redux's, for any `mapStateToProps` and `mapDispatchToProps` and the `forwardRef` option.
|
|
958
|
+
* `HOOK` stands for the zustand store's hook.
|
|
959
|
+
*/
|
|
960
|
+
/**
|
|
961
|
+
* The selector hook of a whole store on zustand 5, whose own hook runs the selector on each read: as react-redux's
|
|
962
|
+
* `useSelector`, it runs the selector once per state and selector, so a selector that builds a value renders once.
|
|
963
|
+
*/
|
|
964
|
+
export const SELECTOR = `export function SELECTOR_HOOK(selector) {
|
|
965
|
+
const last = useRef(undefined);
|
|
966
|
+
const select = () => {
|
|
967
|
+
const state = HOOK.getState();
|
|
968
|
+
const kept = last.current;
|
|
969
|
+
if (kept && kept.state === state && kept.selector === selector) return kept.selection;
|
|
970
|
+
const selection = selector(state);
|
|
971
|
+
last.current = {state, selector, selection};
|
|
972
|
+
return selection;
|
|
973
|
+
};
|
|
974
|
+
return useSyncExternalStore(HOOK.subscribe, select, select);
|
|
975
|
+
}`;
|
|
976
|
+
|
|
977
|
+
/** What `connect` does when `mapStateToProps` throws on the state of a store update, by react-redux's major version. */
|
|
978
|
+
const STORE_UPDATE_ERROR = {
|
|
979
|
+
// react-redux 8 maps a store update in its subscription, which drops the error and keeps the props from before
|
|
980
|
+
swallowed: `if (!update) throw error;`,
|
|
981
|
+
// react-redux 7 throws it again on every render until the next update
|
|
982
|
+
rethrown: `if (update) cache.error = error;
|
|
983
|
+
throw error;`
|
|
984
|
+
};
|
|
985
|
+
|
|
986
|
+
/** The `connect` that the store's source declares for its hook `hook`, as the react-redux of range `reactRedux` behaves. */
|
|
987
|
+
export function connectSource(hook: string, reactRedux: string | undefined): string {
|
|
988
|
+
return CONNECT.split("HOOK").join(hook).replace("STORE_UPDATE_ERROR", STORE_UPDATE_ERROR[(major(reactRedux) ?? 8) >= 8 ? "swallowed" : "rethrown"]);
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
const CONNECT = `export function connect(mapStateToProps, mapDispatchToProps, mergeProps, options) {
|
|
992
|
+
const forwardsRef = Boolean(options && options.forwardRef);
|
|
993
|
+
const selectState = mapStateToProps ? state => state : () => undefined;
|
|
994
|
+
const dependsOnOwnProps = map => map.dependsOnOwnProps !== undefined && map.dependsOnOwnProps !== null ? Boolean(map.dependsOnOwnProps) : map.length !== 1;
|
|
995
|
+
// A map that returns a function on its first call is a factory of the map to use
|
|
996
|
+
const mapper = map => {
|
|
997
|
+
let actual = map;
|
|
998
|
+
let first = true;
|
|
999
|
+
const run = (value, ownProps) => dependsOnOwnProps(actual) ? actual(value, ownProps) : actual(value);
|
|
1000
|
+
return {
|
|
1001
|
+
map(value, ownProps) {
|
|
1002
|
+
let props = run(value, ownProps);
|
|
1003
|
+
if (first) {
|
|
1004
|
+
first = false;
|
|
1005
|
+
if (typeof props === "function") {
|
|
1006
|
+
actual = props;
|
|
1007
|
+
props = run(value, ownProps);
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
return props;
|
|
1011
|
+
},
|
|
1012
|
+
dependsOnOwnProps: () => dependsOnOwnProps(actual)
|
|
1013
|
+
};
|
|
1014
|
+
};
|
|
1015
|
+
const bound = actionCreators => {
|
|
1016
|
+
const props = {};
|
|
1017
|
+
for (const key of Object.keys(actionCreators)) {
|
|
1018
|
+
const actionCreator = actionCreators[key];
|
|
1019
|
+
if (typeof actionCreator === "function") props[key] = (...args) => HOOK.dispatch(actionCreator(...args));
|
|
1020
|
+
}
|
|
1021
|
+
return props;
|
|
1022
|
+
};
|
|
1023
|
+
const shallowEqual = (a, b) => {
|
|
1024
|
+
const keys = Object.keys(a);
|
|
1025
|
+
return keys.length === Object.keys(b).length && keys.every(key => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key]));
|
|
1026
|
+
};
|
|
1027
|
+
const notHoisted = ["$$typeof", "render", "compare", "type", "childContextTypes", "contextType", "contextTypes", "defaultProps", "displayName",
|
|
1028
|
+
"getDefaultProps", "getDerivedStateFromError", "getDerivedStateFromProps", "mixins", "propTypes", "name", "length", "prototype", "caller",
|
|
1029
|
+
"callee", "arguments", "arity"];
|
|
1030
|
+
const hoistStatics = (target, source) => {
|
|
1031
|
+
for (let from = source; from && from !== Function.prototype && from !== Object.prototype; from = Object.getPrototypeOf(from)) {
|
|
1032
|
+
for (const key of [...Object.getOwnPropertyNames(from), ...Object.getOwnPropertySymbols(from)]) {
|
|
1033
|
+
if (!notHoisted.includes(key) && !Object.prototype.hasOwnProperty.call(target, key)) Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(from, key));
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
return target;
|
|
1037
|
+
};
|
|
1038
|
+
return WrappedComponent => {
|
|
1039
|
+
const displayName = \`Connect(\${WrappedComponent.displayName || WrappedComponent.name || "Component"})\`;
|
|
1040
|
+
function ConnectFunction(props) {
|
|
1041
|
+
const cache = useRef({}).current;
|
|
1042
|
+
const state = HOOK(selectState);
|
|
1043
|
+
if (!cache.mappers) cache.mappers = {state: mapStateToProps ? mapper(mapStateToProps) : undefined, dispatch: typeof mapDispatchToProps === "function" ? mapper(mapDispatchToProps) : undefined};
|
|
1044
|
+
const {state: mapState, dispatch: mapDispatch} = cache.mappers;
|
|
1045
|
+
if (cache.props !== props) {
|
|
1046
|
+
cache.props = props;
|
|
1047
|
+
cache.ownProps = props;
|
|
1048
|
+
if (forwardsRef) {
|
|
1049
|
+
cache.ownProps = {};
|
|
1050
|
+
for (const key of Object.keys(props)) if (key !== "reactReduxForwardedRef") cache.ownProps[key] = props[key];
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
const ownProps = cache.ownProps;
|
|
1054
|
+
// Own props compare shallowly with those of the last render, whether that render finished or not
|
|
1055
|
+
const ownPropsChanged = !cache.seenOwnProps || !shallowEqual(cache.seenOwnProps, ownProps);
|
|
1056
|
+
cache.seenOwnProps = ownProps;
|
|
1057
|
+
const propsChanged = Boolean(mapState) && mapState.dependsOnOwnProps() && !(cache.stateOwnProps && shallowEqual(cache.stateOwnProps, ownProps));
|
|
1058
|
+
if (!cache.stateProps || (mapState && (cache.state !== state || propsChanged))) {
|
|
1059
|
+
// The state and props count as mapped before the map runs, so a render React retries after the map
|
|
1060
|
+
// throws keeps the props from before
|
|
1061
|
+
const update = cache.stateProps !== undefined && cache.state !== state && !propsChanged;
|
|
1062
|
+
cache.state = state;
|
|
1063
|
+
cache.stateOwnProps = ownProps;
|
|
1064
|
+
cache.error = undefined;
|
|
1065
|
+
try {
|
|
1066
|
+
cache.stateProps = mapState ? mapState.map(state, ownProps) : {};
|
|
1067
|
+
cache.kept = false;
|
|
1068
|
+
} catch (error) {
|
|
1069
|
+
// The props passed last stay, own props too, until the map returns again
|
|
1070
|
+
cache.kept = true;
|
|
1071
|
+
STORE_UPDATE_ERROR
|
|
1072
|
+
}
|
|
1073
|
+
} else if (cache.error) {
|
|
1074
|
+
throw cache.error;
|
|
1075
|
+
}
|
|
1076
|
+
if (!cache.dispatchProps || (mapDispatch && mapDispatch.dependsOnOwnProps() && cache.dispatchOwnProps !== ownProps)) {
|
|
1077
|
+
cache.dispatchProps = mapDispatch ? mapDispatch.map(HOOK.dispatch, ownProps) : mapDispatchToProps ? bound(mapDispatchToProps) : {dispatch: HOOK.dispatch};
|
|
1078
|
+
cache.dispatchOwnProps = ownProps;
|
|
1079
|
+
}
|
|
1080
|
+
const merged = {...ownProps, ...cache.stateProps, ...cache.dispatchProps};
|
|
1081
|
+
if (!cache.merged || (!cache.kept || ownPropsChanged) && !shallowEqual(cache.merged, merged)) cache.merged = merged;
|
|
1082
|
+
if (!cache.element || cache.rendered !== cache.merged || cache.ref !== props.reactReduxForwardedRef) {
|
|
1083
|
+
cache.rendered = cache.merged;
|
|
1084
|
+
cache.ref = props.reactReduxForwardedRef;
|
|
1085
|
+
cache.element = createElement(WrappedComponent, forwardsRef ? {...cache.merged, ref: cache.ref} : cache.merged);
|
|
1086
|
+
}
|
|
1087
|
+
return cache.element;
|
|
1088
|
+
}
|
|
1089
|
+
ConnectFunction.displayName = displayName;
|
|
1090
|
+
const Connect = memo(ConnectFunction);
|
|
1091
|
+
Connect.displayName = displayName;
|
|
1092
|
+
Connect.WrappedComponent = WrappedComponent;
|
|
1093
|
+
if (!forwardsRef) return hoistStatics(Connect, WrappedComponent);
|
|
1094
|
+
const Forwarded = forwardRef((props, ref) => createElement(Connect, {...props, reactReduxForwardedRef: ref}));
|
|
1095
|
+
Forwarded.displayName = displayName;
|
|
1096
|
+
Forwarded.WrappedComponent = WrappedComponent;
|
|
1097
|
+
return hoistStatics(Forwarded, WrappedComponent);
|
|
1098
|
+
};
|
|
1099
|
+
}`;
|
|
1100
|
+
|
|
1101
|
+
|
|
1102
|
+
/**
|
|
1103
|
+
* Whether the Redux that creates a store is 5 or later, whose `dispatch` rejects a type that isn't a string: for a
|
|
1104
|
+
* store of Redux Toolkit, the Redux that Toolkit 2 depends on, and otherwise the Redux the package declares, or else
|
|
1105
|
+
* the one its Toolkit brings.
|
|
1106
|
+
*/
|
|
1107
|
+
function typedByString(facts: PackageFacts | undefined, fromToolkit: boolean): boolean {
|
|
1108
|
+
const redux = fromToolkit ? undefined : major(facts?.redux);
|
|
1109
|
+
if (redux !== undefined) return redux >= 5;
|
|
1110
|
+
return (major(facts?.toolkit) ?? 0) >= 2;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/**
|
|
1114
|
+
* Rewrites the store's source for a store that moves whole: its reducer runs on one zustand store, whose `dispatch`
|
|
1115
|
+
* runs a thunk as Redux Toolkit's default middleware does and any other plain-object action with a `type` through the
|
|
1116
|
+
* reducer, as Redux does, and the store's variable keeps the store's `getState` and `dispatch`. A legacy `createStore`
|
|
1117
|
+
* has no middleware, so its `dispatch` runs no thunk, and its state starts from its preloaded state.
|
|
1118
|
+
*/
|
|
1119
|
+
async function convertReducerStore(cu: JS.CompilationUnit, p: Plan, facts: PackageFacts | undefined, ctx: ExecutionContext): Promise<J | undefined> {
|
|
1120
|
+
const store = p.store!;
|
|
1121
|
+
const {hook, reducer, renderer, selectorHook, listeners} = p.reducerStore!;
|
|
1122
|
+
const found = storeStatement(cu, store);
|
|
1123
|
+
if (!found) return cu;
|
|
1124
|
+
const padded = cu.statements[found.index];
|
|
1125
|
+
const statement = padded.element;
|
|
1126
|
+
const cursor = new Cursor(statement, new Cursor(cu, undefined));
|
|
1127
|
+
// `configureStore` combines an object of reducers as `combineReducers` does
|
|
1128
|
+
const combined = store.reducerStore === "combined";
|
|
1129
|
+
const legacy = store.reducerStore === "legacy" || store.reducerStore === "legacyThunk";
|
|
1130
|
+
// redux-thunk runs a function with `dispatch` and `getState`, and passes any other action on to the store
|
|
1131
|
+
const thunk = store.reducerStore === "legacyThunk";
|
|
1132
|
+
// Redux rejects what isn't a plain object with a type before a reducer sees it
|
|
1133
|
+
const checks = `if (typeof action !== "object" || action === null || ![Object.prototype, null].includes(Object.getPrototypeOf(action))) throw new Error("Actions must be plain objects.");
|
|
1134
|
+
if (action.type === undefined) throw new Error("Actions may not have an undefined 'type' property.");` +
|
|
1135
|
+
(typedByString(facts, importedAs(cu, RTK, "configureStore", "createStore", "legacy_createStore").has(store.api)) ? `\n if (typeof action.type !== "string") throw new Error("Action 'type' property must be a string.");` : "");
|
|
1136
|
+
// react-redux batches a store's updates, so that a parent renders before the children it may remove
|
|
1137
|
+
// Redux calls the listeners of `subscribe` after every dispatch, as they were when it began, before react-redux renders
|
|
1138
|
+
const update = `${hook}.setState(${reducer}(${hook}.getState(), action), true);`;
|
|
1139
|
+
const notified = listeners ? `${update}\n for (const listener of [...${listeners}.values()]) listener();` : update;
|
|
1140
|
+
const setState = renderer ? listeners ? `unstable_batchedUpdates(() => {\n ${notified}\n });` : `unstable_batchedUpdates(() => ${update.slice(0, -1)});` : notified;
|
|
1141
|
+
const members = `getState: ${hook}.getState, dispatch: ${hook}.dispatch` + (listeners ? `, subscribe: listener => {
|
|
1142
|
+
if (typeof listener !== "function") throw new Error("Expected the listener to be a function. Instead, received: '" + (listener === null ? "null" : Array.isArray(listener) ? "array" : typeof listener) + "'");
|
|
1143
|
+
const id = Symbol();
|
|
1144
|
+
${listeners}.set(id, listener);
|
|
1145
|
+
return () => {
|
|
1146
|
+
${listeners}.delete(id);
|
|
1147
|
+
};
|
|
1148
|
+
}` : "");
|
|
1149
|
+
const generated = [
|
|
1150
|
+
combined ? await template`const ${raw(reducer)} = combineReducers(${found.reducer});`.apply(statement, cursor) :
|
|
1151
|
+
await template`const ${raw(reducer)} = ${found.reducer};`.apply(statement, cursor),
|
|
1152
|
+
found.preloaded ?
|
|
1153
|
+
await template`export const ${raw(hook)} = create(() => ${raw(reducer)}(${found.preloaded}, {type: "@@redux/INIT"}));`.apply(statement, cursor) :
|
|
1154
|
+
await template`export const ${raw(hook)} = create(() => ${raw(reducer)}(undefined, {type: "@@redux/INIT"}));`.apply(statement, cursor),
|
|
1155
|
+
...listeners ? [await template`const ${raw(listeners)} = new Map();`.apply(statement, cursor)] : [],
|
|
1156
|
+
legacy && !thunk ?
|
|
1157
|
+
await template`${raw(hook)}.dispatch = action => {
|
|
1158
|
+
${raw(checks)}
|
|
1159
|
+
${raw(setState)}
|
|
1160
|
+
return action;
|
|
1161
|
+
};`.apply(statement, cursor) :
|
|
1162
|
+
await template`${raw(hook)}.dispatch = action => {
|
|
1163
|
+
if (typeof action === "function") return action(${raw(hook)}.dispatch, ${raw(hook)}.getState, undefined);
|
|
1164
|
+
${raw(checks)}
|
|
1165
|
+
${raw(setState)}
|
|
1166
|
+
return action;
|
|
1167
|
+
};`.apply(statement, cursor),
|
|
1168
|
+
statement.kind === JS.Kind.ExportAssignment ?
|
|
1169
|
+
await template`export default {${raw(members)}};`.apply(statement, cursor) :
|
|
1170
|
+
await template`${raw((statement as J.VariableDeclarations).modifiers.some(m => m.keyword === "export") ? "export " : "")}const ${raw(store.store)} = {${raw(members)}};`.apply(statement, cursor),
|
|
1171
|
+
...selectorHook ? [await template`${raw(SELECTOR.split("SELECTOR_HOOK").join(selectorHook).split("HOOK").join(hook))}`.apply(statement, cursor)] : [],
|
|
1172
|
+
...renderer ? [await template`${raw(connectSource(hook, facts?.reactRedux))}`.apply(statement, cursor)] : []
|
|
1173
|
+
];
|
|
1174
|
+
const statements: J.RightPadded<Statement>[] = [...cu.statements.slice(0, found.index)];
|
|
1175
|
+
for (let i = 0; i < generated.length; i++) {
|
|
1176
|
+
const prefixed = withPrefix(generated[i] as Statement, i === 0 ? statement.prefix : space("\n\n"));
|
|
1177
|
+
const element = i === 0 ? prefixed : await autoFormat(prefixed, ctx, undefined, new Cursor(cu, undefined)) as Statement;
|
|
1178
|
+
// A function declaration ends without the semicolon of the statement it follows
|
|
1179
|
+
statements.push(element.kind === J.Kind.MethodDeclaration ? {...padded, element, markers: emptyMarkers} : {...padded, element});
|
|
1180
|
+
}
|
|
1181
|
+
statements.push(...cu.statements.slice(found.index + 1));
|
|
1182
|
+
const result = await withoutUnused({...cu, statements} as JS.CompilationUnit, found.consts ?? new Set());
|
|
1183
|
+
return new class extends JavaScriptVisitor<ExecutionContext> {
|
|
1184
|
+
override async visitJsCompilationUnit(unit: JS.CompilationUnit, q: ExecutionContext): Promise<J | undefined> {
|
|
1185
|
+
const quoteStyle = quoteOf(cu);
|
|
1186
|
+
maybeRemoveImport(this, RTK, "configureStore");
|
|
1187
|
+
for (const module of [REDUX, RTK]) for (const member of ["createStore", "legacy_createStore"]) maybeRemoveImport(this, module, member);
|
|
1188
|
+
if (legacy) {
|
|
1189
|
+
for (const member of ["applyMiddleware", "compose"]) maybeRemoveImport(this, REDUX, member);
|
|
1190
|
+
for (const member of ["default", "thunk"]) maybeRemoveImport(this, "redux-thunk", member);
|
|
1191
|
+
for (const module of ["redux-devtools-extension", "@redux-devtools/extension"]) {
|
|
1192
|
+
for (const member of ["composeWithDevTools", "devToolsEnhancer", "devToolsEnhancerLogOnlyInProduction"]) maybeRemoveImport(this, module, member);
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
if (combined) maybeAddImport(this, {module: RTK, member: "combineReducers", onlyIfReferenced: false, quoteStyle});
|
|
1196
|
+
maybeAddImport(this, {module: ZUSTAND, member: "create", onlyIfReferenced: false, quoteStyle});
|
|
1197
|
+
if (selectorHook) for (const member of ["useRef", "useSyncExternalStore"]) maybeAddImport(this, {module: "react", member, onlyIfReferenced: false, quoteStyle});
|
|
1198
|
+
if (renderer) {
|
|
1199
|
+
for (const member of ["createElement", "forwardRef", "memo", "useRef"]) maybeAddImport(this, {module: "react", member, onlyIfReferenced: false, quoteStyle});
|
|
1200
|
+
maybeAddImport(this, {module: renderer, member: "unstable_batchedUpdates", onlyIfReferenced: false, quoteStyle});
|
|
1201
|
+
}
|
|
1202
|
+
return super.visitJsCompilationUnit(unit, q);
|
|
1203
|
+
}
|
|
1204
|
+
}().visit(result, ctx);
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
/**
|
|
1208
|
+
* `<Provider store={store}>` of several children as the fragment `<>` of the same children, which renders them as the
|
|
1209
|
+
* provider did once nothing reads its context.
|
|
1210
|
+
*/
|
|
1211
|
+
function fragment(tag: JSX.Tag): JSX.Tag {
|
|
1212
|
+
// The parser makes `<>` and `</>` of empty names, with no space around them
|
|
1213
|
+
const empty = (): J.Empty => ({kind: J.Kind.Empty, id: randomId(), prefix: emptySpace, markers: emptyMarkers});
|
|
1214
|
+
return create(tag, draft => {
|
|
1215
|
+
draft.openName = {...draft.openName, before: emptySpace, element: empty()} as any;
|
|
1216
|
+
draft.closingName = {...draft.closingName!, before: emptySpace, element: empty()} as any;
|
|
1217
|
+
draft.attributes = [];
|
|
1218
|
+
draft.afterName = emptySpace as any;
|
|
1219
|
+
draft.afterClosingName = emptySpace as any;
|
|
1220
|
+
}) as JSX.Tag;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
/** Rewrites a source's uses of react-redux for a store that moves whole: the hooks read and dispatch to its zustand store. */
|
|
1224
|
+
async function convertReducerConsumer(cu: JS.CompilationUnit, p: Plan, scanned: Scanned, ctx: ExecutionContext): Promise<J | undefined> {
|
|
1225
|
+
const {hook, selectorHook} = p.reducerStore!;
|
|
1226
|
+
const source = scanned.sources.get(cu.sourcePath);
|
|
1227
|
+
// A read of the state keeps the store's own hook; another selector, on zustand 5, goes through the store's selector hook
|
|
1228
|
+
const reads = (selector: J | undefined) => !!selectorRead(selector) ||
|
|
1229
|
+
isIdentifier(selector) && !!source && readSelector(source, selector.simpleName, scanned.sources, resolverOf(scanned));
|
|
1230
|
+
const bindings = importBindings(cu);
|
|
1231
|
+
const followed = new Map(bindings.filter(b => followsImport(b.module)).map(b => [b.local, b]));
|
|
1232
|
+
const reactRedux = (name: string, member: string) => followed.get(name)?.module === REACT_REDUX && followed.get(name)?.name === member;
|
|
1233
|
+
const removed = new Set<string>();
|
|
1234
|
+
// The store's hooks the source now calls
|
|
1235
|
+
const uses = new Set<string>();
|
|
1236
|
+
const result = await new class extends JavaScriptVisitor<ExecutionContext> {
|
|
1237
|
+
override async visitVariableDeclarations(declarations: J.VariableDeclarations, q: ExecutionContext): Promise<J | undefined> {
|
|
1238
|
+
const variable = declarations.variables.length === 1 ? declarations.variables[0].element : undefined;
|
|
1239
|
+
if (variable && isDispatcherDeclaration(variable, followed)) {
|
|
1240
|
+
// `useDispatch` returns the store's `dispatch`, which the zustand store now holds
|
|
1241
|
+
removed.add("useDispatch");
|
|
1242
|
+
uses.add(hook);
|
|
1243
|
+
const initializer = variable.initializer!.element;
|
|
1244
|
+
const replaced = await template`${raw(hook)}.dispatch`.apply(initializer, new Cursor(initializer, this.cursor)) as J;
|
|
1245
|
+
return create(declarations, draft => {
|
|
1246
|
+
draft.variables[0].element.initializer!.element = withPrefix(replaced, initializer.prefix) as any;
|
|
1247
|
+
}) as J.VariableDeclarations;
|
|
1248
|
+
}
|
|
1249
|
+
return super.visitVariableDeclarations(declarations, q);
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
override async visitMethodInvocation(call: J.MethodInvocation, q: ExecutionContext): Promise<J | undefined> {
|
|
1253
|
+
const visited = await super.visitMethodInvocation(call, q) as J.MethodInvocation;
|
|
1254
|
+
if (visited.select || !reactRedux(visited.name.simpleName, "useSelector")) return visited;
|
|
1255
|
+
removed.add("useSelector");
|
|
1256
|
+
const through = selectorHook && !reads(argumentsOf(visited)[0]) ? selectorHook : hook;
|
|
1257
|
+
uses.add(through);
|
|
1258
|
+
return create(visited, draft => {
|
|
1259
|
+
draft.name = {...draft.name, simpleName: through, fieldType: undefined, type: undefined} as any;
|
|
1260
|
+
draft.methodType = undefined;
|
|
1261
|
+
}) as J.MethodInvocation;
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
override async visitJsxTag(tag: JSX.Tag, q: ExecutionContext): Promise<J | undefined> {
|
|
1265
|
+
const name = tag.openName.element;
|
|
1266
|
+
if (isIdentifier(name) && reactRedux(name.simpleName, "Provider")) {
|
|
1267
|
+
const child = providerChild(tag);
|
|
1268
|
+
if (child) {
|
|
1269
|
+
removed.add("Provider");
|
|
1270
|
+
return withPrefix(await this.visit(child, q, this.cursor) as JSX.Tag, tag.prefix);
|
|
1271
|
+
}
|
|
1272
|
+
if (providerChildren(tag)) {
|
|
1273
|
+
removed.add("Provider");
|
|
1274
|
+
return fragment(await super.visitJsxTag(tag, q) as JSX.Tag);
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
return super.visitJsxTag(tag, q);
|
|
1278
|
+
}
|
|
1279
|
+
}().visit(cu, ctx) as JS.CompilationUnit;
|
|
1280
|
+
// `connect` stays as it is called, imported from the store's source, which declares it for the zustand store
|
|
1281
|
+
const connected = p.reducerStore!.renderer && bindings.some(b => b.module === REACT_REDUX && b.name === "connect") ?
|
|
1282
|
+
await (await new ChangeImport({oldModule: REACT_REDUX, oldMember: "connect", newModule: relativeSpecifier(cu.sourcePath, p.store!.path)}).editor()).visit(result, ctx) as JS.CompilationUnit :
|
|
1283
|
+
result;
|
|
1284
|
+
return await new class extends JavaScriptVisitor<ExecutionContext> {
|
|
1285
|
+
override async visitJsCompilationUnit(unit: JS.CompilationUnit, q: ExecutionContext): Promise<J | undefined> {
|
|
1286
|
+
for (const member of ["useSelector", "useDispatch", "Provider"]) {
|
|
1287
|
+
if (removed.has(member)) maybeRemoveImport(this, REACT_REDUX, member);
|
|
1288
|
+
}
|
|
1289
|
+
// The store's variable stays, so its import goes only where nothing uses it any more
|
|
1290
|
+
if (removed.has("Provider")) {
|
|
1291
|
+
for (const binding of bindings) {
|
|
1292
|
+
if (binding.module !== REACT_REDUX && resolverOf(scanned)(cu.sourcePath, binding.module) === p.store!.path) maybeRemoveImport(this, binding.module, binding.name);
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
for (const member of [hook, selectorHook]) {
|
|
1296
|
+
if (member && uses.has(member)) maybeAddImport(this, {module: relativeSpecifier(cu.sourcePath, p.store!.path), member, onlyIfReferenced: false, quoteStyle: quoteOf(cu)});
|
|
1297
|
+
}
|
|
1298
|
+
return super.visitJsCompilationUnit(unit, q);
|
|
1299
|
+
}
|
|
1300
|
+
}().visit(connected, ctx);
|
|
1301
|
+
}
|