@openrewrite/recipes-react 0.17.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -5
- package/dist/index.js.map +1 -1
- package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js +3 -5
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
- package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/update-react-app-env-types.js +5 -2
- package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.js +8 -1
- package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
- package/dist/react19/find-legacy-context-api.d.ts.map +1 -1
- package/dist/react19/find-legacy-context-api.js +21 -38
- package/dist/react19/find-legacy-context-api.js.map +1 -1
- package/dist/{react18 → react19}/remove-unstable-batched-updates.d.ts +2 -2
- package/dist/react19/remove-unstable-batched-updates.d.ts.map +1 -0
- package/dist/react19/remove-unstable-batched-updates.js +295 -0
- package/dist/react19/remove-unstable-batched-updates.js.map +1 -0
- package/dist/react19/replace-default-props.d.ts +1 -0
- package/dist/react19/replace-default-props.d.ts.map +1 -1
- package/dist/react19/replace-default-props.js +198 -151
- package/dist/react19/replace-default-props.js.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.js +10 -25
- package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
- package/dist/refactoring/class-to-functional.d.ts.map +1 -1
- package/dist/refactoring/class-to-functional.js +2 -0
- package/dist/refactoring/class-to-functional.js.map +1 -1
- package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
- package/dist/refactoring/create-class-to-es6.js +14 -49
- package/dist/refactoring/create-class-to-es6.js.map +1 -1
- package/dist/search/find-function-component-default-props.d.ts.map +1 -1
- package/dist/search/find-function-component-default-props.js +6 -15
- package/dist/search/find-function-component-default-props.js.map +1 -1
- package/dist/search/find-redux-stores.d.ts +12 -0
- package/dist/search/find-redux-stores.d.ts.map +1 -0
- package/dist/search/find-redux-stores.js +87 -0
- package/dist/search/find-redux-stores.js.map +1 -0
- package/dist/simplify-object-pattern-property.d.ts.map +1 -1
- package/dist/simplify-object-pattern-property.js +14 -21
- package/dist/simplify-object-pattern-property.js.map +1 -1
- package/dist/simplify-react-imports.d.ts.map +1 -1
- package/dist/simplify-react-imports.js +10 -59
- package/dist/simplify-react-imports.js.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.d.ts +10 -1
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +79 -22
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +3 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +10 -7
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/util/java-recipe-proxy.d.ts +2 -0
- package/dist/util/java-recipe-proxy.d.ts.map +1 -1
- package/dist/util/java-recipe-proxy.js +14 -2
- package/dist/util/java-recipe-proxy.js.map +1 -1
- package/dist/util/reindent.d.ts +5 -0
- package/dist/util/reindent.d.ts.map +1 -0
- package/dist/util/reindent.js +44 -0
- package/dist/util/reindent.js.map +1 -0
- package/dist/zustand/redux-stores.d.ts +74 -0
- package/dist/zustand/redux-stores.d.ts.map +1 -0
- package/dist/zustand/redux-stores.js +402 -0
- package/dist/zustand/redux-stores.js.map +1 -0
- package/dist/zustand/redux-to-zustand.d.ts +76 -0
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -0
- package/dist/zustand/redux-to-zustand.js +653 -0
- package/dist/zustand/redux-to-zustand.js.map +1 -0
- package/dist/zustand/zustand-plan.d.ts +96 -0
- package/dist/zustand/zustand-plan.d.ts.map +1 -0
- package/dist/zustand/zustand-plan.js +822 -0
- package/dist/zustand/zustand-plan.js.map +1 -0
- package/package.json +1 -1
- package/src/index.ts +7 -3
- package/src/migration/cra-to-vite/find-cra-config-blockers.ts +3 -5
- package/src/migration/cra-to-vite/update-react-app-env-types.ts +3 -3
- package/src/react18/replace-unmount-component-at-node.ts +13 -2
- package/src/react19/find-legacy-context-api.ts +21 -42
- package/src/react19/remove-unstable-batched-updates.ts +301 -0
- package/src/react19/replace-default-props.ts +212 -159
- package/src/react19/replace-react-shallow-renderer.ts +13 -36
- package/src/refactoring/class-to-functional.ts +3 -1
- package/src/refactoring/create-class-to-es6.ts +12 -63
- package/src/search/find-function-component-default-props.ts +8 -10
- package/src/search/find-redux-stores.ts +76 -0
- package/src/simplify-object-pattern-property.ts +22 -49
- package/src/simplify-react-imports.ts +12 -66
- package/src/testing/enzyme-to-react-testing-library.ts +112 -27
- package/src/testing/enzyme-wrapper-scope.ts +15 -10
- package/src/util/java-recipe-proxy.ts +15 -2
- package/src/util/reindent.ts +35 -0
- package/src/zustand/redux-stores.ts +409 -0
- package/src/zustand/redux-to-zustand.ts +657 -0
- package/src/zustand/zustand-plan.ts +843 -0
- package/dist/react18/remove-unstable-batched-updates.d.ts.map +0 -1
- package/dist/react18/remove-unstable-batched-updates.js +0 -170
- package/dist/react18/remove-unstable-batched-updates.js.map +0 -1
- package/src/react18/remove-unstable-batched-updates.ts +0 -192
|
@@ -168,6 +168,8 @@ export interface WrapperRead {
|
|
|
168
168
|
vacuous?: boolean;
|
|
169
169
|
/** A read outside an assertion, which throws where nothing is found, as Enzyme's single-node methods do. */
|
|
170
170
|
unasserted?: boolean;
|
|
171
|
+
/** A root `html()` a snapshot assertion stores, where Enzyme's `null` for an empty render and RTL's `""` differ. */
|
|
172
|
+
snapshot?: boolean;
|
|
171
173
|
className?: J.Literal;
|
|
172
174
|
event?: string;
|
|
173
175
|
eventInit?: Expression;
|
|
@@ -294,19 +296,19 @@ function nativeEventInit(event: string, init: J | undefined): [string, Expressio
|
|
|
294
296
|
}
|
|
295
297
|
|
|
296
298
|
/**
|
|
297
|
-
* `expect(wrapper.html())` with a matcher RTL's
|
|
298
|
-
*
|
|
299
|
+
* `expect(wrapper.html())` with a matcher RTL's container meets as Enzyme's `html()` does: `"snapshot"` where only the
|
|
300
|
+
* container's `null` for an empty render keeps a stored snapshot, `"string"` where a non-empty string fails either way.
|
|
299
301
|
*/
|
|
300
|
-
function innerHtmlAssertion(read: Cursor, html: J):
|
|
301
|
-
if (!expectArgument(read, html)) return
|
|
302
|
+
function innerHtmlAssertion(read: Cursor, html: J): "snapshot" | "string" | undefined {
|
|
303
|
+
if (!expectArgument(read, html)) return undefined;
|
|
302
304
|
const expect = read.parentTree()!;
|
|
303
305
|
const matcherCursor = expect.parentTree();
|
|
304
306
|
const matcher = matcherCursor?.value as J | undefined;
|
|
305
|
-
if (!selectOf(matcher, expect.value) || !statement(matcherCursor!)) return
|
|
307
|
+
if (!selectOf(matcher, expect.value) || !statement(matcherCursor!)) return undefined;
|
|
306
308
|
const args = (matcher as J.MethodInvocation).arguments.elements.filter(arg => arg.element.kind !== J.Kind.Empty).map(arg => arg.element);
|
|
307
|
-
if (call(matcher, "toMatchSnapshot")) return args.length === 0 || args.length === 1 && stringLiteral(args[0]);
|
|
309
|
+
if (call(matcher, "toMatchSnapshot")) return args.length === 0 || args.length === 1 && stringLiteral(args[0]) ? "snapshot" : undefined;
|
|
308
310
|
return (call(matcher, "toBe") || call(matcher, "toEqual") || call(matcher, "toContain")) &&
|
|
309
|
-
args.length === 1 && stringLiteral(args[0]) && (args[0] as J.Literal).value !== "";
|
|
311
|
+
args.length === 1 && stringLiteral(args[0]) && (args[0] as J.Literal).value !== "" ? "string" : undefined;
|
|
310
312
|
}
|
|
311
313
|
|
|
312
314
|
/** `expect(() => wrapper.unmount()).not.toThrow();`, which unmounts where it stands, as the statement `wrapper.unmount();` does. */
|
|
@@ -364,13 +366,14 @@ export function wrapperDeclaration<R>(statement: J | undefined, classify: (rende
|
|
|
364
366
|
/**
|
|
365
367
|
* Proves that every reference to a block-scoped wrapper is a supported DOM read, so the
|
|
366
368
|
* declaration and all its uses can be converted together. Any other reference, including
|
|
367
|
-
* arguments, returns, and shorthand properties, rejects the whole scope. `
|
|
369
|
+
* arguments, returns, and shorthand properties, rejects the whole scope. `optionalChaining` says whether the test's
|
|
370
|
+
* toolchain parses `?.` and `??`, without which a find within a positioned element is not converted. `events` are those `simulate`
|
|
368
371
|
* may dispatch, and `html` admits `html()` and the DOM node of a host element, none of which a shallow wrapper reads as the DOM does. `snapshots`
|
|
369
372
|
* admits `expect(wrapper).toMatchSnapshot()` and `expect(toJson(wrapper)).toMatchSnapshot()`, whose
|
|
370
373
|
* snapshot RTL records as the DOM rather than Enzyme's tree. `hostNames` decides the selectors {@link selectorLiteral} accepts.
|
|
371
374
|
*/
|
|
372
375
|
export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperDeclaration,
|
|
373
|
-
{events, html, untaggedPositions, hostNames, snapshots = false, constant = () => undefined}: {events: ReadonlySet<string>, html: boolean, untaggedPositions: boolean, hostNames: HostNames, snapshots?: boolean, constant?: (node: J) => string | undefined}): WrapperScope | undefined {
|
|
376
|
+
{events, html, untaggedPositions, hostNames, snapshots = false, optionalChaining = true, constant = () => undefined}: {events: ReadonlySet<string>, html: boolean, untaggedPositions: boolean, hostNames: HostNames, snapshots?: boolean, optionalChaining?: boolean, constant?: (node: J) => string | undefined}): WrapperScope | undefined {
|
|
374
377
|
let serializers: ReadonlySet<string> | undefined;
|
|
375
378
|
const uses = new Map<string, WrapperRead>();
|
|
376
379
|
const removedStatements = new Set<string>();
|
|
@@ -434,6 +437,7 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
434
437
|
inner = ancestors[k++].value;
|
|
435
438
|
const nested = ancestors[k]?.value as J | undefined;
|
|
436
439
|
if (call(nested, "find") && selectOf(nested, inner)) {
|
|
440
|
+
if (!optionalChaining) return false;
|
|
437
441
|
const [argument] = (nested as J.MethodInvocation).arguments.elements;
|
|
438
442
|
const withinText = (nested as J.MethodInvocation).arguments.elements.length === 1 ? selectorValue(argument.element) : undefined;
|
|
439
443
|
if (withinText === undefined || !onlyBelow(selectorText, withinText)) return false;
|
|
@@ -490,7 +494,8 @@ export function analyzeWrapperScope(block: Cursor, {declaration, name}: WrapperD
|
|
|
490
494
|
return record(method, {wrapper: identifier, use: "setProps", props: argument.element as Expression});
|
|
491
495
|
}
|
|
492
496
|
if (!noArguments(method)) return false;
|
|
493
|
-
|
|
497
|
+
const htmlAssertion = html && call(method, "html") ? innerHtmlAssertion(ancestors[0], method) : undefined;
|
|
498
|
+
if (htmlAssertion) return record(method, {wrapper: identifier, use: "rootHtml", snapshot: htmlAssertion === "snapshot"});
|
|
494
499
|
if (call(method, "text")) return record(method, {wrapper: identifier, use: "text", unasserted: !expectArgument(ancestors[0], method)});
|
|
495
500
|
if (call(method, "update") && statement(ancestors[0])?.prefix.comments.length === 0 && method.prefix.comments.length === 0) {
|
|
496
501
|
removedStatements.add(method.id);
|
|
@@ -11,6 +11,8 @@ const NODE_MANIFEST_TREES = ["org.openrewrite.json.tree.Json", "org.openrewrite.
|
|
|
11
11
|
// Native lock transactions also need package-manager policy, patches and hooks they must refuse.
|
|
12
12
|
const NODE_INPUTS = /(^|\/)(\.npmrc|\.yarnrc(?:\.yml)?|bunfig\.toml|\.?pnpmfile\.cjs)$|\.patch$/;
|
|
13
13
|
|
|
14
|
+
const manifestTrees = () => or(...NODE_MANIFEST_TREES.map(treesOfType));
|
|
15
|
+
|
|
14
16
|
export function isNodeDependencyInput(path: string, includeInputs = false): boolean {
|
|
15
17
|
return NODE_MANIFESTS.test(path) || includeInputs && NODE_INPUTS.test(path);
|
|
16
18
|
}
|
|
@@ -44,8 +46,19 @@ export abstract class JavaDependencyRecipe extends ScanningRecipe<number> {
|
|
|
44
46
|
return true;
|
|
45
47
|
}
|
|
46
48
|
|
|
49
|
+
/** Whether the Java recipe's edit of this manifest or lockfile is applied; one it returns false for is left as it was. */
|
|
50
|
+
protected edits(_manifest: SourceFile): boolean {
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// HACK: core's ScanningRecipe.editor() hides editorWithData behind a lazy wrapper, so PrepareRecipe would send the
|
|
55
|
+
// host no edit gate and the host would send the editor every tree (openrewrite/rewrite#9734)
|
|
56
|
+
override async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
57
|
+
return this.includePackageManagerInputs ? super.editor() : check(manifestTrees(), super.editor());
|
|
58
|
+
}
|
|
59
|
+
|
|
47
60
|
async editorWithData(acc: number): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
48
|
-
return manifestsOnly(async () => this.java.editorWithData(acc),
|
|
61
|
+
return manifestsOnly(async () => this.java.editorWithData(acc), manifest => this.edits(manifest), this.includePackageManagerInputs);
|
|
49
62
|
}
|
|
50
63
|
|
|
51
64
|
async generate(acc: number, ctx: ExecutionContext): Promise<SourceFile[]> {
|
|
@@ -77,5 +90,5 @@ async function manifestsOnly(remote: () => Promise<TreeVisitor<any, ExecutionCon
|
|
|
77
90
|
// tree, so this names the types for it. It reads the gate of a scanner only (openrewrite/rewrite#9734).
|
|
78
91
|
// Config and hook files can have any parser type; a plain visitor avoids requiring optional Java parser modules.
|
|
79
92
|
if (includeInputs) return manifests;
|
|
80
|
-
return await check(
|
|
93
|
+
return await check(manifestTrees(), manifests);
|
|
81
94
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import {Marker} from "@openrewrite/rewrite";
|
|
2
|
+
import {JavaScriptVisitor} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {Comment, isTextComment, J, TextComment} from "@openrewrite/rewrite/java";
|
|
4
|
+
|
|
5
|
+
/** The tree with each line it spans that is indented by `from` indented by `to` instead. */
|
|
6
|
+
export async function reindent<T extends J>(tree: T, from: string, to: string): Promise<T> {
|
|
7
|
+
if (from === to) return tree;
|
|
8
|
+
const shift = (text: string) => shiftLines(text, from, to);
|
|
9
|
+
const shiftSpace = (space: J.Space): J.Space => ({
|
|
10
|
+
...space,
|
|
11
|
+
whitespace: shift(space.whitespace),
|
|
12
|
+
comments: space.comments.map(c => ({...shiftComment(c, shift), suffix: shift(c.suffix)}))
|
|
13
|
+
});
|
|
14
|
+
return await new class extends JavaScriptVisitor<void> {
|
|
15
|
+
override async visitSpace(space: J.Space, p: void): Promise<J.Space> {
|
|
16
|
+
return shiftSpace(space);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// A trailing comma keeps the whitespace after it
|
|
20
|
+
protected override async visitMarker<M extends Marker>(marker: M, p: void): Promise<M> {
|
|
21
|
+
const suffix = (marker as any).suffix;
|
|
22
|
+
return suffix?.kind === J.Kind.Space ? {...marker, suffix: shiftSpace(suffix)} : marker;
|
|
23
|
+
}
|
|
24
|
+
}().visit(tree, undefined) as T;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The text with each line after its first that is indented by `from` indented by `to` instead. */
|
|
28
|
+
export function shiftLines(text: string, from: string, to: string): string {
|
|
29
|
+
return text.split('\n').map((line, i) => i > 0 && line.startsWith(from) ? to + line.substring(from.length) : line).join('\n');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The comment with `shift` applied to the lines its text spans, as only a block comment's can. */
|
|
33
|
+
export function shiftComment(comment: Comment, shift: (text: string) => string): Comment {
|
|
34
|
+
return isTextComment(comment) && comment.multiline ? {...comment, text: shift(comment.text)} as TextComment : comment;
|
|
35
|
+
}
|
|
@@ -0,0 +1,409 @@
|
|
|
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
|
+
/**
|
|
163
|
+
* The thunks and cases of `extraReducers` written as `builder => builder.addCase(thunk.pending, reducer)...`, where
|
|
164
|
+
* each thunk is a `createAsyncThunk` of the same source; otherwise why they can't be kept, for the review row.
|
|
165
|
+
*/
|
|
166
|
+
function thunkCases(value: J, cu: JS.CompilationUnit): {thunks: Map<string, SliceThunk>, cases: ThunkCase[]} | string {
|
|
167
|
+
const lambda = lambdaOf(value);
|
|
168
|
+
const parameters = lambda ? parametersOf(lambda) : [];
|
|
169
|
+
const builder = parameters.length === 1 ? plainParameter(parameters[0]) : undefined;
|
|
170
|
+
if (!lambda || !builder) return "`extraReducers` isn't a function of the builder";
|
|
171
|
+
const body = lambda.body as J;
|
|
172
|
+
const expressions = body.kind === J.Kind.Block ? (body as J.Block).statements.map(s => s.element) : [body];
|
|
173
|
+
const thunks = new Map<string, SliceThunk>();
|
|
174
|
+
const cases: ThunkCase[] = [];
|
|
175
|
+
for (let expression of expressions) {
|
|
176
|
+
if (expression.kind === JS.Kind.ExpressionStatement) expression = (expression as JS.ExpressionStatement).expression;
|
|
177
|
+
const chain: ThunkCase[] = [];
|
|
178
|
+
let node: J = expression;
|
|
179
|
+
while (node.kind === J.Kind.MethodInvocation) {
|
|
180
|
+
const call = node as J.MethodInvocation;
|
|
181
|
+
if (!call.select) break;
|
|
182
|
+
if (call.name.simpleName !== "addCase") return `\`builder.${call.name.simpleName}\``;
|
|
183
|
+
const args = call.arguments.elements.map(a => a.element).filter(a => a.kind !== J.Kind.Empty);
|
|
184
|
+
const matcher = args[0];
|
|
185
|
+
if (args.length !== 2 || matcher?.kind !== J.Kind.FieldAccess || !isIdentifier((matcher as J.FieldAccess).target) ||
|
|
186
|
+
!THUNK_STAGES.has((matcher as J.FieldAccess).name.element.simpleName)) return "a case for what isn't a stage of a thunk";
|
|
187
|
+
if (!lambdaOf(args[1])) return "a case reducer that isn't a function written in place";
|
|
188
|
+
const thunk = ((matcher as J.FieldAccess).target as J.Identifier).simpleName;
|
|
189
|
+
chain.unshift({thunk, stage: (matcher as J.FieldAccess).name.element.simpleName, reducer: args[1]});
|
|
190
|
+
node = call.select.element;
|
|
191
|
+
}
|
|
192
|
+
if (!isIdentifier(node) || node.simpleName !== builder || chain.length === 0) return "`extraReducers` does more than `builder.addCase`";
|
|
193
|
+
cases.push(...chain);
|
|
194
|
+
}
|
|
195
|
+
const seen = new Set<string>();
|
|
196
|
+
for (const {thunk, stage} of cases) {
|
|
197
|
+
if (seen.has(`${thunk}.${stage}`)) return `two cases for \`${thunk}.${stage}\``;
|
|
198
|
+
seen.add(`${thunk}.${stage}`);
|
|
199
|
+
if (thunks.has(thunk)) continue;
|
|
200
|
+
const found = asyncThunk(thunk, cu);
|
|
201
|
+
if (typeof found === "string") return found;
|
|
202
|
+
thunks.set(thunk, found);
|
|
203
|
+
}
|
|
204
|
+
return {thunks, cases};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** The top-level `const name = createAsyncThunk('type', payloadCreator)` of `cu`, or why `name` isn't one the conversion keeps. */
|
|
208
|
+
function asyncThunk(name: string, cu: JS.CompilationUnit): SliceThunk | string {
|
|
209
|
+
const createAsyncThunk = importedAs(cu, RTK, "createAsyncThunk");
|
|
210
|
+
for (const {element} of cu.statements) {
|
|
211
|
+
if (element.kind !== J.Kind.VariableDeclarations) continue;
|
|
212
|
+
const declarations = element as J.VariableDeclarations;
|
|
213
|
+
const variable = declarations.variables.find(v => isIdentifier(v.element.name) && v.element.name.simpleName === name)?.element;
|
|
214
|
+
if (!variable) continue;
|
|
215
|
+
const init = variable.initializer?.element;
|
|
216
|
+
const call = init?.kind === J.Kind.MethodInvocation ? init as J.MethodInvocation : undefined;
|
|
217
|
+
if (declarations.variables.length !== 1 || !declarations.modifiers.some(m => m.keyword === "const") || !call || call.select ||
|
|
218
|
+
!createAsyncThunk.has(call.name.simpleName)) return `\`${name}\` isn't a \`createAsyncThunk\` of the slice's source`;
|
|
219
|
+
const args = call.arguments.elements.map(a => a.element).filter(a => a.kind !== J.Kind.Empty);
|
|
220
|
+
if (args.length !== 2) return `\`${name}\` has options`;
|
|
221
|
+
if (args[0].kind !== J.Kind.Literal || typeof (args[0] as J.Literal).value !== "string") return `\`${name}\`'s type isn't a string literal`;
|
|
222
|
+
const creator = lambdaOf(args[1]);
|
|
223
|
+
if (!creator) return `\`${name}\`'s payload creator isn't an arrow function`;
|
|
224
|
+
const parameters = parametersOf(creator);
|
|
225
|
+
if (parameters.length > 2) return `\`${name}\`'s payload creator takes more than \`arg\` and \`thunkAPI\``;
|
|
226
|
+
if (parameters.length === 2) {
|
|
227
|
+
const api = plainParameter(parameters[1]);
|
|
228
|
+
if (!api) return `\`${name}\`'s \`thunkAPI\` isn't a plain parameter`;
|
|
229
|
+
// Every mention of `thunkAPI` must be a read of a member that stays within the thunk
|
|
230
|
+
let mentions = 0;
|
|
231
|
+
let kept = 0;
|
|
232
|
+
walk(creator.body, tree => {
|
|
233
|
+
const node = tree as J;
|
|
234
|
+
if (isIdentifier(node) && node.simpleName === api) mentions++;
|
|
235
|
+
const target = node.kind === J.Kind.FieldAccess ? (node as J.FieldAccess).target :
|
|
236
|
+
node.kind === J.Kind.MethodInvocation ? (node as J.MethodInvocation).select?.element : undefined;
|
|
237
|
+
const member = node.kind === J.Kind.FieldAccess ? (node as J.FieldAccess).name.element.simpleName :
|
|
238
|
+
node.kind === J.Kind.MethodInvocation ? (node as J.MethodInvocation).name.simpleName : undefined;
|
|
239
|
+
if (target && isIdentifier(target) && target.simpleName === api && member && THUNK_API.has(member)) kept++;
|
|
240
|
+
return true;
|
|
241
|
+
});
|
|
242
|
+
if (mentions !== kept) return `\`${name}\` uses \`${api}\` for more than ${[...THUNK_API].map(m => `\`${m}\``).join(", ")}`;
|
|
243
|
+
}
|
|
244
|
+
return {variable: name, typePrefix: (args[0] as J.Literal).value as string};
|
|
245
|
+
}
|
|
246
|
+
return `\`${name}\` isn't a \`createAsyncThunk\` of the slice's source`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** `slice.reducer` for a slice `slices` names. */
|
|
250
|
+
function reducerOf(node: J | undefined, slices: ReadonlyMap<string, SliceFacts>): SliceFacts | undefined {
|
|
251
|
+
if (node?.kind !== J.Kind.FieldAccess) return undefined;
|
|
252
|
+
const access = node as J.FieldAccess;
|
|
253
|
+
return access.name.element.simpleName === "reducer" && isIdentifier(access.target) ? slices.get(access.target.simpleName) : undefined;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function exportKeywords(modifiers: J.Modifier[]): {exported: boolean, isDefault: boolean} {
|
|
257
|
+
const keywords = new Set(modifiers.map(modifier => modifier.keyword));
|
|
258
|
+
return {exported: keywords.has("export"), isDefault: keywords.has("default")};
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** The slices `cu` declares at its top level and the ones it exports. */
|
|
262
|
+
export function localSlices(cu: JS.CompilationUnit): LocalSlices {
|
|
263
|
+
const createSlice = importedAs(cu, RTK, "createSlice");
|
|
264
|
+
const result: LocalSlices = {localSlices: new Map(), localReducers: new Map(), reducers: new Map(), slices: new Map()};
|
|
265
|
+
if (createSlice.size === 0) return result;
|
|
266
|
+
const exportedNames: [string, string][] = [];
|
|
267
|
+
for (const {element} of cu.statements) {
|
|
268
|
+
if (element.kind === J.Kind.VariableDeclarations) {
|
|
269
|
+
const declarations = element as J.VariableDeclarations;
|
|
270
|
+
const {exported} = exportKeywords(declarations.modifiers);
|
|
271
|
+
for (const {element: variable} of declarations.variables) {
|
|
272
|
+
if (!isIdentifier(variable.name)) continue;
|
|
273
|
+
const name = variable.name.simpleName;
|
|
274
|
+
const init = variable.initializer?.element;
|
|
275
|
+
const slice = sliceFacts(init, createSlice, cu, name);
|
|
276
|
+
if (slice) result.localSlices.set(name, slice);
|
|
277
|
+
const reducer = reducerOf(init, result.localSlices);
|
|
278
|
+
if (reducer) result.localReducers.set(name, reducer);
|
|
279
|
+
if (exported) exportedNames.push([name, name]);
|
|
280
|
+
}
|
|
281
|
+
} else if (element.kind === JS.Kind.ExportAssignment) {
|
|
282
|
+
const expression = (element as JS.ExportAssignment).expression.element;
|
|
283
|
+
const reducer = reducerOf(expression, result.localSlices) ??
|
|
284
|
+
(isIdentifier(expression) ? result.localReducers.get(expression.simpleName) : undefined);
|
|
285
|
+
if (reducer) result.reducers.set("default", reducer);
|
|
286
|
+
const slice = sliceFacts(expression, createSlice, cu, "") ?? (isIdentifier(expression) ? result.localSlices.get(expression.simpleName) : undefined);
|
|
287
|
+
if (slice) result.slices.set("default", slice);
|
|
288
|
+
} else if (element.kind === JS.Kind.ExportDeclaration) {
|
|
289
|
+
const declaration = element as JS.ExportDeclaration;
|
|
290
|
+
if (declaration.moduleSpecifier || declaration.exportClause?.kind !== JS.Kind.NamedExports) continue;
|
|
291
|
+
for (const {element: specifier} of (declaration.exportClause as JS.NamedExports).elements.elements) {
|
|
292
|
+
if (specifier.kind !== JS.Kind.ExportSpecifier) continue;
|
|
293
|
+
const named = (specifier as JS.ExportSpecifier).specifier;
|
|
294
|
+
if (isIdentifier(named)) exportedNames.push([named.simpleName, named.simpleName]);
|
|
295
|
+
else if (named.kind === JS.Kind.Alias) {
|
|
296
|
+
const alias = named as JS.Alias;
|
|
297
|
+
const local = alias.propertyName.element;
|
|
298
|
+
if (isIdentifier(local) && isIdentifier(alias.alias)) exportedNames.push([local.simpleName, alias.alias.simpleName]);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
for (const [local, exported] of exportedNames) {
|
|
304
|
+
const slice = result.localSlices.get(local);
|
|
305
|
+
if (slice) result.slices.set(exported, slice);
|
|
306
|
+
const reducer = result.localReducers.get(local);
|
|
307
|
+
if (reducer) result.reducers.set(exported, reducer);
|
|
308
|
+
}
|
|
309
|
+
return result;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Resolves a reducer expression of a store to the slice it is the reducer of. */
|
|
313
|
+
export function resolveSliceReducer(node: J, cu: JS.CompilationUnit, local: LocalSlices, modules: ReadonlyMap<string, SliceModule>): SliceFacts | undefined {
|
|
314
|
+
const inFile = reducerOf(node, local.localSlices) ?? (isIdentifier(node) ? local.localReducers.get(node.simpleName) : undefined);
|
|
315
|
+
if (inFile) return inFile;
|
|
316
|
+
const imported = (name: string) => {
|
|
317
|
+
const binding = importBindings(cu).find(b => b.local === name);
|
|
318
|
+
const path = binding && resolveRelative(cu.sourcePath, binding.module, modules);
|
|
319
|
+
return path ? {binding, module: modules.get(path)!} : undefined;
|
|
320
|
+
};
|
|
321
|
+
if (isIdentifier(node)) {
|
|
322
|
+
const found = imported(node.simpleName);
|
|
323
|
+
return found?.module.reducers.get(found.binding.name);
|
|
324
|
+
}
|
|
325
|
+
if (node.kind === J.Kind.FieldAccess) {
|
|
326
|
+
const access = node as J.FieldAccess;
|
|
327
|
+
if (access.name.element.simpleName !== "reducer" || !isIdentifier(access.target)) return undefined;
|
|
328
|
+
const found = imported(access.target.simpleName);
|
|
329
|
+
return found?.module.slices.get(found.binding.name);
|
|
330
|
+
}
|
|
331
|
+
return undefined;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export const SUGGESTED_ACTIONS: Readonly<Record<string, string>> = {
|
|
335
|
+
SLICE_STORE: "A store of `createSlice` reducers with the default middleware: each slice can become a zustand store. Check its consumers next.",
|
|
336
|
+
LEGACY_STORE: "Move the store to Redux Toolkit's `configureStore` and its reducers to `createSlice` first, or write the zustand store by hand.",
|
|
337
|
+
OPTIONS_NOT_LITERAL: "Write the `configureStore` options as an object literal, so that the setup can be read.",
|
|
338
|
+
ROOT_REDUCER: "Pass `reducer` as an object of slice reducers; a single root reducer, such as `combineReducers(...)`, can't be split into zustand stores.",
|
|
339
|
+
NON_SLICE_REDUCER: "Rewrite this reducer with `createSlice`, or keep it in Redux; zustand has no place for a hand-written reducer.",
|
|
340
|
+
EXTRA_REDUCERS: "Write `extraReducers` as `builder.addCase(thunk.pending, reducer)` cases of `createAsyncThunk`s declared in the slice's source, whose payload creators use only `rejectWithValue`, `fulfillWithValue`, `signal` and `requestId` of `thunkAPI`, or move what it handles into actions of the zustand store by hand.",
|
|
341
|
+
SLICE_OPTIONS_NOT_LITERAL: "Write the `createSlice` options as an object literal, so that the slice can be read.",
|
|
342
|
+
SLICE_REDUCERS_NOT_LITERAL: "Write `reducers` as an object of reducer functions; the builder callback form can't be read.",
|
|
343
|
+
MIDDLEWARE: "Custom middleware has no zustand equivalent: move it into the store's actions or zustand middleware by hand.",
|
|
344
|
+
ENHANCERS: "Store enhancers have no zustand equivalent: replace them by hand, for example with zustand middleware.",
|
|
345
|
+
PRELOADED_STATE: "Merge the preloaded state into the slices' initial state, or set it on the zustand store after it is created.",
|
|
346
|
+
DEVTOOLS: "Configure zustand's `devtools` middleware to match the `devTools` option by hand.",
|
|
347
|
+
UNKNOWN_OPTION: "Review this `configureStore` option by hand."
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
export const TEST_SOURCE = /(^|\/)(__tests__|__mocks__|tests?|stories)\/|\.(test|spec|stories)\.[jt]sx?$/i;
|
|
351
|
+
|
|
352
|
+
/** The options of `configureStore` that keep a store from converting, by the reason they are recorded under. */
|
|
353
|
+
const BLOCKING_OPTIONS: Readonly<Record<string, string>> = {
|
|
354
|
+
middleware: "MIDDLEWARE", enhancers: "ENHANCERS", preloadedState: "PRELOADED_STATE", devTools: "DEVTOOLS"
|
|
355
|
+
};
|
|
356
|
+
|
|
357
|
+
export interface Finding {
|
|
358
|
+
reason: string;
|
|
359
|
+
detail: string;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** The local names a source calls to create a Redux store: legacy `createStore` and Redux Toolkit's `configureStore`. */
|
|
363
|
+
export function storeFunctions(cu: JS.CompilationUnit): {legacy: Set<string>, configure: Set<string>} {
|
|
364
|
+
return {
|
|
365
|
+
legacy: new Set([...importedAs(cu, REDUX, "createStore", "legacy_createStore"), ...importedAs(cu, RTK, "createStore", "legacy_createStore")]),
|
|
366
|
+
configure: importedAs(cu, RTK, "configureStore")
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Why the store `call` creates can't move to zustand, or `[]` for a candidate, with the slices of its reducers by key.
|
|
372
|
+
* `undefined` when `call` creates no store.
|
|
373
|
+
*/
|
|
374
|
+
export function storeFindings(call: J.MethodInvocation, cu: JS.CompilationUnit, modules: ReadonlyMap<string, SliceModule>,
|
|
375
|
+
functions = storeFunctions(cu)): {api: string, findings: Finding[], slices: Map<string, SliceFacts>} | undefined {
|
|
376
|
+
if (call.select) return undefined;
|
|
377
|
+
const api = call.name.simpleName;
|
|
378
|
+
if (functions.legacy.has(api)) return {api, findings: [{reason: "LEGACY_STORE", detail: api}], slices: new Map()};
|
|
379
|
+
if (!functions.configure.has(api)) return undefined;
|
|
380
|
+
const slices = new Map<string, SliceFacts>();
|
|
381
|
+
const options = objectProperties(call.arguments.elements[0]?.element);
|
|
382
|
+
if (!options) return {api, findings: [{reason: "OPTIONS_NOT_LITERAL", detail: ""}], slices};
|
|
383
|
+
const findings: Finding[] = [];
|
|
384
|
+
for (const key of options.keys()) {
|
|
385
|
+
if (key !== "reducer") findings.push({reason: BLOCKING_OPTIONS[key] ?? "UNKNOWN_OPTION", detail: key});
|
|
386
|
+
}
|
|
387
|
+
const reducers = objectProperties(options.get("reducer"));
|
|
388
|
+
if (!reducers) return {api, findings: [...findings, {reason: "ROOT_REDUCER", detail: ""}], slices};
|
|
389
|
+
const local = localSlices(cu);
|
|
390
|
+
for (const [key, value] of reducers) {
|
|
391
|
+
const slice = resolveSliceReducer(value, cu, local, modules);
|
|
392
|
+
if (!slice) findings.push({reason: "NON_SLICE_REDUCER", detail: key});
|
|
393
|
+
else if (slice.blocker) findings.push(slice.blocker);
|
|
394
|
+
else slices.set(key, slice);
|
|
395
|
+
}
|
|
396
|
+
return {api, findings, slices};
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** The variable or function a store is created in, such as `store` in `export const store = configureStore(...)`. */
|
|
400
|
+
export function storeName(cursor: Cursor): string {
|
|
401
|
+
for (let c: Cursor | undefined = cursor.parent; c; c = c.parent) {
|
|
402
|
+
const node = c.value as J;
|
|
403
|
+
if (node?.kind === J.Kind.NamedVariable && isIdentifier((node as J.VariableDeclarations.NamedVariable).name)) {
|
|
404
|
+
return ((node as J.VariableDeclarations.NamedVariable).name as J.Identifier).simpleName;
|
|
405
|
+
}
|
|
406
|
+
if (node?.kind === J.Kind.MethodDeclaration) return (node as J.MethodDeclaration).name.simpleName;
|
|
407
|
+
}
|
|
408
|
+
return "<module>";
|
|
409
|
+
}
|