@openrewrite/recipes-react 0.17.0 → 0.19.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 (109) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +9 -5
  4. package/dist/index.js.map +1 -1
  5. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
  6. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +3 -5
  7. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
  8. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
  9. package/dist/migration/cra-to-vite/update-react-app-env-types.js +5 -2
  10. package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
  11. package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
  12. package/dist/react18/replace-unmount-component-at-node.js +8 -1
  13. package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
  14. package/dist/react19/find-legacy-context-api.d.ts.map +1 -1
  15. package/dist/react19/find-legacy-context-api.js +21 -38
  16. package/dist/react19/find-legacy-context-api.js.map +1 -1
  17. package/dist/react19/no-implicit-ref-callback-return.d.ts.map +1 -1
  18. package/dist/react19/no-implicit-ref-callback-return.js +25 -5
  19. package/dist/react19/no-implicit-ref-callback-return.js.map +1 -1
  20. package/dist/{react18 → react19}/remove-unstable-batched-updates.d.ts +2 -2
  21. package/dist/react19/remove-unstable-batched-updates.d.ts.map +1 -0
  22. package/dist/react19/remove-unstable-batched-updates.js +295 -0
  23. package/dist/react19/remove-unstable-batched-updates.js.map +1 -0
  24. package/dist/react19/replace-default-props.d.ts +1 -0
  25. package/dist/react19/replace-default-props.d.ts.map +1 -1
  26. package/dist/react19/replace-default-props.js +198 -151
  27. package/dist/react19/replace-default-props.js.map +1 -1
  28. package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
  29. package/dist/react19/replace-react-shallow-renderer.js +10 -25
  30. package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
  31. package/dist/refactoring/class-to-functional.d.ts.map +1 -1
  32. package/dist/refactoring/class-to-functional.js +2 -0
  33. package/dist/refactoring/class-to-functional.js.map +1 -1
  34. package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
  35. package/dist/refactoring/create-class-to-es6.js +14 -49
  36. package/dist/refactoring/create-class-to-es6.js.map +1 -1
  37. package/dist/search/find-function-component-default-props.d.ts.map +1 -1
  38. package/dist/search/find-function-component-default-props.js +6 -15
  39. package/dist/search/find-function-component-default-props.js.map +1 -1
  40. package/dist/search/find-redux-stores.d.ts +12 -0
  41. package/dist/search/find-redux-stores.d.ts.map +1 -0
  42. package/dist/search/find-redux-stores.js +87 -0
  43. package/dist/search/find-redux-stores.js.map +1 -0
  44. package/dist/simplify-object-pattern-property.d.ts.map +1 -1
  45. package/dist/simplify-object-pattern-property.js +14 -21
  46. package/dist/simplify-object-pattern-property.js.map +1 -1
  47. package/dist/simplify-react-imports.d.ts.map +1 -1
  48. package/dist/simplify-react-imports.js +10 -59
  49. package/dist/simplify-react-imports.js.map +1 -1
  50. package/dist/testing/enzyme-host-components.d.ts +2 -1
  51. package/dist/testing/enzyme-host-components.d.ts.map +1 -1
  52. package/dist/testing/enzyme-host-components.js +33 -2
  53. package/dist/testing/enzyme-host-components.js.map +1 -1
  54. package/dist/testing/enzyme-to-react-testing-library.d.ts +10 -1
  55. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  56. package/dist/testing/enzyme-to-react-testing-library.js +83 -24
  57. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  58. package/dist/testing/enzyme-wrapper-scope.d.ts +4 -1
  59. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  60. package/dist/testing/enzyme-wrapper-scope.js +36 -7
  61. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  62. package/dist/util/java-recipe-proxy.d.ts +2 -0
  63. package/dist/util/java-recipe-proxy.d.ts.map +1 -1
  64. package/dist/util/java-recipe-proxy.js +14 -2
  65. package/dist/util/java-recipe-proxy.js.map +1 -1
  66. package/dist/util/reindent.d.ts +5 -0
  67. package/dist/util/reindent.d.ts.map +1 -0
  68. package/dist/util/reindent.js +44 -0
  69. package/dist/util/reindent.js.map +1 -0
  70. package/dist/zustand/redux-stores.d.ts +74 -0
  71. package/dist/zustand/redux-stores.d.ts.map +1 -0
  72. package/dist/zustand/redux-stores.js +439 -0
  73. package/dist/zustand/redux-stores.js.map +1 -0
  74. package/dist/zustand/redux-to-zustand.d.ts +76 -0
  75. package/dist/zustand/redux-to-zustand.d.ts.map +1 -0
  76. package/dist/zustand/redux-to-zustand.js +654 -0
  77. package/dist/zustand/redux-to-zustand.js.map +1 -0
  78. package/dist/zustand/zustand-plan.d.ts +97 -0
  79. package/dist/zustand/zustand-plan.d.ts.map +1 -0
  80. package/dist/zustand/zustand-plan.js +833 -0
  81. package/dist/zustand/zustand-plan.js.map +1 -0
  82. package/package.json +1 -1
  83. package/src/index.ts +7 -3
  84. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +3 -5
  85. package/src/migration/cra-to-vite/update-react-app-env-types.ts +3 -3
  86. package/src/react18/replace-unmount-component-at-node.ts +13 -2
  87. package/src/react19/find-legacy-context-api.ts +21 -42
  88. package/src/react19/no-implicit-ref-callback-return.ts +34 -8
  89. package/src/react19/remove-unstable-batched-updates.ts +301 -0
  90. package/src/react19/replace-default-props.ts +212 -159
  91. package/src/react19/replace-react-shallow-renderer.ts +13 -36
  92. package/src/refactoring/class-to-functional.ts +3 -1
  93. package/src/refactoring/create-class-to-es6.ts +12 -63
  94. package/src/search/find-function-component-default-props.ts +8 -10
  95. package/src/search/find-redux-stores.ts +76 -0
  96. package/src/simplify-object-pattern-property.ts +22 -49
  97. package/src/simplify-react-imports.ts +12 -66
  98. package/src/testing/enzyme-host-components.ts +38 -3
  99. package/src/testing/enzyme-to-react-testing-library.ts +118 -31
  100. package/src/testing/enzyme-wrapper-scope.ts +39 -10
  101. package/src/util/java-recipe-proxy.ts +15 -2
  102. package/src/util/reindent.ts +35 -0
  103. package/src/zustand/redux-stores.ts +441 -0
  104. package/src/zustand/redux-to-zustand.ts +660 -0
  105. package/src/zustand/zustand-plan.ts +854 -0
  106. package/dist/react18/remove-unstable-batched-updates.d.ts.map +0 -1
  107. package/dist/react18/remove-unstable-batched-updates.js +0 -170
  108. package/dist/react18/remove-unstable-batched-updates.js.map +0 -1
  109. package/src/react18/remove-unstable-batched-updates.ts +0 -192
@@ -0,0 +1,441 @@
1
+ import {Column, Cursor} from "@openrewrite/rewrite";
2
+ import {JS, walk} from "@openrewrite/rewrite/javascript";
3
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
4
+ import {importBindings, resolveRelative} from "../util/module-imports";
5
+
6
+ export const REDUX = "redux";
7
+ export const RTK = "@reduxjs/toolkit";
8
+ export const ZUSTAND_GUIDE = "https://zustand.docs.pmnd.rs/guides/migrating-to-zustand";
9
+ export const REDUX_STORES_TABLE = "org.openrewrite.react.table.ReduxStores";
10
+
11
+ export class ReduxStoreRow {
12
+ @Column({displayName: "Source path", description: "The file that creates the Redux store."})
13
+ sourcePath!: string;
14
+
15
+ @Column({displayName: "Store", description: "The variable or function the store is created in, or <module> when it has no name."})
16
+ store!: string;
17
+
18
+ @Column({displayName: "API", description: "The Redux function that creates the store: `createStore`, `legacy_createStore` or `configureStore`."})
19
+ api!: string;
20
+
21
+ @Column({displayName: "Status", description: "CANDIDATE for a store whose setup a conversion to zustand can keep, or REVIEW for one it can't, with one row per reason."})
22
+ status!: string;
23
+
24
+ @Column({displayName: "Reason", description: "A stable reason code: SLICE_STORE for a candidate, or the part of the setup that keeps the store from converting."})
25
+ reason!: string;
26
+
27
+ @Column({displayName: "Detail", description: "The option, reducer key or slice the reason is about, when there is one."})
28
+ detail!: string;
29
+
30
+ @Column({displayName: "Test source", description: "Whether the file looks like a test, mock or story."})
31
+ testSource!: boolean;
32
+
33
+ @Column({displayName: "Suggested action", description: "What to do before the store can move to zustand."})
34
+ suggestedAction!: string;
35
+ }
36
+
37
+ /** What a store needs to know about a `createSlice` call. */
38
+ export interface SliceFacts {
39
+ name: string;
40
+ /** The source that declares the slice. */
41
+ path: string;
42
+ /** The top-level variable the slice is held in, or `""` when it has none, as in `export default createSlice(...)`. */
43
+ variable: string;
44
+ /** The part of the slice a conversion can't keep, if any, such as `extraReducers`. */
45
+ blocker?: {reason: string, detail: string};
46
+ /** The `createAsyncThunk`s of the slice's source whose stages its `extraReducers` handle, by variable. */
47
+ thunks?: Map<string, SliceThunk>;
48
+ /** The cases of `extraReducers`, in the order they are added, without their reducers, which `caseReducers` reads. */
49
+ cases?: {thunk: string, stage: string}[];
50
+ }
51
+
52
+ /** A top-level `const x = createAsyncThunk('type', payloadCreator)` of a slice's source. */
53
+ export interface SliceThunk {
54
+ variable: string;
55
+ /** The action type prefix, such as `todos/fetch`, whose stages are `todos/fetch/pending` and so on. */
56
+ typePrefix: string;
57
+ }
58
+
59
+ /** `builder.addCase(thunk.stage, reducer)` in a slice's `extraReducers`. */
60
+ export interface ThunkCase {
61
+ thunk: string;
62
+ stage: string;
63
+ reducer: J;
64
+ }
65
+
66
+ /** The slices a module exports, by export name (`default` for a default export). */
67
+ export interface SliceModule {
68
+ /** Exports holding a slice's `reducer`, such as `export default slice.reducer`. */
69
+ reducers: Map<string, SliceFacts>;
70
+ /** Exports holding the slice itself, such as `export const slice = createSlice(...)`. */
71
+ slices: Map<string, SliceFacts>;
72
+ }
73
+
74
+ /** The slices one source declares, by local name, and what it exports of them. */
75
+ interface LocalSlices extends SliceModule {
76
+ localSlices: Map<string, SliceFacts>;
77
+ localReducers: Map<string, SliceFacts>;
78
+ }
79
+
80
+ /** The local names `cu` imports `name` from `module` as. */
81
+ export function importedAs(cu: JS.CompilationUnit, module: string, ...names: string[]): Set<string> {
82
+ return new Set(importBindings(cu).filter(binding => binding.module === module && names.includes(binding.name)).map(binding => binding.local));
83
+ }
84
+
85
+ /** The properties of an object literal, or undefined when it has any other member, such as a spread or a method. */
86
+ export function objectProperties(node: J | undefined): Map<string, J> | undefined {
87
+ if (node?.kind !== J.Kind.NewClass) return undefined;
88
+ const literal = node as J.NewClass;
89
+ if (literal.class || !literal.body) return undefined;
90
+ const properties = new Map<string, J>();
91
+ for (const {element} of literal.body.statements) {
92
+ if (element.kind !== JS.Kind.PropertyAssignment) return undefined;
93
+ const property = element as JS.PropertyAssignment;
94
+ const name = property.name.element;
95
+ const key = isIdentifier(name) ? name.simpleName :
96
+ name.kind === J.Kind.Literal && typeof (name as J.Literal).value === "string" ? (name as J.Literal).value as string : undefined;
97
+ if (key === undefined) return undefined;
98
+ // Shorthand `{counter}` has no initializer: the name is the value
99
+ properties.set(key, property.initializer ?? name);
100
+ }
101
+ return properties;
102
+ }
103
+
104
+ /** The facts of a `createSlice({...})` call, or undefined when `node` is not one. */
105
+ function sliceFacts(node: J | undefined, createSlice: ReadonlySet<string>, cu: JS.CompilationUnit, variable: string): SliceFacts | undefined {
106
+ const path = cu.sourcePath;
107
+ if (node?.kind !== J.Kind.MethodInvocation) return undefined;
108
+ const call = node as J.MethodInvocation;
109
+ if (call.select || !createSlice.has(call.name.simpleName)) return undefined;
110
+ const options = objectProperties(call.arguments.elements[0]?.element);
111
+ const nameValue = options?.get("name");
112
+ const name = nameValue?.kind === J.Kind.Literal ? String((nameValue as J.Literal).value) : "<unnamed>";
113
+ if (!options) return {name, path, variable, blocker: {reason: "SLICE_OPTIONS_NOT_LITERAL", detail: name}};
114
+ const extra = options.has("extraReducers") ? thunkCases(options.get("extraReducers")!, cu) : undefined;
115
+ if (typeof extra === "string") return {name, path, variable, blocker: {reason: "EXTRA_REDUCERS", detail: `${name}: ${extra}`}};
116
+ // Methods such as `increment(state) {...}` are reducers as properties are; a spread or the builder callback can't be read
117
+ const reducers = options.get("reducers");
118
+ const literal = reducers?.kind === J.Kind.NewClass && !(reducers as J.NewClass).class ? (reducers as J.NewClass).body : undefined;
119
+ if (reducers && !literal?.statements.every(({element}) => element.kind === JS.Kind.PropertyAssignment || element.kind === J.Kind.MethodDeclaration)) {
120
+ return {name, path, variable, blocker: {reason: "SLICE_REDUCERS_NOT_LITERAL", detail: name}};
121
+ }
122
+ return {name, path, variable, ...extra && {thunks: extra.thunks, cases: extra.cases.map(({thunk, stage}) => ({thunk, stage}))}};
123
+ }
124
+
125
+ /** The `extraReducers` cases of the slice `variable` of `cu`, with their reducers, for a slice whose facts have cases. */
126
+ export function caseReducers(cu: JS.CompilationUnit, variable: string): ThunkCase[] {
127
+ for (const {element} of cu.statements) {
128
+ if (element.kind !== J.Kind.VariableDeclarations) continue;
129
+ const found = (element as J.VariableDeclarations).variables.find(v => isIdentifier(v.element.name) && v.element.name.simpleName === variable)?.element;
130
+ const call = found?.initializer?.element;
131
+ if (call?.kind !== J.Kind.MethodInvocation) continue;
132
+ const extra = objectProperties((call as J.MethodInvocation).arguments.elements[0]?.element)?.get("extraReducers");
133
+ const cases = extra ? thunkCases(extra, cu) : undefined;
134
+ return cases && typeof cases !== "string" ? cases.cases : [];
135
+ }
136
+ return [];
137
+ }
138
+
139
+ const THUNK_STAGES = new Set(["pending", "fulfilled", "rejected"]);
140
+
141
+ /** What a payload creator may take from `thunkAPI`: what doesn't reach the rest of the Redux store, as `getState` and `dispatch` do. */
142
+ const THUNK_API = new Set(["rejectWithValue", "fulfillWithValue", "signal", "requestId"]);
143
+
144
+ function lambdaOf(node: J | undefined): J.Lambda | undefined {
145
+ if (node?.kind === JS.Kind.ArrowFunction) return (node as JS.ArrowFunction).lambda;
146
+ return node?.kind === J.Kind.Lambda ? node as J.Lambda : undefined;
147
+ }
148
+
149
+ function parametersOf(lambda: J.Lambda): J[] {
150
+ return lambda.parameters.parameters.map(p => p.element).filter(p => p.kind !== J.Kind.Empty);
151
+ }
152
+
153
+ /** The name of a plain parameter, `x` but not `{a}`, `x = 1` or `x: T`. */
154
+ function plainParameter(node: J): string | undefined {
155
+ if (isIdentifier(node)) return node.simpleName;
156
+ if (node.kind !== J.Kind.VariableDeclarations) return undefined;
157
+ const declarations = node as J.VariableDeclarations;
158
+ const variable = declarations.variables.length === 1 ? declarations.variables[0].element : undefined;
159
+ return variable && !declarations.typeExpression && !declarations.varargs && !variable.initializer && isIdentifier(variable.name) ? variable.name.simpleName : undefined;
160
+ }
161
+
162
+ /** The object pattern a parameter is, `{a, b: c}`, without a type or a default for the whole. */
163
+ function destructured(node: J): JS.ObjectBindingPattern | undefined {
164
+ if (node.kind !== J.Kind.VariableDeclarations) return undefined;
165
+ const declarations = node as J.VariableDeclarations;
166
+ const variable = declarations.variables.length === 1 ? declarations.variables[0].element : undefined;
167
+ const pattern = variable?.name;
168
+ return variable && !declarations.typeExpression && !variable.initializer && pattern?.kind === JS.Kind.ObjectBindingPattern &&
169
+ !(pattern as JS.ObjectBindingPattern).initializer && !(pattern as JS.ObjectBindingPattern).typeExpression ? pattern as JS.ObjectBindingPattern : undefined;
170
+ }
171
+
172
+ /** The members `{a, b: c}` takes, each bound to a name of its own; otherwise what else the pattern does. */
173
+ function thunkApiMembers(pattern: JS.ObjectBindingPattern): string[] | string {
174
+ const members: string[] = [];
175
+ for (const {element} of pattern.bindings.elements) {
176
+ if (element.kind === J.Kind.Empty) continue;
177
+ if (element.kind !== JS.Kind.BindingElement) return "is a pattern of more than names";
178
+ const binding = element as JS.BindingElement;
179
+ if (binding.initializer) return "pattern has a default";
180
+ if (!isIdentifier(binding.name)) return "pattern has a rest element or a nested pattern";
181
+ const key = binding.propertyName?.element ?? binding.name;
182
+ if (!isIdentifier(key)) return "pattern has a computed key";
183
+ members.push(key.simpleName);
184
+ }
185
+ return members;
186
+ }
187
+
188
+ /**
189
+ * The thunks and cases of `extraReducers` written as `builder => builder.addCase(thunk.pending, reducer)...`, where
190
+ * each thunk is a `createAsyncThunk` of the same source; otherwise why they can't be kept, for the review row.
191
+ */
192
+ function thunkCases(value: J, cu: JS.CompilationUnit): {thunks: Map<string, SliceThunk>, cases: ThunkCase[]} | string {
193
+ const lambda = lambdaOf(value);
194
+ const parameters = lambda ? parametersOf(lambda) : [];
195
+ const builder = parameters.length === 1 ? plainParameter(parameters[0]) : undefined;
196
+ if (!lambda || !builder) return "`extraReducers` isn't a function of the builder";
197
+ const body = lambda.body as J;
198
+ const expressions = body.kind === J.Kind.Block ? (body as J.Block).statements.map(s => s.element) : [body];
199
+ const thunks = new Map<string, SliceThunk>();
200
+ const cases: ThunkCase[] = [];
201
+ for (let expression of expressions) {
202
+ if (expression.kind === JS.Kind.ExpressionStatement) expression = (expression as JS.ExpressionStatement).expression;
203
+ const chain: ThunkCase[] = [];
204
+ let node: J = expression;
205
+ while (node.kind === J.Kind.MethodInvocation) {
206
+ const call = node as J.MethodInvocation;
207
+ if (!call.select) break;
208
+ if (call.name.simpleName !== "addCase") return `\`builder.${call.name.simpleName}\``;
209
+ const args = call.arguments.elements.map(a => a.element).filter(a => a.kind !== J.Kind.Empty);
210
+ const matcher = args[0];
211
+ if (args.length !== 2 || matcher?.kind !== J.Kind.FieldAccess || !isIdentifier((matcher as J.FieldAccess).target) ||
212
+ !THUNK_STAGES.has((matcher as J.FieldAccess).name.element.simpleName)) return "a case for what isn't a stage of a thunk";
213
+ if (!lambdaOf(args[1])) return "a case reducer that isn't a function written in place";
214
+ const thunk = ((matcher as J.FieldAccess).target as J.Identifier).simpleName;
215
+ chain.unshift({thunk, stage: (matcher as J.FieldAccess).name.element.simpleName, reducer: args[1]});
216
+ node = call.select.element;
217
+ }
218
+ if (!isIdentifier(node) || node.simpleName !== builder || chain.length === 0) return "`extraReducers` does more than `builder.addCase`";
219
+ cases.push(...chain);
220
+ }
221
+ const seen = new Set<string>();
222
+ for (const {thunk, stage} of cases) {
223
+ if (seen.has(`${thunk}.${stage}`)) return `two cases for \`${thunk}.${stage}\``;
224
+ seen.add(`${thunk}.${stage}`);
225
+ if (thunks.has(thunk)) continue;
226
+ const found = asyncThunk(thunk, cu);
227
+ if (typeof found === "string") return found;
228
+ thunks.set(thunk, found);
229
+ }
230
+ return {thunks, cases};
231
+ }
232
+
233
+ /** The top-level `const name = createAsyncThunk('type', payloadCreator)` of `cu`, or why `name` isn't one the conversion keeps. */
234
+ function asyncThunk(name: string, cu: JS.CompilationUnit): SliceThunk | string {
235
+ const createAsyncThunk = importedAs(cu, RTK, "createAsyncThunk");
236
+ for (const {element} of cu.statements) {
237
+ if (element.kind !== J.Kind.VariableDeclarations) continue;
238
+ const declarations = element as J.VariableDeclarations;
239
+ const variable = declarations.variables.find(v => isIdentifier(v.element.name) && v.element.name.simpleName === name)?.element;
240
+ if (!variable) continue;
241
+ const init = variable.initializer?.element;
242
+ const call = init?.kind === J.Kind.MethodInvocation ? init as J.MethodInvocation : undefined;
243
+ if (declarations.variables.length !== 1 || !declarations.modifiers.some(m => m.keyword === "const") || !call || call.select ||
244
+ !createAsyncThunk.has(call.name.simpleName)) return `\`${name}\` isn't a \`createAsyncThunk\` of the slice's source`;
245
+ const args = call.arguments.elements.map(a => a.element).filter(a => a.kind !== J.Kind.Empty);
246
+ if (args.length !== 2) return `\`${name}\` has options`;
247
+ if (args[0].kind !== J.Kind.Literal || typeof (args[0] as J.Literal).value !== "string") return `\`${name}\`'s type isn't a string literal`;
248
+ const creator = lambdaOf(args[1]);
249
+ if (!creator) return `\`${name}\`'s payload creator isn't an arrow function`;
250
+ const parameters = parametersOf(creator);
251
+ if (parameters.length > 2) return `\`${name}\`'s payload creator takes more than \`arg\` and \`thunkAPI\``;
252
+ if (parameters.length === 2 && destructured(parameters[1])) {
253
+ // `{rejectWithValue, signal}` takes only what stays within the thunk, whatever the payload creator does with it
254
+ const taken = thunkApiMembers(destructured(parameters[1])!);
255
+ if (typeof taken === "string") return `\`${name}\`'s \`thunkAPI\` ${taken}`;
256
+ const other = taken.find(member => !THUNK_API.has(member));
257
+ if (other) return `\`${name}\` takes \`${other}\` from \`thunkAPI\`, beyond ${[...THUNK_API].map(m => `\`${m}\``).join(", ")}`;
258
+ } else if (parameters.length === 2) {
259
+ const api = plainParameter(parameters[1]);
260
+ if (!api) return `\`${name}\`'s \`thunkAPI\` isn't a plain parameter or an object pattern`;
261
+ // Every mention of `thunkAPI` must be a read of a member that stays within the thunk
262
+ let mentions = 0;
263
+ let kept = 0;
264
+ walk(creator.body, tree => {
265
+ const node = tree as J;
266
+ if (isIdentifier(node) && node.simpleName === api) mentions++;
267
+ const target = node.kind === J.Kind.FieldAccess ? (node as J.FieldAccess).target :
268
+ node.kind === J.Kind.MethodInvocation ? (node as J.MethodInvocation).select?.element : undefined;
269
+ const member = node.kind === J.Kind.FieldAccess ? (node as J.FieldAccess).name.element.simpleName :
270
+ node.kind === J.Kind.MethodInvocation ? (node as J.MethodInvocation).name.simpleName : undefined;
271
+ if (target && isIdentifier(target) && target.simpleName === api && member && THUNK_API.has(member)) kept++;
272
+ return true;
273
+ });
274
+ if (mentions !== kept) return `\`${name}\` uses \`${api}\` for more than ${[...THUNK_API].map(m => `\`${m}\``).join(", ")}`;
275
+ }
276
+ return {variable: name, typePrefix: (args[0] as J.Literal).value as string};
277
+ }
278
+ return `\`${name}\` isn't a \`createAsyncThunk\` of the slice's source`;
279
+ }
280
+
281
+ /** `slice.reducer` for a slice `slices` names. */
282
+ function reducerOf(node: J | undefined, slices: ReadonlyMap<string, SliceFacts>): SliceFacts | undefined {
283
+ if (node?.kind !== J.Kind.FieldAccess) return undefined;
284
+ const access = node as J.FieldAccess;
285
+ return access.name.element.simpleName === "reducer" && isIdentifier(access.target) ? slices.get(access.target.simpleName) : undefined;
286
+ }
287
+
288
+ function exportKeywords(modifiers: J.Modifier[]): {exported: boolean, isDefault: boolean} {
289
+ const keywords = new Set(modifiers.map(modifier => modifier.keyword));
290
+ return {exported: keywords.has("export"), isDefault: keywords.has("default")};
291
+ }
292
+
293
+ /** The slices `cu` declares at its top level and the ones it exports. */
294
+ export function localSlices(cu: JS.CompilationUnit): LocalSlices {
295
+ const createSlice = importedAs(cu, RTK, "createSlice");
296
+ const result: LocalSlices = {localSlices: new Map(), localReducers: new Map(), reducers: new Map(), slices: new Map()};
297
+ if (createSlice.size === 0) return result;
298
+ const exportedNames: [string, string][] = [];
299
+ for (const {element} of cu.statements) {
300
+ if (element.kind === J.Kind.VariableDeclarations) {
301
+ const declarations = element as J.VariableDeclarations;
302
+ const {exported} = exportKeywords(declarations.modifiers);
303
+ for (const {element: variable} of declarations.variables) {
304
+ if (!isIdentifier(variable.name)) continue;
305
+ const name = variable.name.simpleName;
306
+ const init = variable.initializer?.element;
307
+ const slice = sliceFacts(init, createSlice, cu, name);
308
+ if (slice) result.localSlices.set(name, slice);
309
+ const reducer = reducerOf(init, result.localSlices);
310
+ if (reducer) result.localReducers.set(name, reducer);
311
+ if (exported) exportedNames.push([name, name]);
312
+ }
313
+ } else if (element.kind === JS.Kind.ExportAssignment) {
314
+ const expression = (element as JS.ExportAssignment).expression.element;
315
+ const reducer = reducerOf(expression, result.localSlices) ??
316
+ (isIdentifier(expression) ? result.localReducers.get(expression.simpleName) : undefined);
317
+ if (reducer) result.reducers.set("default", reducer);
318
+ const slice = sliceFacts(expression, createSlice, cu, "") ?? (isIdentifier(expression) ? result.localSlices.get(expression.simpleName) : undefined);
319
+ if (slice) result.slices.set("default", slice);
320
+ } else if (element.kind === JS.Kind.ExportDeclaration) {
321
+ const declaration = element as JS.ExportDeclaration;
322
+ if (declaration.moduleSpecifier || declaration.exportClause?.kind !== JS.Kind.NamedExports) continue;
323
+ for (const {element: specifier} of (declaration.exportClause as JS.NamedExports).elements.elements) {
324
+ if (specifier.kind !== JS.Kind.ExportSpecifier) continue;
325
+ const named = (specifier as JS.ExportSpecifier).specifier;
326
+ if (isIdentifier(named)) exportedNames.push([named.simpleName, named.simpleName]);
327
+ else if (named.kind === JS.Kind.Alias) {
328
+ const alias = named as JS.Alias;
329
+ const local = alias.propertyName.element;
330
+ if (isIdentifier(local) && isIdentifier(alias.alias)) exportedNames.push([local.simpleName, alias.alias.simpleName]);
331
+ }
332
+ }
333
+ }
334
+ }
335
+ for (const [local, exported] of exportedNames) {
336
+ const slice = result.localSlices.get(local);
337
+ if (slice) result.slices.set(exported, slice);
338
+ const reducer = result.localReducers.get(local);
339
+ if (reducer) result.reducers.set(exported, reducer);
340
+ }
341
+ return result;
342
+ }
343
+
344
+ /** Resolves a reducer expression of a store to the slice it is the reducer of. */
345
+ export function resolveSliceReducer(node: J, cu: JS.CompilationUnit, local: LocalSlices, modules: ReadonlyMap<string, SliceModule>): SliceFacts | undefined {
346
+ const inFile = reducerOf(node, local.localSlices) ?? (isIdentifier(node) ? local.localReducers.get(node.simpleName) : undefined);
347
+ if (inFile) return inFile;
348
+ const imported = (name: string) => {
349
+ const binding = importBindings(cu).find(b => b.local === name);
350
+ const path = binding && resolveRelative(cu.sourcePath, binding.module, modules);
351
+ return path ? {binding, module: modules.get(path)!} : undefined;
352
+ };
353
+ if (isIdentifier(node)) {
354
+ const found = imported(node.simpleName);
355
+ return found?.module.reducers.get(found.binding.name);
356
+ }
357
+ if (node.kind === J.Kind.FieldAccess) {
358
+ const access = node as J.FieldAccess;
359
+ if (access.name.element.simpleName !== "reducer" || !isIdentifier(access.target)) return undefined;
360
+ const found = imported(access.target.simpleName);
361
+ return found?.module.slices.get(found.binding.name);
362
+ }
363
+ return undefined;
364
+ }
365
+
366
+ export const SUGGESTED_ACTIONS: Readonly<Record<string, string>> = {
367
+ SLICE_STORE: "A store of `createSlice` reducers with the default middleware: each slice can become a zustand store. Check its consumers next.",
368
+ LEGACY_STORE: "Move the store to Redux Toolkit's `configureStore` and its reducers to `createSlice` first, or write the zustand store by hand.",
369
+ OPTIONS_NOT_LITERAL: "Write the `configureStore` options as an object literal, so that the setup can be read.",
370
+ ROOT_REDUCER: "Pass `reducer` as an object of slice reducers; a single root reducer, such as `combineReducers(...)`, can't be split into zustand stores.",
371
+ NON_SLICE_REDUCER: "Rewrite this reducer with `createSlice`, or keep it in Redux; zustand has no place for a hand-written reducer.",
372
+ EXTRA_REDUCERS: "Write `extraReducers` as `builder.addCase(thunk.pending, reducer)` cases of `createAsyncThunk`s declared in the slice's source, whose payload creators take or use only `rejectWithValue`, `fulfillWithValue`, `signal` and `requestId` of `thunkAPI`, or move what it handles into actions of the zustand store by hand.",
373
+ SLICE_OPTIONS_NOT_LITERAL: "Write the `createSlice` options as an object literal, so that the slice can be read.",
374
+ SLICE_REDUCERS_NOT_LITERAL: "Write `reducers` as an object of reducer functions; the builder callback form can't be read.",
375
+ MIDDLEWARE: "Custom middleware has no zustand equivalent: move it into the store's actions or zustand middleware by hand.",
376
+ ENHANCERS: "Store enhancers have no zustand equivalent: replace them by hand, for example with zustand middleware.",
377
+ PRELOADED_STATE: "Merge the preloaded state into the slices' initial state, or set it on the zustand store after it is created.",
378
+ DEVTOOLS: "Configure zustand's `devtools` middleware to match the `devTools` option by hand.",
379
+ UNKNOWN_OPTION: "Review this `configureStore` option by hand."
380
+ };
381
+
382
+ export const TEST_SOURCE = /(^|\/)(__tests__|__mocks__|tests?|stories)\/|\.(test|spec|stories)\.[jt]sx?$/i;
383
+
384
+ /** The options of `configureStore` that keep a store from converting, by the reason they are recorded under. */
385
+ const BLOCKING_OPTIONS: Readonly<Record<string, string>> = {
386
+ middleware: "MIDDLEWARE", enhancers: "ENHANCERS", preloadedState: "PRELOADED_STATE", devTools: "DEVTOOLS"
387
+ };
388
+
389
+ export interface Finding {
390
+ reason: string;
391
+ detail: string;
392
+ }
393
+
394
+ /** The local names a source calls to create a Redux store: legacy `createStore` and Redux Toolkit's `configureStore`. */
395
+ export function storeFunctions(cu: JS.CompilationUnit): {legacy: Set<string>, configure: Set<string>} {
396
+ return {
397
+ legacy: new Set([...importedAs(cu, REDUX, "createStore", "legacy_createStore"), ...importedAs(cu, RTK, "createStore", "legacy_createStore")]),
398
+ configure: importedAs(cu, RTK, "configureStore")
399
+ };
400
+ }
401
+
402
+ /**
403
+ * Why the store `call` creates can't move to zustand, or `[]` for a candidate, with the slices of its reducers by key.
404
+ * `undefined` when `call` creates no store.
405
+ */
406
+ export function storeFindings(call: J.MethodInvocation, cu: JS.CompilationUnit, modules: ReadonlyMap<string, SliceModule>,
407
+ functions = storeFunctions(cu)): {api: string, findings: Finding[], slices: Map<string, SliceFacts>} | undefined {
408
+ if (call.select) return undefined;
409
+ const api = call.name.simpleName;
410
+ if (functions.legacy.has(api)) return {api, findings: [{reason: "LEGACY_STORE", detail: api}], slices: new Map()};
411
+ if (!functions.configure.has(api)) return undefined;
412
+ const slices = new Map<string, SliceFacts>();
413
+ const options = objectProperties(call.arguments.elements[0]?.element);
414
+ if (!options) return {api, findings: [{reason: "OPTIONS_NOT_LITERAL", detail: ""}], slices};
415
+ const findings: Finding[] = [];
416
+ for (const key of options.keys()) {
417
+ if (key !== "reducer") findings.push({reason: BLOCKING_OPTIONS[key] ?? "UNKNOWN_OPTION", detail: key});
418
+ }
419
+ const reducers = objectProperties(options.get("reducer"));
420
+ if (!reducers) return {api, findings: [...findings, {reason: "ROOT_REDUCER", detail: ""}], slices};
421
+ const local = localSlices(cu);
422
+ for (const [key, value] of reducers) {
423
+ const slice = resolveSliceReducer(value, cu, local, modules);
424
+ if (!slice) findings.push({reason: "NON_SLICE_REDUCER", detail: key});
425
+ else if (slice.blocker) findings.push(slice.blocker);
426
+ else slices.set(key, slice);
427
+ }
428
+ return {api, findings, slices};
429
+ }
430
+
431
+ /** The variable or function a store is created in, such as `store` in `export const store = configureStore(...)`. */
432
+ export function storeName(cursor: Cursor): string {
433
+ for (let c: Cursor | undefined = cursor.parent; c; c = c.parent) {
434
+ const node = c.value as J;
435
+ if (node?.kind === J.Kind.NamedVariable && isIdentifier((node as J.VariableDeclarations.NamedVariable).name)) {
436
+ return ((node as J.VariableDeclarations.NamedVariable).name as J.Identifier).simpleName;
437
+ }
438
+ if (node?.kind === J.Kind.MethodDeclaration) return (node as J.MethodDeclaration).name.simpleName;
439
+ }
440
+ return "<module>";
441
+ }