@storesjs/stores 0.8.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 (92) hide show
  1. package/LICENSE +21 -0
  2. package/dist/config.d.ts +13 -0
  3. package/dist/createBaseStore.d.ts +35 -0
  4. package/dist/createDerivedStore.d.ts +70 -0
  5. package/dist/createQueryStore.d.ts +131 -0
  6. package/dist/createVirtualStore.d.ts +39 -0
  7. package/dist/derivedStore/deriveProxy.d.ts +24 -0
  8. package/dist/derivedStore/globalDeriveScheduler.d.ts +22 -0
  9. package/dist/env.d.ts +7 -0
  10. package/dist/env.native.d.ts +8 -0
  11. package/dist/env.web.d.ts +7 -0
  12. package/dist/hooks/compareHooks.d.ts +49 -0
  13. package/dist/hooks/useLazyRef.d.ts +12 -0
  14. package/dist/hooks/useListen.d.ts +97 -0
  15. package/dist/hooks/useStableValue.d.ts +15 -0
  16. package/dist/index.d.ts +16 -0
  17. package/dist/logger.d.ts +16 -0
  18. package/dist/middleware/createHydrationGate.d.ts +19 -0
  19. package/dist/middleware/createSubscriptionManager.d.ts +10 -0
  20. package/dist/native/index.js +1 -0
  21. package/dist/native/index.mjs +1 -0
  22. package/dist/plugins/chrome/chromeExtensionSyncEngine.d.ts +31 -0
  23. package/dist/plugins/chrome/chromeStorageAdapter.d.ts +32 -0
  24. package/dist/plugins/chrome/createSyncedChromeStorage.d.ts +16 -0
  25. package/dist/plugins/chrome/index.d.ts +3 -0
  26. package/dist/plugins/chrome/utils.d.ts +1 -0
  27. package/dist/plugins/delta/deltaInstrumentation.d.ts +42 -0
  28. package/dist/plugins/delta/index.d.ts +1 -0
  29. package/dist/plugins/delta/recordDelta.d.ts +14 -0
  30. package/dist/plugins/network/index.d.ts +2 -0
  31. package/dist/plugins/router/RouteErrorBoundary.d.ts +19 -0
  32. package/dist/plugins/router/__tests__/router-types.test.d.ts +0 -0
  33. package/dist/plugins/router/constants.d.ts +38 -0
  34. package/dist/plugins/router/createRouter-old-version.d.ts +183 -0
  35. package/dist/plugins/router/createRouter.d.ts +183 -0
  36. package/dist/plugins/router/errorBoundary.d.ts +23 -0
  37. package/dist/plugins/router/index.d.ts +6 -0
  38. package/dist/plugins/router/lazy.d.ts +14 -0
  39. package/dist/plugins/router/locationStore.d.ts +24 -0
  40. package/dist/plugins/router/pathMatching.d.ts +28 -0
  41. package/dist/plugins/router/scrollRestoration.d.ts +8 -0
  42. package/dist/plugins/router/searchParams.d.ts +53 -0
  43. package/dist/plugins/router/test-link-params.d.ts +1 -0
  44. package/dist/plugins/router/test-prefetch.d.ts +17 -0
  45. package/dist/plugins/router/test-types.d.ts +1 -0
  46. package/dist/plugins/router/types.d.ts +11 -0
  47. package/dist/plugins/router/utils.d.ts +14 -0
  48. package/dist/plugins/router/vite.d.ts +5 -0
  49. package/dist/presence/heartbeat.d.ts +23 -0
  50. package/dist/presence/presenceChannel.d.ts +19 -0
  51. package/dist/presence/pruning.d.ts +34 -0
  52. package/dist/queryStore/classes/SubscriptionManager.d.ts +66 -0
  53. package/dist/queryStore/createParamManager.d.ts +27 -0
  54. package/dist/queryStore/types.d.ts +396 -0
  55. package/dist/signal.d.ts +19 -0
  56. package/dist/storage/storageCreators.d.ts +21 -0
  57. package/dist/storage/storageTypes.d.ts +12 -0
  58. package/dist/storesStorage.d.ts +2 -0
  59. package/dist/storesStorage.native.d.ts +2 -0
  60. package/dist/storesStorage.web.d.ts +2 -0
  61. package/dist/sync/browserSyncEngine.d.ts +2 -0
  62. package/dist/sync/networkSyncEngine.d.ts +137 -0
  63. package/dist/sync/noopSyncEngine.d.ts +2 -0
  64. package/dist/sync/syncEnhancer.d.ts +21 -0
  65. package/dist/sync/syncUtils.d.ts +5 -0
  66. package/dist/sync/transport.d.ts +112 -0
  67. package/dist/sync/types.d.ts +189 -0
  68. package/dist/tsconfig.tsbuildinfo +1 -0
  69. package/dist/types/functions.d.ts +6 -0
  70. package/dist/types/objects.d.ts +3 -0
  71. package/dist/types/utils.d.ts +8 -0
  72. package/dist/types.d.ts +332 -0
  73. package/dist/utils/core.d.ts +6 -0
  74. package/dist/utils/createAsyncMicrotaskScheduler.d.ts +34 -0
  75. package/dist/utils/createMicrotaskScheduler.d.ts +27 -0
  76. package/dist/utils/createStoreActions.d.ts +24 -0
  77. package/dist/utils/debounce.d.ts +21 -0
  78. package/dist/utils/equality.d.ts +37 -0
  79. package/dist/utils/factoryUtils.d.ts +21 -0
  80. package/dist/utils/hydrationCoordinator.d.ts +12 -0
  81. package/dist/utils/persistUtils.d.ts +8 -0
  82. package/dist/utils/promiseUtils.d.ts +1 -0
  83. package/dist/utils/serialization.d.ts +13 -0
  84. package/dist/utils/storeUtils.d.ts +56 -0
  85. package/dist/utils/stringUtils.d.ts +6 -0
  86. package/dist/utils/time.d.ts +46 -0
  87. package/dist/web/chrome.js +1 -0
  88. package/dist/web/chrome.mjs +1 -0
  89. package/dist/web/chunk-YWUZUTPH.mjs +1 -0
  90. package/dist/web/index.js +1 -0
  91. package/dist/web/index.mjs +1 -0
  92. package/package.json +75 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Christian Baroni
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,13 @@
1
+ import { StoresLogger } from './logger';
2
+ import { SyncEngine } from './sync/types';
3
+ import { AsyncStorageInterface, SyncStorageInterface } from './types';
4
+ export type StoresConfig = {
5
+ logger: StoresLogger;
6
+ storage: AsyncStorageInterface | SyncStorageInterface;
7
+ syncEngine: SyncEngine;
8
+ };
9
+ type ConfigWithoutLogger = Omit<StoresConfig, 'logger'>;
10
+ export declare function configureStores(update: Partial<StoresConfig>): void;
11
+ export declare function getStoresConfig(): ConfigWithoutLogger;
12
+ export declare function markStoreCreated(): void;
13
+ export {};
@@ -0,0 +1,35 @@
1
+ import { BaseStoreOptions, OptionallyPersistedStore, Store, StateCreator } from './types';
2
+ /**
3
+ * Creates a base store without persistence.
4
+ * @param createState - The state creator function for the base store.
5
+ * @returns A Zustand store with the specified state.
6
+ */
7
+ export declare function createBaseStore<S>(createState: StateCreator<S>): Store<S>;
8
+ /**
9
+ * Creates a base store with persistence.
10
+ * @param createState - The state creator function for the base store.
11
+ * @param options - The configuration options for persistence and sync.
12
+ * @returns A Zustand store with the specified state and persistence.
13
+ */
14
+ export declare function createBaseStore<S, PersistedState extends Partial<S> = Partial<S>, PersistReturn extends void = void>(createState: StateCreator<S>, options: BaseStoreOptions<S, PersistedState, PersistReturn>): Store<S, PersistedState, false, PersistReturn>;
15
+ /**
16
+ * Creates a base store with async persistence.
17
+ * @param createState - The state creator function for the base store.
18
+ * @param options - The configuration options for persistence and sync.
19
+ * @returns A Zustand store with the specified state and persistence.
20
+ */
21
+ export declare function createBaseStore<S, PersistedState extends Partial<S> = Partial<S>, PersistReturn extends Promise<void> = Promise<void>>(createState: StateCreator<S>, options: BaseStoreOptions<S, PersistedState, PersistReturn>): Store<S, PersistedState, false, PersistReturn>;
22
+ /**
23
+ * Creates a base store with optional persistence.
24
+ * @param createState - The state creator function for the base store.
25
+ * @param options - The configuration options for persistence and sync.
26
+ * @returns A Zustand store with the specified state and optional persistence.
27
+ */
28
+ export declare function createBaseStore<S, PersistedState extends Partial<S> = Partial<S>, PersistReturn extends void = void>(createState: StateCreator<S>, options?: BaseStoreOptions<S, PersistedState, PersistReturn>): OptionallyPersistedStore<S, PersistedState, PersistReturn>;
29
+ /**
30
+ * Creates a base store with optional async persistence.
31
+ * @param createState - The state creator function for the base store.
32
+ * @param options - The configuration options for persistence and sync.
33
+ * @returns A Zustand store with the specified state and optional persistence.
34
+ */
35
+ export declare function createBaseStore<S, PersistedState extends Partial<S> = Partial<S>, PersistReturn extends Promise<void> = Promise<void>>(createState: StateCreator<S>, options?: BaseStoreOptions<S, PersistedState, PersistReturn>): OptionallyPersistedStore<S, PersistedState, PersistReturn>;
@@ -0,0 +1,70 @@
1
+ import { DeriveOptions, DerivedStore, EqualityFn, Store, Selector, InferStoreState } from './types';
2
+ /**
3
+ * ### `createDerivedStore`
4
+ *
5
+ * Creates a **read-only** store derived from one or more underlying Zustand stores.
6
+ *
7
+ * ---
8
+ * The `deriveFunction` is called whenever its dependencies change, producing a new derived state.
9
+ * Dependencies are automatically tracked through a special `$` helper, which supports:
10
+ *
11
+ * 1) **Selector-based** usage:
12
+ * ```ts
13
+ * $ => {
14
+ * const user = $(useUserStore, s => s.user, shallowEqual);
15
+ * const theme = $(useSettingsStore, s => s.appearance.theme);
16
+ * return { user, theme, isAdmin: user?.roles.includes('admin') };
17
+ * }
18
+ * ```
19
+ *
20
+ * 2) **Proxy-based** usage (auto-built selectors for nested properties):
21
+ * ```ts
22
+ * $ => {
23
+ * const { user } = $(useUserStore); // Subscribe to `user`
24
+ * const theme = $(useSettingsStore).appearance.theme; // Subscribe to `theme`
25
+ * return { isAdmin: user?.roles.includes('admin'), theme, user };
26
+ * }
27
+ * ```
28
+ *
29
+ * ---
30
+ * Derived stores automatically unsubscribe from all dependencies when no consumers remain, and
31
+ * resubscribe when new consumers appear. The returned function doubles as:
32
+ *
33
+ * - A **React hook** (`const state = useDerivedStore(selector, equalityFn?)`)
34
+ * - A **store object** with `getState()`, `subscribe()`, and `destroy()`
35
+ *
36
+ * ---
37
+ * You can optionally pass a second parameter (either an equality function or a config object)
38
+ * to enable debouncing, customize the equality function, or set `lockDependencies: true`.
39
+ *
40
+ * (When dependencies are locked, subscriptions created via `$` are established once and are
41
+ * not rebuilt on subsequent re-derives, which can be a performance win for certain workloads.)
42
+ *
43
+ * ---
44
+ * @example
45
+ * ```ts
46
+ * // Create a derived store
47
+ * const useSearchResults = createDerivedStore($ => {
48
+ * const query = $(useSearchStore).query.trim().toLowerCase();
49
+ * const items = $(useItemsStore).items;
50
+ * return findResults(query, items);
51
+ * }, shallowEqual);
52
+ *
53
+ * function SearchResults() {
54
+ * // Consume the derived state
55
+ * const results = useSearchResults(); // Or (selector, equalityFn?)
56
+ * return <ResultsList items={results} />;
57
+ * }
58
+ * ```
59
+ *
60
+ * ---
61
+ * @param deriveFunction - Function that reads from other stores via `$` to produce derived state.
62
+ * @param optionsOrEqualityFn - Either an equality function or a config object (see `DeriveOptions`).
63
+ *
64
+ * @returns A read-only derived store (usable as a hook or standard store object).
65
+ */
66
+ export declare function createDerivedStore<Derived>(deriveFunction: ($: DeriveGetter) => Derived, optionsOrEqualityFn?: DeriveOptions<Derived>): DerivedStore<Derived>;
67
+ export type DeriveGetter = {
68
+ <S extends Store<unknown>>(store: S): InferStoreState<S>;
69
+ <S extends Store<unknown>, Selected>(store: S, selector: Selector<InferStoreState<S>, Selected>, equalityFn?: EqualityFn<Selected>): Selected;
70
+ };
@@ -0,0 +1,131 @@
1
+ import { QueryStoreConfig, QueryStoreState } from './queryStore/types';
2
+ import { BaseStoreOptions, OptionallyPersistedStore, PersistedStore, StateCreator, Store } from './types';
3
+ /**
4
+ * Creates a persisted, query-enabled store with data fetching capabilities (sync storage).
5
+ *
6
+ * @template TQueryFnData - The raw data type returned by the fetcher
7
+ * @template TParams - Parameters passed to the fetcher function
8
+ * @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
9
+ * @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
10
+ */
11
+ export declare function createQueryStore<TQueryFnData, TParams extends Record<string, unknown> = Record<string, never>, TData = TQueryFnData, PersistedState extends Partial<QueryStoreState<TData, TParams>> = Partial<QueryStoreState<TData, TParams>>, PersistReturn extends void = void>(config: QueryStoreConfig<TQueryFnData, TParams, TData>, options: BaseStoreOptions<QueryStoreState<TData, TParams>, PersistedState, PersistReturn>): PersistedStore<QueryStoreState<TData, TParams>, PersistedState, false, PersistReturn>;
12
+ /**
13
+ * Creates a persisted, query-enabled store with data fetching capabilities (async storage).
14
+ *
15
+ * @template TQueryFnData - The raw data type returned by the fetcher
16
+ * @template TParams - Parameters passed to the fetcher function
17
+ * @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
18
+ * @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
19
+ */
20
+ export declare function createQueryStore<TQueryFnData, TParams extends Record<string, unknown> = Record<string, never>, TData = TQueryFnData, PersistedState extends Partial<QueryStoreState<TData, TParams>> = Partial<QueryStoreState<TData, TParams>>, PersistReturn extends Promise<void> = Promise<void>>(config: QueryStoreConfig<TQueryFnData, TParams, TData>, options: BaseStoreOptions<QueryStoreState<TData, TParams>, PersistedState, PersistReturn>): PersistedStore<QueryStoreState<TData, TParams>, PersistedState, false, PersistReturn>;
21
+ /**
22
+ * Creates a persisted, query-enabled store with data fetching capabilities (sync storage).
23
+ *
24
+ * @template TQueryFnData - The raw data type returned by the fetcher
25
+ * @template TParams - Parameters passed to the fetcher function
26
+ * @template CustomState - User-defined custom store state
27
+ * @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
28
+ * @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
29
+ */
30
+ export declare function createQueryStore<TQueryFnData, TParams extends Record<string, unknown> = Record<string, never>, CustomState = unknown, TData = TQueryFnData, PersistedState extends Partial<QueryStoreState<TData, TParams, CustomState>> = Partial<QueryStoreState<TData, TParams, CustomState>>, PersistReturn extends void = void>(config: QueryStoreConfig<TQueryFnData, TParams, TData, CustomState>, stateCreator: StateCreator<QueryStoreState<TData, TParams, CustomState>, CustomState>, options: BaseStoreOptions<QueryStoreState<TData, TParams, CustomState>, PersistedState, PersistReturn>): PersistedStore<QueryStoreState<TData, TParams, CustomState>, PersistedState, false, PersistReturn>;
31
+ /**
32
+ * Creates a persisted, query-enabled store with data fetching capabilities (async storage).
33
+ *
34
+ * @template TQueryFnData - The raw data type returned by the fetcher
35
+ * @template TParams - Parameters passed to the fetcher function
36
+ * @template CustomState - User-defined custom store state
37
+ * @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
38
+ * @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
39
+ */
40
+ export declare function createQueryStore<TQueryFnData, TParams extends Record<string, unknown> = Record<string, never>, CustomState = unknown, TData = TQueryFnData, PersistedState extends Partial<QueryStoreState<TData, TParams, CustomState>> = Partial<QueryStoreState<TData, TParams, CustomState>>, PersistReturn extends Promise<void> = Promise<void>>(config: QueryStoreConfig<TQueryFnData, TParams, TData, CustomState>, stateCreator: StateCreator<QueryStoreState<TData, TParams, CustomState>, CustomState>, options: BaseStoreOptions<QueryStoreState<TData, TParams, CustomState>, PersistedState, PersistReturn>): PersistedStore<QueryStoreState<TData, TParams, CustomState>, PersistedState, false, PersistReturn>;
41
+ /**
42
+ * Creates a query-enabled store with data fetching capabilities.
43
+ *
44
+ * @template TQueryFnData - The raw data type returned by the fetcher
45
+ * @template TParams - Parameters passed to the fetcher function
46
+ * @template CustomState - User-defined custom store state
47
+ * @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
48
+ */
49
+ export declare function createQueryStore<TQueryFnData, TParams extends Record<string, unknown> = Record<string, never>, CustomState = unknown, TData = TQueryFnData>(config: QueryStoreConfig<TQueryFnData, TParams, TData, CustomState>, stateCreator: StateCreator<QueryStoreState<TData, TParams, CustomState>, CustomState>, options?: BaseStoreOptions<QueryStoreState<TData, TParams, CustomState>>): Store<QueryStoreState<TData, TParams, CustomState>>;
50
+ /**
51
+ * Creates a query-enabled store with data fetching capabilities.
52
+ *
53
+ * @template TQueryFnData - The raw data type returned by the fetcher
54
+ * @template TParams - Parameters passed to the fetcher function
55
+ * @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
56
+ */
57
+ export declare function createQueryStore<TQueryFnData, TParams extends Record<string, unknown> = Record<string, never>, TData = TQueryFnData>(config: QueryStoreConfig<TQueryFnData, TParams, TData>, options?: BaseStoreOptions<QueryStoreState<TData, TParams>>): Store<QueryStoreState<TData, TParams>>;
58
+ /**
59
+ * Creates a conditionally persisted, query-enabled store with data-fetching capabilities
60
+ * and custom state (sync storage).
61
+ *
62
+ * `options.persist` may be `undefined` – the returned store exposes `persist?`.
63
+ *
64
+ * @template TQueryFnData - The raw data type returned by the fetcher
65
+ * @template TParams - Parameters passed to the fetcher function
66
+ * @template CustomState - User-defined custom store state
67
+ * @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
68
+ * @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
69
+ */
70
+ export declare function createQueryStore<TQueryFnData, TParams extends Record<string, unknown> = Record<string, never>, CustomState = unknown, TData = TQueryFnData, PersistedState extends Partial<QueryStoreState<TData, TParams, CustomState>> = Partial<QueryStoreState<TData, TParams, CustomState>>, PersistReturn extends void = void>(config: QueryStoreConfig<TQueryFnData, TParams, TData, CustomState>, stateCreator: StateCreator<QueryStoreState<TData, TParams, CustomState>, CustomState>, options?: BaseStoreOptions<QueryStoreState<TData, TParams, CustomState>, PersistedState, PersistReturn>): OptionallyPersistedStore<QueryStoreState<TData, TParams, CustomState>, PersistedState, PersistReturn>;
71
+ /**
72
+ * Creates a conditionally persisted, query-enabled store with data-fetching capabilities
73
+ * and custom state (async storage).
74
+ *
75
+ * `options.persist` may be `undefined` – the returned store exposes `persist?`.
76
+ *
77
+ * @template TQueryFnData - The raw data type returned by the fetcher
78
+ * @template TParams - Parameters passed to the fetcher function
79
+ * @template CustomState - User-defined custom store state
80
+ * @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
81
+ * @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
82
+ */
83
+ export declare function createQueryStore<TQueryFnData, TParams extends Record<string, unknown> = Record<string, never>, CustomState = unknown, TData = TQueryFnData, PersistedState extends Partial<QueryStoreState<TData, TParams, CustomState>> = Partial<QueryStoreState<TData, TParams, CustomState>>, PersistReturn extends Promise<void> = Promise<void>>(config: QueryStoreConfig<TQueryFnData, TParams, TData, CustomState>, stateCreator: StateCreator<QueryStoreState<TData, TParams, CustomState>, CustomState>, options?: BaseStoreOptions<QueryStoreState<TData, TParams, CustomState>, PersistedState, PersistReturn>): OptionallyPersistedStore<QueryStoreState<TData, TParams, CustomState>, PersistedState, PersistReturn>;
84
+ /**
85
+ * Creates a conditionally persisted, query-enabled store with data fetching capabilities (sync storage).
86
+ *
87
+ * `options.persist` may be `undefined` – the returned store exposes `persist?`.
88
+ *
89
+ * @template TQueryFnData - The raw data type returned by the fetcher
90
+ * @template TParams - Parameters passed to the fetcher function
91
+ * @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
92
+ * @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
93
+ */
94
+ export declare function createQueryStore<TQueryFnData, TParams extends Record<string, unknown> = Record<string, never>, TData = TQueryFnData, PersistedState extends Partial<QueryStoreState<TData, TParams>> = Partial<QueryStoreState<TData, TParams>>, PersistReturn extends void = void>(config: QueryStoreConfig<TQueryFnData, TParams, TData, QueryStoreState<TData, TParams>>, options: BaseStoreOptions<QueryStoreState<TData, TParams>, PersistedState, PersistReturn> | undefined): OptionallyPersistedStore<QueryStoreState<TData, TParams>, PersistedState, PersistReturn>;
95
+ /**
96
+ * Creates a conditionally persisted, query-enabled store with data fetching capabilities (async storage).
97
+ *
98
+ * `options.persist` may be `undefined` – the returned store exposes `persist?`.
99
+ *
100
+ * @template TQueryFnData - The raw data type returned by the fetcher
101
+ * @template TParams - Parameters passed to the fetcher function
102
+ * @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
103
+ * @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
104
+ */
105
+ export declare function createQueryStore<TQueryFnData, TParams extends Record<string, unknown> = Record<string, never>, TData = TQueryFnData, PersistedState extends Partial<QueryStoreState<TData, TParams>> = Partial<QueryStoreState<TData, TParams>>, PersistReturn extends Promise<void> = Promise<void>>(config: QueryStoreConfig<TQueryFnData, TParams, TData, QueryStoreState<TData, TParams>>, options: BaseStoreOptions<QueryStoreState<TData, TParams>, PersistedState, PersistReturn> | undefined): OptionallyPersistedStore<QueryStoreState<TData, TParams>, PersistedState, PersistReturn>;
106
+ /**
107
+ * The default query store `retryDelay` function.
108
+ *
109
+ * Exponential backoff starting at `baseDelay` (5s default), doubling each retry, capped at `maxDelay` (5m default).
110
+ *
111
+ * ```ts
112
+ * retryCount => Math.min(baseDelay * Math.pow(2, retryCount), maxDelay)
113
+ * ```
114
+ */
115
+ export declare function defaultRetryDelay(retryCount: number, options?: {
116
+ baseDelay?: number;
117
+ maxDelay?: number;
118
+ }): number;
119
+ /**
120
+ * @deprecated Use `getQueryKey` instead, unless using for non-parsable query keys.
121
+ */
122
+ export declare function getLegacyQueryKey<TParams extends Record<string, unknown>>(params: TParams): string;
123
+ /**
124
+ * Generates a deterministic query store `queryKey` from the given parameters,
125
+ * consistent with internally generated keys.
126
+ */
127
+ export declare function getQueryKey<TParams extends Record<string, unknown>>(params: TParams): string;
128
+ /**
129
+ * Parses a query store `queryKey` into the corresponding parameters.
130
+ */
131
+ export declare function parseQueryKey<TParams extends Record<string, unknown>>(queryKey: string): TParams;
@@ -0,0 +1,39 @@
1
+ import { DeriveGetter } from './createDerivedStore';
2
+ import { BaseStore, InferPersistedState, InferSetStateReturn, InferStoreState, OptionallyPersistedStore } from './types';
3
+ type MethodOverrides<Store extends BaseStore<State>, State = InferStoreState<Store>> = Partial<Pick<Store, 'getState' | 'setState'>>;
4
+ type VirtualStoreOptions = {
5
+ debugMode?: boolean;
6
+ /**
7
+ * Whether to lock dependencies (see: {@link DeriveOptions}) for the virtual store.
8
+ * @default true
9
+ */
10
+ lockDependencies?: boolean;
11
+ };
12
+ /**
13
+ * ### `createVirtualStore`
14
+ *
15
+ * Returns a stable store interface backed by different store instances over time.
16
+ * When dependencies change, the derive function runs and creates a new store, then
17
+ * all subscriptions rebind automatically. Only depend on state that should trigger
18
+ * new store creation.
19
+ *
20
+ * ---
21
+ * 💡 **Note:** `lockDependencies` (see: {@link DeriveOptions}) is enabled by default.
22
+ * Ensure that any `$` dependencies in your `createStore` function are called
23
+ * consistently. If they are not, set `lockDependencies` to `false`.
24
+ *
25
+ * ---
26
+ * @param createStore - Derive function that returns a store instance
27
+ * @param overrides - Optional method overrides (e.g., `getState(id?: string)`)
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * const useUserAssetsStore = createVirtualStore($ => {
32
+ * const address = $(useWalletsStore).accountAddress;
33
+ * return createUserAssetsStore(address);
34
+ * });
35
+ * ```
36
+ */
37
+ export declare function createVirtualStore<Store extends BaseStore<InferStoreState<Store>>>(createStore: ($: DeriveGetter) => Store, options?: VirtualStoreOptions): OptionallyPersistedStore<InferStoreState<Store>, InferPersistedState<Store, InferStoreState<Store>>, InferSetStateReturn<Store>>;
38
+ export declare function createVirtualStore<Store extends BaseStore<InferStoreState<Store>>, Overrides extends MethodOverrides<Store>>(createStore: ($: DeriveGetter) => Store, overrides: (getStore: () => Store) => Overrides, options?: VirtualStoreOptions): OptionallyPersistedStore<InferStoreState<Store>, InferPersistedState<Store, InferStoreState<Store>>, InferSetStateReturn<Store>> & Overrides;
39
+ export {};
@@ -0,0 +1,24 @@
1
+ import { BaseStore, Selector } from '../types';
2
+ type TrackedInvocation = {
3
+ args: unknown[] | undefined;
4
+ method: string;
5
+ };
6
+ type TrackPathFn = (store: BaseStore<unknown>, path: string[], isLeaf: boolean, invocation?: TrackedInvocation) => void;
7
+ type SubscriptionBuilder = (store: BaseStore<unknown>, selector: Selector<unknown, unknown>) => void;
8
+ /**
9
+ * Gets or creates a lightweight tracking proxy that records path access and store
10
+ * method invocations via proxy traps. Used to auto-generate selectors that point
11
+ * to either the accessed path or the value returned by an invoked store method.
12
+ */
13
+ export declare function getOrCreateProxy<S>(store: BaseStore<S>, rootProxyCache: WeakMap<BaseStore<unknown>, unknown>, trackPath: TrackPathFn): S;
14
+ export type PathFinder = {
15
+ buildProxySubscriptions(createSubscription: SubscriptionBuilder, shouldLog: boolean): void;
16
+ trackPath: TrackPathFn;
17
+ };
18
+ /**
19
+ * A factory that returns a proxy path-tracking object with two methods:
20
+ * - `buildProxySubscriptions()`: builds subscriptions to the final paths
21
+ * - `trackPath()`: records usage of a store path
22
+ */
23
+ export declare function createPathFinder(): PathFinder;
24
+ export {};
@@ -0,0 +1,22 @@
1
+ type Rank = number;
2
+ type StoreId = string;
3
+ type Task = () => void;
4
+ export declare function isCascadeActive(): boolean;
5
+ /**
6
+ * Rank of the currently running derive batch, or null if not in a batch.
7
+ */
8
+ export declare function getCurrentDeriveRank(): Rank | null;
9
+ /**
10
+ * Arms the cascade and schedules a single microtask flush.
11
+ */
12
+ export declare function activateCascade(): void;
13
+ /**
14
+ * Enlist one per-store component flush (idempotent per store).
15
+ */
16
+ export declare function joinCascade(storeId: StoreId, task: Task): void;
17
+ /**
18
+ * Enqueue (or upgrade) a derive task with the given rank.
19
+ * If the task is already present, we keep the maximum rank (run later).
20
+ */
21
+ export declare function enqueueDerive(task: Task, rank: Rank): void;
22
+ export {};
package/dist/env.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export declare const IS_REACT_NATIVE = false;
2
+ export declare const IS_BROWSER: boolean;
3
+ export declare const IS_IOS = false;
4
+ export declare const IS_ANDROID = false;
5
+ export declare const IS_DEV: boolean;
6
+ export declare const IS_TEST: boolean;
7
+ export declare const unstable_batchedUpdates: <T>(callback: () => T) => T;
@@ -0,0 +1,8 @@
1
+ import { unstable_batchedUpdates } from 'react-native';
2
+ export declare const IS_REACT_NATIVE = true;
3
+ export declare const IS_BROWSER = false;
4
+ export declare const IS_IOS: boolean;
5
+ export declare const IS_ANDROID: boolean;
6
+ export declare const IS_DEV: boolean;
7
+ export declare const IS_TEST: boolean;
8
+ export { unstable_batchedUpdates };
@@ -0,0 +1,7 @@
1
+ export declare const IS_REACT_NATIVE = false;
2
+ export declare const IS_BROWSER: boolean;
3
+ export declare const IS_IOS = false;
4
+ export declare const IS_ANDROID = false;
5
+ export declare const IS_DEV: boolean;
6
+ export declare const IS_TEST: boolean;
7
+ export declare const unstable_batchedUpdates: <T>(callback: () => T) => T;
@@ -0,0 +1,49 @@
1
+ import { DependencyList, EffectCallback } from 'react';
2
+ type EqualityFn = <T>(a: T, b: T) => boolean;
3
+ /**
4
+ * A version of React's `useMemo` that uses deep comparison (or a custom comparator) for its dependencies.
5
+ *
6
+ * @param factory - Function that computes the memoized value.
7
+ * @param deps - Dependency list to compare.
8
+ * @param equalityFn - Custom function to compare dependencies. Defaults to deep equality.
9
+ * @returns The memoized value.
10
+ */
11
+ export declare function useDeepMemo<T>(factory: () => T, deps: DependencyList, equalityFn?: EqualityFn): T;
12
+ /**
13
+ * A version of React's `useEffect` that uses deep comparison (or a custom comparator) for its dependencies.
14
+ *
15
+ * @param effect - The effect callback.
16
+ * @param deps - Dependency list to compare.
17
+ * @param equalityFn - Custom function to compare dependencies. Defaults to deep equality.
18
+ */
19
+ export declare function useDeepEffect(effect: EffectCallback, deps: DependencyList, equalityFn?: EqualityFn): void;
20
+ /**
21
+ * A version of React's `useCallback` that uses deep comparison (or a custom comparator) for its dependencies.
22
+ *
23
+ * @param callback - The callback function to memoize.
24
+ * @param deps - Dependency list to compare.
25
+ * @param equalityFn - Custom function to compare dependencies. Defaults to deep equality.
26
+ * @returns A memoized callback.
27
+ */
28
+ export declare function useDeepCallback<T extends (...args: Parameters<T>) => ReturnType<T>>(callback: T, deps: DependencyList, equalityFn?: EqualityFn): T;
29
+ /**
30
+ * A version of React's `useLayoutEffect` that uses deep comparison (or a custom comparator) for its dependencies.
31
+ *
32
+ * @param effect - The effect callback.
33
+ * @param deps - Dependency list to compare.
34
+ * @param equalityFn - Custom function to compare dependencies. Defaults to deep equality.
35
+ */
36
+ export declare function useDeepLayoutEffect(effect: EffectCallback, deps: DependencyList, equalityFn?: EqualityFn): void;
37
+ /**
38
+ * A JS-side equivalent of Reanimated's `useAnimatedReaction` hook.
39
+ *
40
+ * Runs a "prepare" function to compute a value, and then runs a "react" function
41
+ * whenever the prepared value changes, providing both the current and previous prepared values.
42
+ *
43
+ * @param prepare - Function that computes the value to watch.
44
+ * @param react - Function that reacts to changes in the prepared value, receiving (current, previous).
45
+ * @param dependencies - Dependency array. Required for correct operation in React.
46
+ * @param equalityFn - Custom function to compare dependencies. Defaults to `Object.is`.
47
+ */
48
+ export declare function useCompareEffect<PreparedResult>(prepare: () => PreparedResult, react: (current: PreparedResult, previous: PreparedResult | null) => void, dependencies: DependencyList, equalityFn?: EqualityFn): void;
49
+ export {};
@@ -0,0 +1,12 @@
1
+ import { RefObject } from 'react';
2
+ /**
3
+ * ### `useLazyRef`
4
+ *
5
+ * A version of `useRef` that allows for lazy initialization.
6
+ *
7
+ * ---
8
+ * @param initializer A function that returns the initial value for the ref.
9
+ *
10
+ * @returns A stable, pre-initialized `RefObject<T>`.
11
+ */
12
+ export declare function useLazyRef<T>(initializer: () => T): RefObject<T>;
@@ -0,0 +1,97 @@
1
+ import { RefObject } from 'react';
2
+ import { BaseStore, EqualityFn, InferStoreState, Selector } from '../types';
3
+ /**
4
+ * Handle returned by `useListen`.
5
+ *
6
+ * The hook cleans itself up, so you normally ignore this handle.
7
+ * Keep it only when you need to pause or resume the listener manually
8
+ * (e.g. suspend heavy work while a long-lived component is off screen).
9
+ */
10
+ export type ListenHandle = {
11
+ /** `true` while the listener is attached. */
12
+ isActive: boolean;
13
+ /** Re-attach the listener. */
14
+ resubscribe: (options?: ResubscribeOptions) => void;
15
+ /** Detach the listener. Safe to call more than once. */
16
+ unsubscribe: () => void;
17
+ };
18
+ /**
19
+ * Options for resubscribing a listener.
20
+ */
21
+ export type ResubscribeOptions = {
22
+ /**
23
+ * Whether to fire the callback immediately when resubscribing.
24
+ * @default false
25
+ */
26
+ fireImmediately?: boolean;
27
+ /**
28
+ * Whether to force a resubscription even if the listener is already active.
29
+ * @default false
30
+ */
31
+ forceResubscribe?: boolean;
32
+ };
33
+ /**
34
+ * Options for the `useListen` hook.
35
+ */
36
+ export type UseListenOptions<Selected> = {
37
+ /**
38
+ * Whether to log debug messages to the console.
39
+ * @default false
40
+ */
41
+ debugMode?: boolean;
42
+ /**
43
+ * Whether to enable the listener.
44
+ * @default true
45
+ */
46
+ enabled?: boolean;
47
+ /**
48
+ * Dictates whether `react` should be called on state slice changes.
49
+ * Compares the previous and current selected values.
50
+ * @default Object.is
51
+ */
52
+ equalityFn?: EqualityFn<Selected>;
53
+ /**
54
+ * Whether to fire the callback immediately on mount. Note that if `true`,
55
+ * the `react` callback will be called on mount regardless of whether the
56
+ * selected value has changed.
57
+ * @default false
58
+ */
59
+ fireImmediately?: boolean;
60
+ };
61
+ /**
62
+ * ### `useListen`
63
+ *
64
+ * Subscribes to a slice of a Zustand store and runs a callback whenever that slice changes,
65
+ * **without triggering re-renders**.
66
+ *
67
+ * Useful for forwarding updates to non-React state (e.g. Reanimated shared values), scoped side
68
+ * effects, or deciding yourself if or when a render should happen.
69
+ *
70
+ * The hook attaches the listener and cleans it up automatically. Use the returned `ListenHandle`
71
+ * only when you need to pause or resume the listener manually.
72
+ *
73
+ * ---
74
+ * 💡 **Note:** With the exception of `enabled`, changes in `options` are **not reactive**.
75
+ * They take effect only if a resubscription occurs.
76
+ *
77
+ * ---
78
+ * @param store - Zustand store to listen to. Should be a stable reference.
79
+ * @param selector - Selects the slice of the store state to listen to.
80
+ * @param react - Triggered when the selected slice changes. Receives `(current, previous, unsubscribe)`.
81
+ * @param optionsOrEqualityFn - Optional `equalityFn`, `fireImmediately` settings, forwarded to `store.subscribe`.
82
+ *
83
+ * ---
84
+ * @example
85
+ * ```ts
86
+ * useListen(
87
+ * useCandlestickStore,
88
+ * state => state.getData(),
89
+ * (candles, previous, unsubscribe) => {
90
+ * if (candles?.unsupported) return unsubscribe();
91
+ * updateTokenPrice(token, getPriceUpdate(candles, previous));
92
+ * runOnUI(() => chartManager.value?.setCandles(candles))();
93
+ * }
94
+ * );
95
+ * ```
96
+ */
97
+ export declare function useListen<Store extends BaseStore<S>, Selected, S = InferStoreState<Store>>(store: Store, selector: Selector<S, Selected>, react: (current: Selected, previous: Selected, unsubscribe: () => void) => void, optionsOrEqualityFn?: UseListenOptions<Selected> | UseListenOptions<Selected>['equalityFn']): RefObject<Readonly<ListenHandle>>;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * **Initializes a value once**, guaranteeing stability across renders.
3
+ *
4
+ * @param initializer A function that produces the value. It is invoked **only
5
+ * on the first render** for a given component instance.
6
+ *
7
+ * @returns A stable `T` guaranteed to be the value initially returned by the
8
+ * provided `initializer`.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const initialState = useStableValue(() => getInitialState());
13
+ * ```
14
+ */
15
+ export declare function useStableValue<T>(init: () => T): T;
@@ -0,0 +1,16 @@
1
+ export { configureStores } from './config';
2
+ export { createBaseStore } from './createBaseStore';
3
+ export * from './createDerivedStore';
4
+ export * from './createQueryStore';
5
+ export * from './createVirtualStore';
6
+ export { replacer, reviver } from './utils/serialization';
7
+ export { applyStateUpdate, destroyStore, destroyStores, getStoreName, isDerivedStore, isPersistedStore, isQueryStore, isVirtualStore, } from './utils/storeUtils';
8
+ export * from './hooks/useListen';
9
+ export * from './hooks/useStableValue';
10
+ export * from './sync/types';
11
+ export * from './queryStore/types';
12
+ export * from './storage/storageTypes';
13
+ export * from './types';
14
+ export * from './utils/createStoreActions';
15
+ export { deepEqual, shallowEqual } from './utils/equality';
16
+ export { time } from './utils/time';
@@ -0,0 +1,16 @@
1
+ export declare class StoresError extends Error {
2
+ cause: Error;
3
+ constructor(message: string, error?: unknown);
4
+ }
5
+ export interface StoresLogger {
6
+ debug: (message: string, context?: Record<string, unknown>) => void;
7
+ error: {
8
+ <T extends Error>(error: T, context?: Record<string, unknown>): void;
9
+ <T extends string>(error: T, context?: Record<string, unknown>): void;
10
+ };
11
+ info: (message: string, context?: Record<string, unknown>) => void;
12
+ warn: (message: string, context?: Record<string, unknown>) => void;
13
+ }
14
+ export declare let logger: StoresLogger;
15
+ export declare function ensureError(error: unknown): Error;
16
+ export declare function setLogger(customLogger: StoresLogger): void;
@@ -0,0 +1,19 @@
1
+ import { StateCreator } from '../types';
2
+ import { SyncContext } from 'src/sync/syncEnhancer';
3
+ type WrappedOnRehydrateStorage<S> = (userCallback: ((state: S) => ((finalState?: S, error?: unknown) => void) | void) | undefined, syncContext: SyncContext | undefined) => (state: S) => (finalState?: S, error?: unknown) => void;
4
+ /**
5
+ * Creates hydration-gating middleware that queues state updates until rehydration completes.
6
+ *
7
+ * **Before hydration**: Queues all `set()` calls and flushes them sequentially after rehydration.
8
+ *
9
+ * **After hydration**: Passes `set()` calls through synchronously without batching.
10
+ *
11
+ * This ensures persistence sees a fully rehydrated base state before applying queued updates,
12
+ * while keeping in-memory state changes synchronous post-hydration.
13
+ */
14
+ export declare function createHydrationGate<S>(stateCreator: StateCreator<S>): {
15
+ hydrationPromise: () => Promise<void>;
16
+ stateCreator: StateCreator<S>;
17
+ wrapOnRehydrateStorage: WrappedOnRehydrateStorage<S>;
18
+ };
19
+ export {};
@@ -0,0 +1,10 @@
1
+ export type SubscriptionLifecycleHandlers = {
2
+ readonly onSubscribe?: (isFirstSubscription: boolean) => void;
3
+ readonly onLastUnsubscribe?: () => void;
4
+ };
5
+ export type SubscriptionManager = {
6
+ readonly getSubscriptionCount: () => number;
7
+ readonly setHandlers: (handlers: SubscriptionLifecycleHandlers | null) => void;
8
+ readonly subscribe: () => () => void;
9
+ };
10
+ export declare function createSubscriptionManager(): SubscriptionManager;