@openrewrite/recipes-react 0.19.0 → 0.20.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 (39) hide show
  1. package/dist/search/find-enzyme-usage.d.ts.map +1 -1
  2. package/dist/search/find-enzyme-usage.js +34 -1
  3. package/dist/search/find-enzyme-usage.js.map +1 -1
  4. package/dist/testing/enzyme-shared-wrapper.d.ts +26 -0
  5. package/dist/testing/enzyme-shared-wrapper.d.ts.map +1 -0
  6. package/dist/testing/enzyme-shared-wrapper.js +213 -0
  7. package/dist/testing/enzyme-shared-wrapper.js.map +1 -0
  8. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  9. package/dist/testing/enzyme-to-react-testing-library.js +276 -0
  10. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  11. package/dist/testing/enzyme-usage.d.ts +3 -1
  12. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  13. package/dist/testing/enzyme-usage.js +19 -3
  14. package/dist/testing/enzyme-usage.js.map +1 -1
  15. package/dist/testing/enzyme-wrapper-scope.d.ts +2 -0
  16. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  17. package/dist/testing/enzyme-wrapper-scope.js +12 -6
  18. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  19. package/dist/zustand/redux-stores.d.ts +10 -0
  20. package/dist/zustand/redux-stores.d.ts.map +1 -1
  21. package/dist/zustand/redux-stores.js +147 -5
  22. package/dist/zustand/redux-stores.js.map +1 -1
  23. package/dist/zustand/redux-to-zustand.d.ts +20 -5
  24. package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
  25. package/dist/zustand/redux-to-zustand.js +518 -26
  26. package/dist/zustand/redux-to-zustand.js.map +1 -1
  27. package/dist/zustand/zustand-plan.d.ts +27 -4
  28. package/dist/zustand/zustand-plan.d.ts.map +1 -1
  29. package/dist/zustand/zustand-plan.js +250 -15
  30. package/dist/zustand/zustand-plan.js.map +1 -1
  31. package/package.json +1 -1
  32. package/src/search/find-enzyme-usage.ts +32 -3
  33. package/src/testing/enzyme-shared-wrapper.ts +224 -0
  34. package/src/testing/enzyme-to-react-testing-library.ts +265 -2
  35. package/src/testing/enzyme-usage.ts +27 -3
  36. package/src/testing/enzyme-wrapper-scope.ts +11 -4
  37. package/src/zustand/redux-stores.ts +160 -5
  38. package/src/zustand/redux-to-zustand.ts +555 -34
  39. package/src/zustand/zustand-plan.ts +267 -12
@@ -3,7 +3,7 @@ import {JavaScriptVisitor, JS, JSX, namesReferencedWithin} from "@openrewrite/re
3
3
  import {isIdentifier, J} from "@openrewrite/rewrite/java";
4
4
  import {posix} from "path";
5
5
  import {ImportBinding, importBindings, isRelativeSpecifier, resolveRelative} from "../util/module-imports";
6
- import {Finding, localSlices, objectProperties, RTK, SliceFacts, SliceModule, storeFindings, storeFunctions, TEST_SOURCE} from "./redux-stores";
6
+ import {Finding, localSlices, ReducerStoreKind, objectProperties, RTK, SliceFacts, SliceModule, storeFindings, storeFunctions, TEST_SOURCE} from "./redux-stores";
7
7
 
8
8
  export const REACT_REDUX = "react-redux";
9
9
 
@@ -23,6 +23,8 @@ export type UseKind =
23
23
  "dispatcher" |
24
24
  /** The `Provider` tag itself. */
25
25
  "providerTag" |
26
+ /** `connect(...)` with no `mergeProps` and no option but `forwardRef`, which moves with its whole store. */
27
+ "connect" |
26
28
  /** Anything else, which keeps the store from converting. */
27
29
  "other";
28
30
 
@@ -37,6 +39,12 @@ export interface Use {
37
39
  detail?: string;
38
40
  /** The reason an `other` use is recorded under, when it is more precise than the kind of import it uses. */
39
41
  reason?: string;
42
+ /** For a call of a member of an import, `store.getState()`, the member called. */
43
+ member?: string;
44
+ /** For `useSelector(name)`, the name the selector is passed by. */
45
+ selector?: string;
46
+ /** For `useSelector(selector)` with one argument and no type arguments, which a whole store runs as it is. */
47
+ anySelector?: boolean;
40
48
  }
41
49
 
42
50
  /** What one source tells the plan. */
@@ -52,6 +60,11 @@ export interface SourceFacts {
52
60
  unfollowed: {module: string, detail: string}[];
53
61
  /** The Redux stores the source creates. */
54
62
  stores: StoreFacts[];
63
+ /**
64
+ * The top-level `const name = state => state.key...` the source declares once, plain reads of the state, and those
65
+ * of them it exports as declared.
66
+ */
67
+ readSelectors: {local: ReadonlySet<string>, exported: ReadonlySet<string>};
55
68
  }
56
69
 
57
70
  export interface StoreFacts {
@@ -62,6 +75,15 @@ export interface StoreFacts {
62
75
  slices: Map<string, SliceFacts>;
63
76
  /** The name the store module exports the store as, `default`, or undefined when it isn't exported at the top level. */
64
77
  exportedAs?: string;
78
+ /**
79
+ * For a store that can move to zustand whole driven by its reducer, a `configureStore` of its `reducer` alone or a
80
+ * legacy `createStore` without an enhancer, how its reducer is given.
81
+ */
82
+ reducerStore?: ReducerStoreKind;
83
+ /** Whether the store's own source uses the store other than to declare and export it, or to call its `getState`, `dispatch` or `subscribe`. */
84
+ usedInSource?: boolean;
85
+ /** The members of the store its own source calls, such as `subscribe`. */
86
+ calledInSource?: ReadonlySet<string>;
65
87
  }
66
88
 
67
89
  /** The parent tree of the node at `cursor`, past paddings and containers. */
@@ -212,13 +234,30 @@ export function walk(node: unknown, visit: (tree: J) => boolean): void {
212
234
 
213
235
  const SKIPPED = new Set(["markers", "prefix", "type", "methodType", "fieldType", "variableType", "constructorType", "javaType", "before", "after"]);
214
236
 
237
+ /** The plain-read selectors `cu` declares, as {@link SourceFacts.readSelectors} says. */
238
+ function readSelectors(cu: JS.CompilationUnit, declared: ReadonlyMap<string, number>): SourceFacts["readSelectors"] {
239
+ const local = new Set<string>();
240
+ const exported = new Set<string>();
241
+ for (const {element} of cu.statements) {
242
+ if (element.kind !== J.Kind.VariableDeclarations) continue;
243
+ const declarations = element as J.VariableDeclarations;
244
+ if (!declarations.modifiers.some(m => m.keyword === "const")) continue;
245
+ for (const {element: variable} of declarations.variables) {
246
+ if (!isIdentifier(variable.name) || declared.get(variable.name.simpleName) !== 1 || !selectorRead(variable.initializer?.element)) continue;
247
+ local.add(variable.name.simpleName);
248
+ if (declarations.modifiers.some(m => m.keyword === "export")) exported.add(variable.name.simpleName);
249
+ }
250
+ }
251
+ return {local, exported};
252
+ }
253
+
215
254
  /** The facts of one source, read once while scanning. */
216
255
  export async function sourceFacts(cu: JS.CompilationUnit): Promise<SourceFacts> {
217
256
  const bindings = importBindings(cu);
218
257
  const declared = declaredNames(cu);
219
258
  const facts: SourceFacts = {
220
259
  path: cu.sourcePath, typescript: /\.(?:ts|tsx|mts|cts)$/.test(cu.sourcePath), test: TEST_SOURCE.test(cu.sourcePath),
221
- bindings, declared: new Set(declared.keys()), uses: [], unfollowed: [], stores: []
260
+ bindings, declared: new Set(declared.keys()), uses: [], unfollowed: [], stores: [], readSelectors: readSelectors(cu, declared)
222
261
  };
223
262
  const followed = new Map(bindings.filter(binding => binding.module === REACT_REDUX || isRelativeSpecifier(binding.module))
224
263
  .map(binding => [binding.local, binding]));
@@ -283,8 +322,10 @@ export async function storeFacts(cu: JS.CompilationUnit, modules: ReadonlyMap<st
283
322
  override async visitMethodInvocation(call: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
284
323
  const store = storeFindings(call, cu, modules, functions);
285
324
  if (store) {
286
- stores.push({path: cu.sourcePath, api: store.api, store: storeNameAt(this.cursor), findings: store.findings,
287
- slices: store.slices, exportedAs: exportedStore(cu, this.cursor)});
325
+ const name = storeNameAt(this.cursor);
326
+ const own = await usesInSource(cu, name, call);
327
+ stores.push({path: cu.sourcePath, api: store.api, store: name, findings: store.findings,
328
+ slices: store.slices, exportedAs: exportedStore(cu, this.cursor), reducerStore: store.reducerStore, usedInSource: own.other, calledInSource: own.called});
288
329
  }
289
330
  return super.visitMethodInvocation(call, ctx);
290
331
  }
@@ -348,10 +389,14 @@ function classify(identifier: J.Identifier, binding: ImportBinding, cursor: Curs
348
389
  if (binding.module === REACT_REDUX) {
349
390
  if (parent?.kind !== J.Kind.MethodInvocation || (parent as J.MethodInvocation).name !== identifier) return other(`\`${binding.name}\` from react-redux`);
350
391
  const call = parent as J.MethodInvocation;
392
+ if (binding.name === "connect") return connectUse(call, other) ?? {local, kind: "connect"};
351
393
  if (binding.name === "useSelector") {
352
394
  const args = argumentsOf(call);
353
395
  const read = args.length === 1 && !call.typeParameters ? selectorRead(args[0]) : undefined;
354
- return read ? {local, kind: "selector", key: read.key} : {...other("a selector that isn't a read of one slice's state"), reason: "SELECTOR"};
396
+ if (read) return {local, kind: "selector", key: read.key};
397
+ // A selector passed by name moves only with its whole store, which calls it as it is
398
+ const selector = args.length === 1 && !call.typeParameters && isIdentifier(args[0]) ? args[0].simpleName : undefined;
399
+ return {...other("a selector that isn't a read of one slice's state"), reason: "SELECTOR", selector, anySelector: args.length === 1 && !call.typeParameters};
355
400
  }
356
401
  if (binding.name === "useDispatch") {
357
402
  const variable = parentTree(cursorOf(cursor, call));
@@ -377,10 +422,11 @@ function classify(identifier: J.Identifier, binding: ImportBinding, cursor: Curs
377
422
  const outer = parentTree(cursorOf(cursor, call));
378
423
  const read = getStateRead(call, outer);
379
424
  if (read) return {local, kind: "getState", key: read.key};
380
- if (call.name.simpleName === "dispatch" && dispatchedAction(call)) {
381
- return isStatement(call, outer) ? {local, kind: "storeDispatch"} : {...other("the dispatch's result is used"), reason: "DISPATCH"};
425
+ const member = call.name.simpleName;
426
+ if (member === "dispatch" && dispatchedAction(call)) {
427
+ return isStatement(call, outer) ? {local, kind: "storeDispatch", member} : {...other("the dispatch's result is used"), reason: "DISPATCH", member};
382
428
  }
383
- return other(`\`${local}.${call.name.simpleName}\``);
429
+ return {...other(`\`${local}.${member}\``), member};
384
430
  }
385
431
  if (parent?.kind === JS.Kind.JsxEmbeddedExpression) {
386
432
  const attribute = trees[2];
@@ -395,6 +441,24 @@ function classify(identifier: J.Identifier, binding: ImportBinding, cursor: Curs
395
441
  return other("referenced");
396
442
  }
397
443
 
444
+ /** Why a call of `connect` can't move to the zustand store's own `connect`, if it can't. */
445
+ function connectUse(call: J.MethodInvocation, other: (detail: string) => Use): Use | undefined {
446
+ const args = argumentsOf(call);
447
+ // NOTE: a `null` read back from a stored LST doesn't keep `value: null`, so its source decides
448
+ const absent = (node: J | undefined) => !node ||
449
+ node.kind === J.Kind.Literal && (node as J.Literal).valueSource === "null" ||
450
+ isIdentifier(node) && node.simpleName === "undefined";
451
+ if (args.length > 4 || !absent(args[2])) return other("`connect` with `mergeProps`");
452
+ if (args.length === 4 && !absent(args[3])) {
453
+ const options = objectProperties(args[3]);
454
+ const forwardRef = options?.get("forwardRef");
455
+ if (!options || options.size !== 1 || forwardRef?.kind !== J.Kind.Literal || typeof (forwardRef as J.Literal).value !== "boolean") {
456
+ return other("`connect` with options other than `forwardRef`");
457
+ }
458
+ }
459
+ return undefined;
460
+ }
461
+
398
462
  /** A use of a dispatcher from `useDispatch`: only `dispatch(x(...))` of an imported `x`, whose result is unused, converts. */
399
463
  function dispatcherUse(identifier: J.Identifier, cursor: Cursor, followed: ReadonlyMap<string, ImportBinding>,
400
464
  bindings: readonly ImportBinding[]): Use | undefined {
@@ -422,10 +486,16 @@ function providerUse(tag: JSX.Tag, followed: ReadonlyMap<string, ImportBinding>,
422
486
  const value = (attributes[0] as JSX.Attribute).value?.element;
423
487
  const expression = value?.kind === JS.Kind.JsxEmbeddedExpression ? (value as JSX.EmbeddedExpression).expression.element : undefined;
424
488
  if (!isIdentifier(expression) || !followed.has(expression.simpleName)) return other("`Provider` of a store that isn't imported");
425
- if (!providerChild(tag)) return other("`Provider` without exactly one element child");
489
+ if (!providerChild(tag) && !providerChildren(tag)) return other("`Provider` without children");
426
490
  return {local, kind: "providerTag"};
427
491
  }
428
492
 
493
+ /** Whether a tag has children other than whitespace, which a fragment keeps when the tag goes. */
494
+ export function providerChildren(tag: JSX.Tag): boolean {
495
+ return !tag.selfClosing && (tag.children ?? []).some(child => !(child.kind === J.Kind.Literal && String((child as J.Literal).value ?? "").trim() === "") &&
496
+ child.kind !== J.Kind.Empty);
497
+ }
498
+
429
499
  /** The one element child of a tag, with only whitespace around it. */
430
500
  export function providerChild(tag: JSX.Tag): JSX.Tag | undefined {
431
501
  const children = (tag.children ?? []).filter(child => !(child.kind === J.Kind.Literal && String((child as J.Literal).value ?? "").trim() === "") &&
@@ -439,6 +509,49 @@ function cursorOf(cursor: Cursor, node: J): Cursor {
439
509
  return cursor;
440
510
  }
441
511
 
512
+ /** Members of a store that a whole store keeps, so that a call of one on the store's variable stays as it is. */
513
+ export const STORE_MEMBERS: ReadonlySet<string> = new Set(["getState", "dispatch", "subscribe"]);
514
+
515
+ /**
516
+ * How the statements of `cu` other than the store's declaration, `call`, and `export default name` refer to the store's
517
+ * variable: the members of `STORE_MEMBERS` they call on it, and whether they refer to it any other way.
518
+ */
519
+ async function usesInSource(cu: JS.CompilationUnit, name: string, call: J.MethodInvocation): Promise<{other: boolean, called: Set<string>}> {
520
+ const result = {other: false, called: new Set<string>()};
521
+ const statements = cu.statements.map(s => s.element).flatMap(statement => {
522
+ if (statement.kind === JS.Kind.Import) return [];
523
+ if (statement.kind === JS.Kind.ExportAssignment && isIdentifier((statement as JS.ExportAssignment).expression.element) &&
524
+ ((statement as JS.ExportAssignment).expression.element as J.Identifier).simpleName === name) return [];
525
+ if (statement.kind === J.Kind.VariableDeclarations && (statement as J.VariableDeclarations).variables.some(v => v.element.initializer?.element === call)) {
526
+ return [call];
527
+ }
528
+ return [statement];
529
+ });
530
+ for (const statement of statements) {
531
+ if (![...namesReferencedWithin(statement)].includes(name)) continue;
532
+ await new class extends JavaScriptVisitor<ExecutionContext> {
533
+ override async visitIdentifier(identifier: J.Identifier, ctx: ExecutionContext): Promise<J | undefined> {
534
+ if (identifier.simpleName !== name) return identifier;
535
+ const parent = parentTree(this.cursor);
536
+ // Names of members and properties are no use of the store
537
+ if (parent?.kind === J.Kind.FieldAccess && (parent as J.FieldAccess).name.element === identifier) return identifier;
538
+ if (parent?.kind === J.Kind.MethodInvocation && (parent as J.MethodInvocation).name === identifier) {
539
+ if ((parent as J.MethodInvocation).select) return identifier;
540
+ } else if (parent?.kind === J.Kind.MethodInvocation && (parent as J.MethodInvocation).select?.element === identifier &&
541
+ STORE_MEMBERS.has((parent as J.MethodInvocation).name.simpleName)) {
542
+ result.called.add((parent as J.MethodInvocation).name.simpleName);
543
+ return identifier;
544
+ }
545
+ if (parent?.kind === JS.Kind.PropertyAssignment && (parent as JS.PropertyAssignment).name.element === identifier &&
546
+ (parent as JS.PropertyAssignment).initializer) return identifier;
547
+ result.other = true;
548
+ return identifier;
549
+ }
550
+ }().visit(statement, new ExecutionContext());
551
+ }
552
+ return result;
553
+ }
554
+
442
555
  function storeNameAt(cursor: Cursor): string {
443
556
  for (let c: Cursor | undefined = cursor.parent; c; c = c.parent) {
444
557
  const node = c.value as J;
@@ -497,8 +610,25 @@ export interface Plan {
497
610
  sources: Set<string>;
498
611
  /** Why each store doesn't convert, by store; the converting store has no entry. */
499
612
  blocked: Map<StoreFacts, Finding[]>;
613
+ /**
614
+ * For a store that moves to zustand whole, the names the conversion gives its zustand store and its reducer, and,
615
+ * where a source calls `connect`, the module whose `unstable_batchedUpdates` the store's `connect` renders with.
616
+ */
617
+ reducerStore?: {hook: string, reducer: string, renderer?: string, selectorHook?: string, listeners?: string};
500
618
  }
501
619
 
620
+ /**
621
+ * The hook a whole store's source declares for selectors that may build a value, where the store's own hook, as
622
+ * zustand 5's does, runs the selector on each read: it keeps the selection while the state and the selector stay.
623
+ */
624
+ export const SELECTOR_HOOK = "useAppStoreSelector";
625
+
626
+ /** The `Map` a whole store's source keeps the listeners of its `subscribe` in. */
627
+ export const STORE_LISTENERS = "storeListeners";
628
+
629
+ /** The zustand store a store becomes when it moves whole, driven by its own reducer. */
630
+ export const REDUCER_STORE_HOOK = "useAppStore";
631
+
502
632
  /** The hook a slice under `key` becomes, such as `useCounterStore` for `counter`. */
503
633
  export const hookName = (key: string) => `use${key.charAt(0).toUpperCase()}${key.slice(1)}Store`;
504
634
 
@@ -507,7 +637,9 @@ export const hookName = (key: string) => `use${key.charAt(0).toUpperCase()}${key
507
637
  * slices can be rewritten, and every use of the store, its slices, their action creators and react-redux converts.
508
638
  */
509
639
  export function plan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: ReadonlyMap<string, SliceSource>,
510
- dependencies: (storePath: string) => Finding | undefined, scope: (path: string) => boolean = () => true): Plan {
640
+ dependencies: (storePath: string, immer?: boolean) => Finding | undefined, scope: (path: string) => boolean = () => true,
641
+ wholeStores = true, renderer: (storePath: string) => string | undefined = () => "react-dom",
642
+ selectsOnEachRead: (storePath: string) => boolean = () => false): Plan {
511
643
  const stores = [...facts.values()].filter(source => scope(source.path)).flatMap(source => source.stores);
512
644
  const result: Plan = {slices: new Map(), sources: new Set(), blocked: new Map()};
513
645
  if (stores.length === 0) return result;
@@ -615,6 +747,8 @@ export function plan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: Read
615
747
  if (!slice || !binding || !slice.actions.has(binding.name) && !slice.unknown.has(binding.name) && !slice.thunkVariables.has(binding.name)) block("DISPATCH", `${where} dispatches what isn't an action creator of a slice`);
616
748
  const via = source.bindings.find(b => b.local === use.via);
617
749
  if (via && !(resolve(via.module) === store.path && via.name === store.exportedAs)) block("DISPATCH", `${where} is dispatched through \`${use.via}\``);
750
+ } else if (use.kind === "connect") {
751
+ block("REACT_REDUX_USE", `${where}: \`connect\` from react-redux`);
618
752
  } else if ((use.kind === "provider" || use.kind === "storeDispatch") && !isStore) {
619
753
  block("STORE_USE", `${where} isn't the store`);
620
754
  }
@@ -639,6 +773,8 @@ export function plan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: Read
639
773
  }
640
774
  }
641
775
  if ([store.path, ...slicePaths.keys()].some(path => /\.(?:ts|tsx|mts|cts)$/.test(path))) block("TYPESCRIPT", store.path);
776
+ // A store whose slices can't move one by one may still move whole, its reducer running on one zustand store
777
+ if (findings.length > 0 && store.reducerStore && wholeStores) return reducerPlan(facts, sliceSources, store, dependencies, scope, renderer, selectsOnEachRead);
642
778
  if (findings.length > 0) {
643
779
  result.blocked.set(store, dedupe(findings));
644
780
  result.slices.clear();
@@ -649,15 +785,134 @@ export function plan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: Read
649
785
  return result;
650
786
  }
651
787
 
788
+ /**
789
+ * Plans a store of its `reducer` alone to move whole: one zustand store whose state is the reducer's, and whose
790
+ * `dispatch` runs the reducer as Redux does, and thunks as Redux Toolkit's default middleware does. The slices, their
791
+ * action creators and thunks stay as they are, so only the uses of react-redux and of the store itself must convert.
792
+ */
793
+ function reducerPlan(facts: ReadonlyMap<string, SourceFacts>, sliceSources: ReadonlyMap<string, SliceSource>, store: StoreFacts,
794
+ dependencies: (storePath: string, immer?: boolean) => Finding | undefined, scope: (path: string) => boolean,
795
+ renderer: (storePath: string) => string | undefined, selectsOnEachRead: (storePath: string) => boolean): Plan {
796
+ const findings: Finding[] = [];
797
+ const block = (reason: string, detail: string) => findings.push({reason, detail});
798
+ const hook = REDUCER_STORE_HOOK;
799
+ // A legacy `createStore` source has no slice source, so its own declarations and imports count too
800
+ const source = facts.get(store.path);
801
+ const names = new Set<string>([...sliceSources.get(store.path)?.names ?? [], ...source?.declared ?? [], ...source?.bindings.map(b => b.local) ?? []]);
802
+ const reducer = ["rootReducer", "appReducer", "storeReducer"].find(name => !names.has(name)) ?? "rootReducer";
803
+ if (!store.exportedAs) block("STORE_NOT_MODULE_LEVEL", store.store);
804
+ if (store.usedInSource) block("STORE_USE", `\`${store.store}\` is used in its own source`);
805
+ const dependency = dependencies(store.path, false);
806
+ if (dependency) findings.push(dependency);
807
+ for (const name of [hook, reducer, "create"]) if (names.has(name)) block("NAME_TAKEN", `${name} in ${store.path}`);
808
+ const storeSource = facts.get(store.path);
809
+ // RTK's `combineReducers` combines the reducers, as `configureStore` does, under its own name
810
+ const rtkCombine = storeSource?.bindings.some(b => b.local === "combineReducers" && b.module === RTK && b.name === "combineReducers");
811
+ if (store.reducerStore === "combined" && names.has("combineReducers") && !rtkCombine) block("NAME_TAKEN", `combineReducers in ${store.path}`);
812
+ const sources = new Set<string>([store.path]);
813
+ let connects = false;
814
+ let selects = false;
815
+ // Redux calls a store's listeners after every dispatch, which the store's `dispatch` does for its own `subscribe`
816
+ let subscribes = store.calledInSource?.has("subscribe") ?? false;
817
+ for (const source of facts.values()) {
818
+ const resolve = (module: string) => resolveRelative(source.path, module, facts);
819
+ if (!scope(source.path)) {
820
+ for (const binding of source.bindings) {
821
+ if (binding.module !== REACT_REDUX && resolve(binding.module) === store.path) block("STORE_USE", `${binding.local} in ${source.path}, of another package`);
822
+ }
823
+ for (const {module, detail} of source.unfollowed) {
824
+ if (resolve(module) === store.path) block("UNFOLLOWED_IMPORT", `${detail} of ${module} in ${source.path}, of another package`);
825
+ }
826
+ continue;
827
+ }
828
+ for (const {module, detail} of source.unfollowed) {
829
+ if (module === REACT_REDUX || resolve(module) === store.path) block("UNFOLLOWED_IMPORT", `${detail} of ${module} in ${source.path}`);
830
+ }
831
+ let changes = false;
832
+ for (const use of source.uses) {
833
+ const binding = source.bindings.find(b => b.local === use.local);
834
+ // A dispatcher stays the store's `dispatch`, whatever it is used for, and the slices stay as they are
835
+ if (!binding) continue;
836
+ const where = `${use.local} in ${source.path}`;
837
+ if (binding.module === REACT_REDUX) {
838
+ changes = true;
839
+ if (use.kind === "connect") connects = true;
840
+ if (use.kind === "other" && use.selector && readSelector(source, use.selector, facts)) continue;
841
+ // Any other selector runs as it is on the whole store, through a hook that keeps its selection where the store's own doesn't
842
+ if (use.kind === "other" && use.anySelector) {
843
+ if (selectsOnEachRead(store.path)) selects = true;
844
+ continue;
845
+ }
846
+ if (use.kind === "other") block(use.reason ?? "REACT_REDUX_USE", `${where}: ${use.detail}`);
847
+ continue;
848
+ }
849
+ const path = resolve(binding.module);
850
+ // What else the store's source exports stays there
851
+ if (path !== store.path || binding.name !== store.exportedAs) continue;
852
+ if (use.kind === "provider") changes = true;
853
+ else if (use.kind === "other" && use.member === "subscribe") subscribes = true;
854
+ else if (use.kind === "other" && use.member !== "getState" && use.member !== "dispatch") block(use.reason === "DISPATCH" ? "STORE_USE" : use.reason ?? "STORE_USE", `${where}: ${use.detail}`);
855
+ }
856
+ if (changes && source.path !== store.path) {
857
+ if (source.typescript) block("TYPESCRIPT", source.path);
858
+ if (source.bindings.some(b => b.local === hook) || source.declared.has(hook)) block("NAME_TAKEN", `${hook} in ${source.path}`);
859
+ sources.add(source.path);
860
+ }
861
+ }
862
+ if (/\.(?:ts|tsx|mts|cts)$/.test(store.path)) block("TYPESCRIPT", store.path);
863
+ // The store's source declares `connect`, with what it imports to render and to batch the store's updates
864
+ const module = connects ? renderer(store.path) : undefined;
865
+ if (connects && !module) block("REACT_REDUX_USE", `connect in a package that declares neither react-dom nor react-native`);
866
+ if (connects && storeSource) {
867
+ const helpers: [string, string][] = [["connect", ""], ...["createElement", "forwardRef", "memo", "useRef"].map(name => [name, "react"] as [string, string]),
868
+ ["unstable_batchedUpdates", module ?? ""]];
869
+ for (const [name, from] of helpers) {
870
+ const bound = storeSource.bindings.find(b => b.local === name);
871
+ if (storeSource.declared.has(name) || bound && (bound.module !== from || bound.name !== name)) block("NAME_TAKEN", `${name} in ${store.path}`);
872
+ }
873
+ }
874
+ if (selects && storeSource) {
875
+ for (const name of [SELECTOR_HOOK, "useRef", "useSyncExternalStore"]) {
876
+ const bound = storeSource.bindings.find(b => b.local === name);
877
+ if (storeSource.declared.has(name) || bound && (bound.module !== (name === SELECTOR_HOOK ? "" : "react") || bound.name !== name)) block("NAME_TAKEN", `${name} in ${store.path}`);
878
+ }
879
+ for (const path of sources) {
880
+ const source = facts.get(path);
881
+ if (source && path !== store.path && (source.declared.has(SELECTOR_HOOK) || source.bindings.some(b => b.local === SELECTOR_HOOK))) block("NAME_TAKEN", `${SELECTOR_HOOK} in ${path}`);
882
+ }
883
+ }
884
+ if (subscribes && names.has(STORE_LISTENERS)) block("NAME_TAKEN", `${STORE_LISTENERS} in ${store.path}`);
885
+ const result: Plan = {slices: new Map(), sources: new Set(), blocked: new Map()};
886
+ if (findings.length > 0) {
887
+ result.blocked.set(store, dedupe(findings));
888
+ return result;
889
+ }
890
+ return {...result, store, sources, reducerStore: {hook, reducer, ...module ? {renderer: module} : {}, ...selects ? {selectorHook: SELECTOR_HOOK} : {},
891
+ ...subscribes ? {listeners: STORE_LISTENERS} : {}}};
892
+ }
893
+
894
+ /**
895
+ * Whether `name`, which `source` passes to `useSelector`, is a plain read of the state: a `const` of its own, or one it
896
+ * imports by the name a followed module exports it as.
897
+ */
898
+ export function readSelector(source: SourceFacts, name: string, facts: ReadonlyMap<string, SourceFacts>): boolean {
899
+ const binding = source.bindings.find(b => b.local === name);
900
+ if (!binding) return source.readSelectors.local.has(name);
901
+ const path = resolveRelative(source.path, binding.module, facts);
902
+ return path !== undefined && (facts.get(path)?.readSelectors.exported.has(binding.name) ?? false);
903
+ }
904
+
652
905
  /**
653
906
  * A plan for each package that creates a store, by `packageOf`, the root of the package a source is in. A package's
654
907
  * one store converts with its own sources; what another package imports of it keeps it in Redux.
655
908
  */
656
909
  export function planPackages(facts: ReadonlyMap<string, SourceFacts>, sliceSources: ReadonlyMap<string, SliceSource>,
657
- packageOf: (path: string) => string | undefined, dependencies: (storePath: string) => Finding | undefined): Plan[] {
910
+ packageOf: (path: string) => string | undefined, dependencies: (storePath: string, immer?: boolean) => Finding | undefined,
911
+ wholeStores = true, renderer?: (storePath: string) => string | undefined,
912
+ selectsOnEachRead?: (storePath: string) => boolean): Plan[] {
658
913
  const root = (path: string) => packageOf(path) ?? "";
659
914
  const roots = new Set([...facts.values()].filter(source => source.stores.length > 0).map(source => root(source.path)));
660
- return [...roots].map(packageRoot => plan(facts, sliceSources, dependencies, path => root(path) === packageRoot));
915
+ return [...roots].map(packageRoot => plan(facts, sliceSources, dependencies, path => root(path) === packageRoot, wholeStores, renderer, selectsOnEachRead));
661
916
  }
662
917
 
663
918
  function dedupe(findings: Finding[]): Finding[] {