@storesjs/stores 0.10.0 → 0.12.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 +1583 -4
- package/dist/native/index.js +7 -1
- package/dist/native/index.mjs +7 -1
- package/dist/plugins/chrome/index.d.ts +186 -4
- package/dist/vanilla/index.js +1 -1
- package/dist/vanilla/index.mjs +1 -1
- package/dist/vanilla/index.vanilla.d.ts +1469 -1
- package/dist/web/chrome.js +1 -1
- package/dist/web/chrome.mjs +1 -1
- package/dist/web/index.js +1 -1
- package/dist/web/index.mjs +1 -1
- package/dist/web/internal/runtime.js +2 -1
- package/dist/web/internal/runtime.mjs +2 -1
- package/dist/web/queryParam-Ckp7Zi5t.mjs +1 -0
- package/dist/web/queryParam-Ctnhipnd.js +1 -0
- package/dist/web/serialization-BgaGfw_1.mjs +1 -0
- package/dist/web/serialization-Dau9pNHc.js +1 -0
- package/dist/web/utils-Ba1RIeAA.mjs +1 -0
- package/dist/web/utils-CwejruRb.js +1 -0
- package/package.json +7 -7
- package/dist/createBaseStore.d.ts +0 -36
- package/dist/createDerivedStore.d.ts +0 -63
- package/dist/createQueryStore.d.ts +0 -117
- package/dist/createVirtualStore.d.ts +0 -40
- package/dist/env.native.d.ts +0 -7
- package/dist/env.web.d.ts +0 -7
- package/dist/hooks/useLazyRef.d.ts +0 -13
- package/dist/hooks/useListen.d.ts +0 -98
- package/dist/hooks/useStableValue.d.ts +0 -16
- package/dist/hooks/useSyncExternalStoreWithSelector.d.ts +0 -5
- package/dist/index.shared.d.ts +0 -14
- package/dist/index.vanilla.d.ts +0 -2
- package/dist/internal/baseStore.d.ts +0 -2
- package/dist/internal/config.d.ts +0 -64
- package/dist/internal/createStoreActions.d.ts +0 -24
- package/dist/internal/derivedStore/cascadeScheduler.d.ts +0 -31
- package/dist/internal/derivedStore/deriveProxy.d.ts +0 -15
- package/dist/internal/derivedStore/pathFinder.d.ts +0 -26
- package/dist/internal/derivedStore.d.ts +0 -2
- package/dist/internal/errors.d.ts +0 -10
- package/dist/internal/logger.d.ts +0 -10
- package/dist/internal/middleware/createHydrationGate.d.ts +0 -20
- package/dist/internal/queryStore/queryStoreDefaults.d.ts +0 -8
- package/dist/internal/queryStore.d.ts +0 -2
- package/dist/internal/runtime.d.ts +0 -13
- package/dist/internal/signal.d.ts +0 -12
- package/dist/internal/storage/storageCreators.d.ts +0 -12
- package/dist/internal/storeUtils.d.ts +0 -46
- package/dist/internal/sync/browserSyncEngine.d.ts +0 -3
- package/dist/internal/sync/noopSyncEngine.d.ts +0 -3
- package/dist/internal/sync/syncEnhancer.d.ts +0 -26
- package/dist/internal/sync/syncUtils.d.ts +0 -6
- package/dist/internal/utils/persistUtils.d.ts +0 -9
- package/dist/internal/virtualStore.d.ts +0 -2
- package/dist/plugins/chrome/chromeExtensionSyncEngine.d.ts +0 -30
- package/dist/plugins/chrome/chromeStorageAdapter.d.ts +0 -31
- package/dist/plugins/chrome/createSyncedChromeStorage.d.ts +0 -14
- package/dist/queryStore/classes/SubscriptionManager.d.ts +0 -67
- package/dist/queryStore/queryKey.d.ts +0 -3
- package/dist/queryStore/signalTypes.d.ts +0 -14
- package/dist/queryStore/types.d.ts +0 -403
- package/dist/storage/storageTypes.d.ts +0 -13
- package/dist/store/attachStoreHook.react.d.ts +0 -5
- package/dist/store/attachStoreHook.vanilla.d.ts +0 -6
- package/dist/store/batchStoreNotifications.native.d.ts +0 -3
- package/dist/store/batchStoreNotifications.web.d.ts +0 -2
- package/dist/store/createStore.d.ts +0 -6
- package/dist/store/persist.d.ts +0 -14
- package/dist/store/stateUpdate.d.ts +0 -10
- package/dist/store/types.d.ts +0 -108
- package/dist/storesStorage.native.d.ts +0 -3
- package/dist/storesStorage.web.d.ts +0 -3
- package/dist/sync/types.d.ts +0 -115
- package/dist/types/functions.d.ts +0 -24
- package/dist/types/objects.d.ts +0 -11
- package/dist/types/setState.d.ts +0 -22
- package/dist/types/subscribe.d.ts +0 -28
- package/dist/types/useStoreCallSignatures.d.ts +0 -2
- package/dist/types/useStoreCallSignatures.react.d.ts +0 -6
- package/dist/types/useStoreCallSignatures.vanilla.d.ts +0 -2
- package/dist/types/utils.d.ts +0 -13
- package/dist/types.d.ts +0 -286
- package/dist/utils/core.d.ts +0 -26
- package/dist/utils/createAsyncMicrotaskScheduler.d.ts +0 -35
- package/dist/utils/createMicrotaskScheduler.d.ts +0 -28
- package/dist/utils/debounce.d.ts +0 -22
- package/dist/utils/equality.d.ts +0 -38
- package/dist/utils/hydrationCoordinator.d.ts +0 -13
- package/dist/utils/promiseUtils.d.ts +0 -2
- package/dist/utils/serialization.d.ts +0 -14
- package/dist/utils/stringUtils.d.ts +0 -7
- package/dist/utils/time.d.ts +0 -37
- package/dist/vanilla/createBaseStore.d.ts +0 -35
- package/dist/vanilla/createDerivedStore.d.ts +0 -62
- package/dist/vanilla/createQueryStore.d.ts +0 -116
- package/dist/vanilla/createVirtualStore.d.ts +0 -39
- package/dist/vanilla/env.web.d.ts +0 -6
- package/dist/vanilla/index.d.ts +0 -1
- package/dist/vanilla/index.shared.d.ts +0 -13
- package/dist/vanilla/internal/baseStore.d.ts +0 -1
- package/dist/vanilla/internal/config.d.ts +0 -63
- package/dist/vanilla/internal/createStoreActions.d.ts +0 -23
- package/dist/vanilla/internal/derivedStore/cascadeScheduler.d.ts +0 -30
- package/dist/vanilla/internal/derivedStore/deriveProxy.d.ts +0 -14
- package/dist/vanilla/internal/derivedStore/pathFinder.d.ts +0 -25
- package/dist/vanilla/internal/derivedStore.d.ts +0 -1
- package/dist/vanilla/internal/errors.d.ts +0 -9
- package/dist/vanilla/internal/logger.d.ts +0 -9
- package/dist/vanilla/internal/middleware/createHydrationGate.d.ts +0 -19
- package/dist/vanilla/internal/queryStore/queryStoreDefaults.d.ts +0 -7
- package/dist/vanilla/internal/queryStore.d.ts +0 -1
- package/dist/vanilla/internal/runtime.d.ts +0 -12
- package/dist/vanilla/internal/signal.d.ts +0 -11
- package/dist/vanilla/internal/storage/storageCreators.d.ts +0 -11
- package/dist/vanilla/internal/storeUtils.d.ts +0 -45
- package/dist/vanilla/internal/sync/browserSyncEngine.d.ts +0 -2
- package/dist/vanilla/internal/sync/noopSyncEngine.d.ts +0 -2
- package/dist/vanilla/internal/sync/syncEnhancer.d.ts +0 -25
- package/dist/vanilla/internal/utils/persistUtils.d.ts +0 -8
- package/dist/vanilla/internal/virtualStore.d.ts +0 -1
- package/dist/vanilla/queryStore/classes/SubscriptionManager.d.ts +0 -66
- package/dist/vanilla/queryStore/queryKey.d.ts +0 -2
- package/dist/vanilla/queryStore/signalTypes.d.ts +0 -13
- package/dist/vanilla/queryStore/types.d.ts +0 -402
- package/dist/vanilla/storage/storageTypes.d.ts +0 -12
- package/dist/vanilla/store/attachStoreHook.d.ts +0 -5
- package/dist/vanilla/store/attachStoreHook.vanilla.d.ts +0 -5
- package/dist/vanilla/store/batchStoreNotifications.web.d.ts +0 -1
- package/dist/vanilla/store/createStore.d.ts +0 -5
- package/dist/vanilla/store/persist.d.ts +0 -13
- package/dist/vanilla/store/stateUpdate.d.ts +0 -9
- package/dist/vanilla/store/types.d.ts +0 -107
- package/dist/vanilla/storesStorage.web.d.ts +0 -2
- package/dist/vanilla/sync/types.d.ts +0 -114
- package/dist/vanilla/types/functions.d.ts +0 -23
- package/dist/vanilla/types/objects.d.ts +0 -10
- package/dist/vanilla/types/setState.d.ts +0 -21
- package/dist/vanilla/types/subscribe.d.ts +0 -27
- package/dist/vanilla/types/useStoreCallSignatures.d.ts +0 -1
- package/dist/vanilla/types/useStoreCallSignatures.vanilla.d.ts +0 -1
- package/dist/vanilla/types/utils.d.ts +0 -12
- package/dist/vanilla/types.d.ts +0 -285
- package/dist/vanilla/utils/core.d.ts +0 -25
- package/dist/vanilla/utils/createAsyncMicrotaskScheduler.d.ts +0 -34
- package/dist/vanilla/utils/createMicrotaskScheduler.d.ts +0 -27
- package/dist/vanilla/utils/debounce.d.ts +0 -21
- package/dist/vanilla/utils/equality.d.ts +0 -37
- package/dist/vanilla/utils/hydrationCoordinator.d.ts +0 -12
- package/dist/vanilla/utils/promiseUtils.d.ts +0 -1
- package/dist/vanilla/utils/serialization.d.ts +0 -13
- package/dist/vanilla/utils/stringUtils.d.ts +0 -6
- package/dist/vanilla/utils/time.d.ts +0 -36
- package/dist/web/chunk-QJLWBD7M.mjs +0 -1
- package/dist/web/chunk-V4LHP7LR.mjs +0 -1
|
@@ -1 +1,1469 @@
|
|
|
1
|
-
|
|
1
|
+
//#region src/storage/storageTypes.d.ts
|
|
2
|
+
type StorageValue<S, HideSyncMetadata extends boolean = false> = HideSyncMetadata extends true ? {
|
|
3
|
+
state: S;
|
|
4
|
+
version?: number;
|
|
5
|
+
} : {
|
|
6
|
+
state: S;
|
|
7
|
+
syncMetadata?: {
|
|
8
|
+
origin?: string;
|
|
9
|
+
timestamp?: number;
|
|
10
|
+
fields?: Record<string, number>;
|
|
11
|
+
};
|
|
12
|
+
version?: number;
|
|
13
|
+
};
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/types/functions.d.ts
|
|
16
|
+
/**
|
|
17
|
+
* Relaxes function parameter variance to allow subtype
|
|
18
|
+
* assignment otherwise blocked by strict contravariance.
|
|
19
|
+
*/
|
|
20
|
+
type BivariantMethod<T extends Record<string, UnknownFunction>> = T[keyof T];
|
|
21
|
+
/**
|
|
22
|
+
* Extract the keys of `T` whose values are functions.
|
|
23
|
+
*/
|
|
24
|
+
type FunctionKeys<T> = { [K in keyof T]-?: T[K] extends UnknownFunction ? K : never }[keyof T];
|
|
25
|
+
/**
|
|
26
|
+
* A record of string keys to unknown functions.
|
|
27
|
+
*/
|
|
28
|
+
type FunctionRecord = Record<string, UnknownFunction>;
|
|
29
|
+
/**
|
|
30
|
+
* Return `T` if it is **not** a function, otherwise `never`.
|
|
31
|
+
*/
|
|
32
|
+
type NonFunction<T> = T extends ((...args: infer _) => unknown) ? never : T;
|
|
33
|
+
/**
|
|
34
|
+
* Unknown generic function type.
|
|
35
|
+
*/
|
|
36
|
+
type UnknownFunction = (...args: never[]) => unknown;
|
|
37
|
+
//#endregion
|
|
38
|
+
//#region src/types/setState.d.ts
|
|
39
|
+
type SetPartial<S> = S | Partial<S> | BivariantMethod<{
|
|
40
|
+
updater(state: S): S | Partial<S>;
|
|
41
|
+
}>;
|
|
42
|
+
type SetFull<S> = S | BivariantMethod<{
|
|
43
|
+
updater(state: S): S;
|
|
44
|
+
}>;
|
|
45
|
+
type SetStateReplaceArgs<S, ExtraArgs extends unknown[] = []> = [update: SetFull<S>, replace: true, ...extraArgs: ExtraArgs];
|
|
46
|
+
type SetStatePartialArgs<S, ExtraArgs extends unknown[] = []> = [update: SetPartial<S>, replace?: false, ...extraArgs: ExtraArgs];
|
|
47
|
+
type SetStateArgs<S, ExtraArgs extends unknown[] = []> = SetStatePartialArgs<S, ExtraArgs> | SetStateReplaceArgs<S, ExtraArgs>;
|
|
48
|
+
/**
|
|
49
|
+
* Rest-argument form of `setState`, used when forwarding calls.
|
|
50
|
+
*/
|
|
51
|
+
type SetState<S, ExtraArgs extends unknown[] = [], PersistReturn extends Promise<void> | void = void> = (...args: SetStateArgs<S, ExtraArgs>) => PersistReturn;
|
|
52
|
+
/**
|
|
53
|
+
* Store `setState` method overloads for partial updates and full replacement.
|
|
54
|
+
*/
|
|
55
|
+
type SetStateOverloads<S, PersistReturn extends Promise<void> | void = void> = BivariantMethod<{
|
|
56
|
+
setState(update: SetPartial<S>, replace?: false): PersistReturn;
|
|
57
|
+
setState(update: SetFull<S>, replace: true): PersistReturn;
|
|
58
|
+
}>;
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/types/subscribe.d.ts
|
|
61
|
+
type Listener<S> = (state: S, prevState: S) => void;
|
|
62
|
+
type Selector<S, Selected> = (state: S) => Selected;
|
|
63
|
+
type EqualityFn<T = unknown> = (a: T, b: T) => boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Minimum store API required for subscription.
|
|
66
|
+
*/
|
|
67
|
+
type SubscribableStore = {
|
|
68
|
+
subscribe(selector: Selector<unknown, unknown>, listener: () => void, options?: SubscribeOptions<unknown>): UnsubscribeFn;
|
|
69
|
+
};
|
|
70
|
+
type SubscribeOptions<Selected> = {
|
|
71
|
+
equalityFn?: EqualityFn<Selected>;
|
|
72
|
+
fireImmediately?: boolean;
|
|
73
|
+
};
|
|
74
|
+
type ListenerArgs<S> = [listener: Listener<S>];
|
|
75
|
+
type SelectorArgs<S, Selected> = [selector: Selector<S, Selected>, listener: Listener<Selected>, options?: SubscribeOptions<Selected>];
|
|
76
|
+
type SubscribeArgs<S, Selected = unknown> = ListenerArgs<S> | SelectorArgs<S, Selected>;
|
|
77
|
+
type UnsubscribeFn = () => void;
|
|
78
|
+
type SubscribeFn<S, Selected = S> = (...args: SubscribeArgs<S, Selected>) => UnsubscribeFn;
|
|
79
|
+
type SubscribeOverloads<S> = {
|
|
80
|
+
(listener: Listener<S>): UnsubscribeFn;
|
|
81
|
+
<Selected>(selector: Selector<S, Selected>, listener: Listener<Selected>, options?: SubscribeOptions<Selected>): UnsubscribeFn;
|
|
82
|
+
};
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region src/store/types.d.ts
|
|
85
|
+
/**
|
|
86
|
+
* Store object contract shared by creators, middleware, and internal store utilities.
|
|
87
|
+
*/
|
|
88
|
+
type StoreApi<S> = {
|
|
89
|
+
getInitialState: () => S;
|
|
90
|
+
getState: () => S;
|
|
91
|
+
setState: SetStateOverloads<S>;
|
|
92
|
+
subscribe: SubscribeOverloads<S>;
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Callback that builds store state from the set/get/store API supplied during construction.
|
|
96
|
+
*/
|
|
97
|
+
type StateCreator$1<S, Mutators extends StoreMutators = [], StoreMutatorOutput extends StoreMutators = [], U = S> = ((setState: Get<Mutate<StoreApi<S>, Mutators>, "setState", never>, getState: Get<Mutate<StoreApi<S>, Mutators>, "getState", never>, store: Mutate<StoreApi<S>, Mutators>) => U) & {
|
|
98
|
+
$$storeMutators?: StoreMutatorOutput;
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Synchronous storage adapter consumed by the persistence wrapper.
|
|
102
|
+
*/
|
|
103
|
+
type SyncPersistStorage<State, PersistedState = Partial<State>> = {
|
|
104
|
+
getItem: (name: string) => StorageValue<PersistedState> | null;
|
|
105
|
+
removeItem: (name: string) => void;
|
|
106
|
+
setItem: (name: string, state: State, version: number | undefined) => void;
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* Asynchronous storage adapter consumed by the persistence wrapper.
|
|
110
|
+
*/
|
|
111
|
+
type AsyncPersistStorage<State, PersistedState = Partial<State>> = {
|
|
112
|
+
getItem: (name: string) => Promise<StorageValue<PersistedState> | null>;
|
|
113
|
+
removeItem: (name: string) => Promise<void>;
|
|
114
|
+
setItem: (name: string, state: State, version: number | undefined) => Promise<void>;
|
|
115
|
+
};
|
|
116
|
+
/**
|
|
117
|
+
* Accepted storage adapter types for sync or async persistence.
|
|
118
|
+
*/
|
|
119
|
+
type PersistStorage<State, PersistedState = Partial<State>> = AsyncPersistStorage<State, PersistedState> | SyncPersistStorage<State, PersistedState>;
|
|
120
|
+
/**
|
|
121
|
+
* Persistence options consumed by the persistence wrapper.
|
|
122
|
+
*/
|
|
123
|
+
type PersistOptions<S, PersistedState = Partial<S>> = {
|
|
124
|
+
merge?: (persistedState: PersistedState | undefined, currentState: S) => S;
|
|
125
|
+
migrate?: (persistedState: PersistedState, version: number) => PersistedState | Promise<PersistedState>;
|
|
126
|
+
name: string;
|
|
127
|
+
onRehydrateStorage?: (state: S) => ((state?: S, error?: unknown) => void) | void;
|
|
128
|
+
skipHydration?: boolean;
|
|
129
|
+
storage: PersistStorage<S, PersistedState>;
|
|
130
|
+
version: number;
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* Methods attached by the persistence wrapper before async hydration state is added.
|
|
134
|
+
*/
|
|
135
|
+
type PersistMethods<S, PersistedState> = {
|
|
136
|
+
clearStorage: () => void;
|
|
137
|
+
getOptions: () => Partial<PersistOptions<S, PersistedState>>;
|
|
138
|
+
hasHydrated: () => boolean;
|
|
139
|
+
onHydrate: (listener: (state: S) => void) => () => void;
|
|
140
|
+
onFinishHydration: (listener: (state: S) => void) => () => void;
|
|
141
|
+
rehydrate: () => Promise<void> | void;
|
|
142
|
+
setOptions: (options: Partial<PersistOptions<S, PersistedState>>) => void;
|
|
143
|
+
};
|
|
144
|
+
/**
|
|
145
|
+
* Store shape after the persistence wrapper adds persistence methods, write-through `setState`,
|
|
146
|
+
* and async hydration state when applicable.
|
|
147
|
+
*/
|
|
148
|
+
type WithPersist<Store, PersistedState, PersistReturn extends void | Promise<void>> = Store extends StoreApi<infer S> ? Write<Store, {
|
|
149
|
+
persist: PersistMethods<S, PersistedState> & HydrationPromise<PersistReturn>;
|
|
150
|
+
setState: SetStateOverloads<S, PersistReturn>;
|
|
151
|
+
}> : Store;
|
|
152
|
+
type HydrationPromise<PersistReturn> = PersistReturn extends Promise<void> ? {
|
|
153
|
+
/** Invoke to get a promise that resolves once hydration completes. */hydrationPromise: () => Promise<void>;
|
|
154
|
+
} : {
|
|
155
|
+
hydrationPromise?: undefined;
|
|
156
|
+
};
|
|
157
|
+
type Get<T, K, Fallback> = K extends keyof T ? T[K] : Fallback;
|
|
158
|
+
type Write<T, U> = Omit<T, keyof U> & U;
|
|
159
|
+
type PersistMutator<Store, Args> = Args extends [infer PersistedState, infer PersistReturn extends void | Promise<void>] ? WithPersist<Store, PersistedState, PersistReturn> : Store;
|
|
160
|
+
type StoreMutatorIdentifier = keyof StoreMutatorMap<unknown, unknown>;
|
|
161
|
+
/**
|
|
162
|
+
* Mapping from store mutator identifiers to the store API shape they add.
|
|
163
|
+
*/
|
|
164
|
+
interface StoreMutatorMap<Store, Args> {
|
|
165
|
+
"stores/persist": PersistMutator<Store, Args>;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Ordered list of store mutators applied to a state creator.
|
|
169
|
+
*/
|
|
170
|
+
type StoreMutators = [StoreMutatorIdentifier, unknown][];
|
|
171
|
+
/**
|
|
172
|
+
* Applies a list of store mutators to a store API type.
|
|
173
|
+
*/
|
|
174
|
+
type Mutate<Store, Mutators> = number extends Mutators["length" & keyof Mutators] ? Store : Mutators extends [] ? Store : Mutators extends [[infer Identifier, infer Args], ...infer Rest] ? Identifier extends StoreMutatorIdentifier ? Rest extends StoreMutators ? Mutate<StoreMutatorMap<Store, Args>[Identifier], Rest> : StoreMutatorMap<Store, Args>[Identifier] : Store : Store;
|
|
175
|
+
//#endregion
|
|
176
|
+
//#region src/sync/types.d.ts
|
|
177
|
+
/**
|
|
178
|
+
* Metadata for a field's last write.
|
|
179
|
+
*/
|
|
180
|
+
type FieldMetadata = readonly [timestamp: number, sessionId: string];
|
|
181
|
+
type SyncStateKey<T extends Record<string, unknown>> = Extract<{ [K in keyof T]-?: T[K] extends UnknownFunction ? never : K }[keyof T], string>;
|
|
182
|
+
type SyncValues<T extends Record<string, unknown>> = Partial<T> & { [K in SyncStateKey<T>]?: T[K] };
|
|
183
|
+
type SyncUpdate<T extends Record<string, unknown>> = {
|
|
184
|
+
replace: boolean;
|
|
185
|
+
sessionId: string;
|
|
186
|
+
timestamp: number;
|
|
187
|
+
values: SyncValues<T>;
|
|
188
|
+
};
|
|
189
|
+
/**
|
|
190
|
+
* Passed to `SyncEngine.register()` to connect a store to the sync system.
|
|
191
|
+
*/
|
|
192
|
+
type SyncRegistration<T extends Record<string, unknown>> = {
|
|
193
|
+
/** Callback invoked by the engine to apply incoming remote updates to the store. */apply: (update: SyncUpdate<T>) => void; /** The state keys to sync. Non-function properties only. */
|
|
194
|
+
fields: ReadonlyArray<SyncStateKey<T>>; /** Returns the store's current state. Used by engines that need to read state (e.g., for diffing). */
|
|
195
|
+
getState: () => T; /** Unique identifier for this store. Must match across clients to sync the same data. */
|
|
196
|
+
key: string;
|
|
197
|
+
};
|
|
198
|
+
/**
|
|
199
|
+
* Returned by `SyncEngine.register()`. Controls the lifecycle of a synced store.
|
|
200
|
+
*/
|
|
201
|
+
interface SyncHandle<T extends Record<string, unknown>> {
|
|
202
|
+
/**
|
|
203
|
+
* Permanently removes this store from the sync engine. After calling, the handle
|
|
204
|
+
* is invalid and the store will no longer send or receive updates. To temporarily
|
|
205
|
+
* pause sync, use `onFirstSubscribe`/`onLastUnsubscribe` lifecycle hooks instead.
|
|
206
|
+
*/
|
|
207
|
+
destroy: () => void;
|
|
208
|
+
/** Returns `true` once the store has received its initial state from the engine. */
|
|
209
|
+
hydrated?: () => boolean;
|
|
210
|
+
/**
|
|
211
|
+
* Called when the store's subscriber count goes from 0 to 1. The registration
|
|
212
|
+
* remains active. Use for lazy resource acquisition (e.g., opening a WebSocket).
|
|
213
|
+
*/
|
|
214
|
+
onFirstSubscribe?: () => void;
|
|
215
|
+
/** Registers a one-time callback to run when hydration completes. */
|
|
216
|
+
onHydrated?: (callback: () => void) => void;
|
|
217
|
+
/**
|
|
218
|
+
* Called when the store's subscriber count drops to 0. The registration remains
|
|
219
|
+
* active and `onFirstSubscribe` will fire again on the next subscription.
|
|
220
|
+
* Use for resource cleanup (e.g., closing idle connections).
|
|
221
|
+
*/
|
|
222
|
+
onLastUnsubscribe?: () => void;
|
|
223
|
+
/**
|
|
224
|
+
* Broadcasts a state update to other clients. Set to `null` for engines where
|
|
225
|
+
* publishing is implicit (e.g., `chrome.storage` where the write itself triggers sync).
|
|
226
|
+
*/
|
|
227
|
+
publish: ((update: SyncUpdate<T>) => void) | null;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Interface for multi-client state synchronization. Stores register to send and receive updates.
|
|
231
|
+
*/
|
|
232
|
+
interface SyncEngine {
|
|
233
|
+
/**
|
|
234
|
+
* When `true`, embeds sync metadata (`{ origin, timestamp, fields }`) into persisted
|
|
235
|
+
* storage values. Required for engines that use storage writes as their transport.
|
|
236
|
+
* Only effective when the store is also persisted.
|
|
237
|
+
* @default false
|
|
238
|
+
*/
|
|
239
|
+
readonly injectStorageMetadata?: boolean;
|
|
240
|
+
/** Registers a store for synchronization. Returns a handle to control the sync lifecycle. */
|
|
241
|
+
register: {
|
|
242
|
+
<T extends Record<string, unknown>>(registration: SyncRegistration<T>): SyncHandle<T>;
|
|
243
|
+
(registration: SyncRegistration<Record<string, unknown>>): SyncHandle<Record<string, unknown>>;
|
|
244
|
+
};
|
|
245
|
+
/** Unique identifier for this client session. Used for conflict resolution and filtering self-updates. */
|
|
246
|
+
readonly sessionId: string;
|
|
247
|
+
}
|
|
248
|
+
type SyncMergeFn<T, TState = unknown> = (incoming: T, current: T, currentState: TState, incomingValues: Partial<TState>) => T;
|
|
249
|
+
type SyncConfig<T extends Record<string, unknown>> = {
|
|
250
|
+
/**
|
|
251
|
+
* The sync engine implementation to use.
|
|
252
|
+
*
|
|
253
|
+
* Defaults to cross-tab sync in browser environments. No-op in other environments unless a
|
|
254
|
+
* custom engine is provided.
|
|
255
|
+
*/
|
|
256
|
+
engine?: SyncEngine; /** The state keys to sync. If unspecified, all non-function store properties are synced. */
|
|
257
|
+
fields?: ReadonlyArray<SyncStateKey<T>>;
|
|
258
|
+
/**
|
|
259
|
+
* When true, injects sync metadata (`{ origin, timestamp, fields }`) into the persisted
|
|
260
|
+
* storage payload. Only takes effect when used with a persisted store.
|
|
261
|
+
*
|
|
262
|
+
* Useful for sync engines that use storage events as their transport (e.g., `chrome.storage`).
|
|
263
|
+
*
|
|
264
|
+
* Can also be set on the `engine` object. This option takes precedence if both are provided.
|
|
265
|
+
* @default false
|
|
266
|
+
*/
|
|
267
|
+
injectStorageMetadata?: boolean; /** The key used to identify the store to the sync engine. Required if `storageKey` is absent. */
|
|
268
|
+
key?: string; /** Optional merge function to use for each synced state key. Use with caution. */
|
|
269
|
+
merge?: { [K in SyncStateKey<T>]?: SyncMergeFn<T[K], T> };
|
|
270
|
+
};
|
|
271
|
+
/**
|
|
272
|
+
* Internal type for `SyncConfig` with `key` always present.
|
|
273
|
+
*/
|
|
274
|
+
type NormalizedSyncConfig<T extends Record<string, unknown>> = SyncConfig<T> & {
|
|
275
|
+
key: string;
|
|
276
|
+
};
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region src/types/useStoreCallSignatures.react.d.ts
|
|
279
|
+
type UseStoreCallSignatures<State> = {
|
|
280
|
+
(): State;
|
|
281
|
+
<Selected>(selector: Selector<State, Selected>, equalityFn?: EqualityFn<Selected>): Selected;
|
|
282
|
+
};
|
|
283
|
+
//#endregion
|
|
284
|
+
//#region src/types.d.ts
|
|
285
|
+
type StoreMutatorsWithSelector<Mutators extends StoreMutators = StoreMutators> = Mutators;
|
|
286
|
+
type StateCreator<S, U = S> = StateCreator$1<S, [], [], U>;
|
|
287
|
+
type UseBoundStoreWithEqualityFn<Store extends {
|
|
288
|
+
getState: () => unknown;
|
|
289
|
+
}, State = InferStoreState<Store>> = UseStoreCallSignatures<State> & Store;
|
|
290
|
+
type BaseStore<S> = UseBoundStoreWithEqualityFn<StoreApi<S>> & {
|
|
291
|
+
subscribe: SubscribeOverloads<S>;
|
|
292
|
+
};
|
|
293
|
+
type PersistedStore<S, PersistedState = Partial<S>, PersistReturn extends void | Promise<void> = void | Promise<void>> = UseStoreCallSignatures<S> & WithPersist<BaseStore<S>, PersistedState, PersistReturn>;
|
|
294
|
+
type Store<S, PersistedState extends Partial<S> = never, PersistReturn extends void | Promise<void> = void | Promise<void>> = [PersistedState] extends [never] ? BaseStore<S> : PersistedStore<S, PersistedState, PersistReturn>;
|
|
295
|
+
/**
|
|
296
|
+
* Store returned by creators that accept optional persistence options.
|
|
297
|
+
* `persist` exists only when persistence is configured.
|
|
298
|
+
*/
|
|
299
|
+
type OptionallyPersistedStore<S, PersistedState, PersistReturn extends void | Promise<void> = void> = UseStoreCallSignatures<S> & Omit<BaseStore<S>, "setState"> & {
|
|
300
|
+
persist?: PersistedStore<S, PersistedState, PersistReturn>["persist"];
|
|
301
|
+
setState(update: SetPartial<S>, replace?: false): PersistReturn;
|
|
302
|
+
setState(update: SetFull<S>, replace: true): PersistReturn;
|
|
303
|
+
};
|
|
304
|
+
type NoInfer<T> = [T][T extends unknown ? 0 : never];
|
|
305
|
+
type Timeout = ReturnType<typeof setTimeout>;
|
|
306
|
+
type InferStoreState<Store> = Store extends {
|
|
307
|
+
getState: () => infer T;
|
|
308
|
+
} ? T : never;
|
|
309
|
+
/**
|
|
310
|
+
* Action methods returned by `createStoreActions(store)`.
|
|
311
|
+
*/
|
|
312
|
+
type StoreActions<Store extends StoreApi<unknown>> = Pick<InferStoreState<Store>, FunctionKeys<InferStoreState<Store>>>;
|
|
313
|
+
/**
|
|
314
|
+
* Extracts a store's `setState` return type.
|
|
315
|
+
* - `void` for non-persisted or synchronous persisted stores.
|
|
316
|
+
* - `Promise<void>` for async persisted stores.
|
|
317
|
+
*/
|
|
318
|
+
type InferSetStateReturn<Store> = Store extends {
|
|
319
|
+
setState(...args: SetStateArgs<infer S>): infer R;
|
|
320
|
+
} ? R : void;
|
|
321
|
+
/**
|
|
322
|
+
* Extracts a store's `PersistedState` type.
|
|
323
|
+
* Returns `never` if the store doesn't use persistence.
|
|
324
|
+
*/
|
|
325
|
+
type InferPersistedState<PersistedStore> = PersistedStore extends Store<infer _, infer PersistedState> ? PersistedState : never;
|
|
326
|
+
/**
|
|
327
|
+
* Reads store state and records dependencies for tracked computations.
|
|
328
|
+
* - `$(store, selector, equalityFn?)` depends on the selected state
|
|
329
|
+
* - `$(store)` depends on accessed state paths
|
|
330
|
+
*/
|
|
331
|
+
type DeriveGetter = {
|
|
332
|
+
<SourceStore extends StoreApi<InferStoreState<SourceStore>>>(store: SourceStore): InferStoreState<SourceStore>;
|
|
333
|
+
<SourceStore extends StoreApi<InferStoreState<SourceStore>>, Selected>(store: SourceStore, selector: Selector<InferStoreState<SourceStore>, Selected>, equalityFn?: EqualityFn<Selected>): Selected;
|
|
334
|
+
};
|
|
335
|
+
type DerivedStore<S> = WithFlushUpdates<ReadOnlyDerivedStore<BaseStore<S>>>;
|
|
336
|
+
type WithFlushUpdates<Store extends StoreApi<unknown>> = Store & {
|
|
337
|
+
/**
|
|
338
|
+
* Destroy the derived store and its subscriptions.
|
|
339
|
+
*
|
|
340
|
+
* Derived stores automatically clean up internal resources and subscriptions
|
|
341
|
+
* when no subscribers exist. So calling `destroy()` is usually unnecessary,
|
|
342
|
+
* unless `keepAlive: true` is specified and explicit teardown is desired.
|
|
343
|
+
*/
|
|
344
|
+
destroy: () => void;
|
|
345
|
+
/**
|
|
346
|
+
* Flush all pending updates — only applicable to **debounced** derived stores.
|
|
347
|
+
*/
|
|
348
|
+
flushUpdates: () => void;
|
|
349
|
+
};
|
|
350
|
+
type WithGetSnapshot<Store extends StoreApi<unknown>> = Store & {
|
|
351
|
+
/**
|
|
352
|
+
* Reads the current snapshot while activating lazy derived stores before subscription.
|
|
353
|
+
*/
|
|
354
|
+
getSnapshot: () => InferStoreState<Store>;
|
|
355
|
+
};
|
|
356
|
+
type ReadOnlyDerivedStore<Store extends BaseStore<unknown>> = Omit<Store, "getInitialState" | "setState"> & UseStoreCallSignatures<InferStoreState<Store>> & {
|
|
357
|
+
/**
|
|
358
|
+
* @deprecated **Not applicable to derived stores.** Will throw an error.
|
|
359
|
+
*/
|
|
360
|
+
getInitialState: Store["getInitialState"];
|
|
361
|
+
/**
|
|
362
|
+
* @deprecated **Not applicable to derived stores.** Will throw an error.
|
|
363
|
+
*/
|
|
364
|
+
setState: Store["setState"];
|
|
365
|
+
};
|
|
366
|
+
/**
|
|
367
|
+
* Configuration for creating derived stores. You can pass either:
|
|
368
|
+
* - A **function** (used as `equalityFn`), or
|
|
369
|
+
* - An **object** with the fields below
|
|
370
|
+
*/
|
|
371
|
+
type DeriveOptions<DerivedState = unknown> = EqualityFn<DerivedState> | {
|
|
372
|
+
/**
|
|
373
|
+
* Delay before triggering a re-derive when dependencies change.
|
|
374
|
+
* Accepts a number (ms) or debounce options:
|
|
375
|
+
*
|
|
376
|
+
* `{ delay: number, leading?: boolean, trailing?: boolean, maxWait?: number }`
|
|
377
|
+
* @default 0
|
|
378
|
+
*/
|
|
379
|
+
debounce?: number | DebounceOptions;
|
|
380
|
+
/**
|
|
381
|
+
* If `true`, the store will log debug messages to the console.
|
|
382
|
+
*
|
|
383
|
+
* If `'verbose'`, the store will log the subscriptions it creates each time the derive
|
|
384
|
+
* function is run, rather than only the first time.
|
|
385
|
+
* @default false
|
|
386
|
+
*/
|
|
387
|
+
debugMode?: boolean | "verbose";
|
|
388
|
+
/**
|
|
389
|
+
* A custom comparison function for detecting state changes.
|
|
390
|
+
* @default `Object.is`
|
|
391
|
+
*/
|
|
392
|
+
equalityFn?: EqualityFn<DerivedState>;
|
|
393
|
+
/**
|
|
394
|
+
* If `true`, the derived store will never destroy itself. Useful in cases where your
|
|
395
|
+
* derived store serves as a permanent cache subscribed to intermittently or not at all.
|
|
396
|
+
* Manual calls to `destroy` *will* destroy the store even when `keepAlive` is `true`.
|
|
397
|
+
*
|
|
398
|
+
* *Use this option carefully.*
|
|
399
|
+
* @default false
|
|
400
|
+
*/
|
|
401
|
+
keepAlive?: boolean;
|
|
402
|
+
/**
|
|
403
|
+
* Locks the dependency graph after the first derivation. Subscriptions to
|
|
404
|
+
* underlying stores are established once and reused on subsequent runs, rather
|
|
405
|
+
* than being torn down and rebuilt (the default behavior).
|
|
406
|
+
*
|
|
407
|
+
* This avoids the overhead of regenerating selectors and prevents unnecessary
|
|
408
|
+
* subscription churn. However, it means only the *initially tracked* dependencies
|
|
409
|
+
* will trigger updates — even if your derive function conditionally reads different
|
|
410
|
+
* stores in later runs.
|
|
411
|
+
*
|
|
412
|
+
* **Requirement**: All `$` calls in your derive function must be consistent and
|
|
413
|
+
* top level. Conditional dependency tracking will not work correctly.
|
|
414
|
+
*
|
|
415
|
+
* Safe to enable for most derived stores where dependencies are static.
|
|
416
|
+
*
|
|
417
|
+
* @default false
|
|
418
|
+
*/
|
|
419
|
+
lockDependencies?: boolean;
|
|
420
|
+
};
|
|
421
|
+
type Deserializer<SerializedState, PersistedState> = (serializedState: SerializedState) => StorageValue<PersistedState>;
|
|
422
|
+
type Serializer<SerializedState> = <PersistedState>(storageValue: StorageValue<PersistedState>) => SerializedState;
|
|
423
|
+
/**
|
|
424
|
+
* Synchronous storage interface.
|
|
425
|
+
* Used for localStorage and MMKV implementations.
|
|
426
|
+
*/
|
|
427
|
+
type SyncStorageInterface<SerializedState = unknown> = {
|
|
428
|
+
readonly async?: false;
|
|
429
|
+
/**
|
|
430
|
+
* Adapter-level deserializer used when a store does not supply its own.
|
|
431
|
+
* Acts as the default before falling back to the framework implementation.
|
|
432
|
+
*/
|
|
433
|
+
deserializer?<PersistedState>(serializedState: SerializedState): StorageValue<PersistedState>;
|
|
434
|
+
/**
|
|
435
|
+
* Adapter-level serializer used when a store does not supply its own.
|
|
436
|
+
* Acts as the default before falling back to the framework implementation.
|
|
437
|
+
*/
|
|
438
|
+
serializer?<PersistedState>(storageValue: StorageValue<PersistedState>): SerializedState;
|
|
439
|
+
clearAll(): void;
|
|
440
|
+
contains(key: string): boolean;
|
|
441
|
+
delete(key: string): void;
|
|
442
|
+
get(key: string): SerializedState | undefined;
|
|
443
|
+
getAllKeys(): string[];
|
|
444
|
+
set(key: string, value: SerializedState): void;
|
|
445
|
+
};
|
|
446
|
+
/**
|
|
447
|
+
* Asynchronous storage interface.
|
|
448
|
+
* Used for Chrome storage and other async storage implementations.
|
|
449
|
+
*/
|
|
450
|
+
type AsyncStorageInterface<SerializedState = unknown> = {
|
|
451
|
+
readonly async: true;
|
|
452
|
+
/**
|
|
453
|
+
* Adapter-level deserializer used when a store does not supply its own.
|
|
454
|
+
* Acts as the default before falling back to the framework implementation.
|
|
455
|
+
*/
|
|
456
|
+
deserializer?<PersistedState>(serializedState: SerializedState): StorageValue<PersistedState>;
|
|
457
|
+
/**
|
|
458
|
+
* Adapter-level serializer used when a store does not supply its own.
|
|
459
|
+
* Acts as the default before falling back to the framework implementation.
|
|
460
|
+
*/
|
|
461
|
+
serializer?<PersistedState>(storageValue: StorageValue<PersistedState>): SerializedState;
|
|
462
|
+
clearAll(): Promise<void>;
|
|
463
|
+
contains(key: string): Promise<boolean>;
|
|
464
|
+
delete(key: string): Promise<void>;
|
|
465
|
+
get(key: string): Promise<SerializedState | undefined>;
|
|
466
|
+
getAllKeys(): Promise<string[]>;
|
|
467
|
+
set(key: string, value: SerializedState): Promise<void>;
|
|
468
|
+
};
|
|
469
|
+
/**
|
|
470
|
+
* Configuration options for creating a persistable store.
|
|
471
|
+
*/
|
|
472
|
+
type PersistConfig<S, PersistedState extends Partial<S> = Partial<S>, PersistReturn = void> = {
|
|
473
|
+
/**
|
|
474
|
+
* A function to convert the serialized value back into the state object.
|
|
475
|
+
* If not provided, the storage adapter's `deserializer` is used before falling back to the default implementation.
|
|
476
|
+
*/
|
|
477
|
+
deserializer?: (serializedState: unknown) => StorageValue<PersistedState>;
|
|
478
|
+
/**
|
|
479
|
+
* A function to merge persisted state with current state during hydration.
|
|
480
|
+
* By default, persisted state is shallow-merged into the current state.
|
|
481
|
+
*/
|
|
482
|
+
merge?: PersistOptions<S, PersistedState>["merge"];
|
|
483
|
+
/**
|
|
484
|
+
* A function to perform persisted state migration.
|
|
485
|
+
* This function will be called when persisted state versions mismatch with the one specified here.
|
|
486
|
+
*/
|
|
487
|
+
migrate?: PersistOptions<S, PersistedState>["migrate"];
|
|
488
|
+
/**
|
|
489
|
+
* A function returning another (optional) function.
|
|
490
|
+
* The main function will be called before the state rehydration.
|
|
491
|
+
* The returned function will be called after the state rehydration or when an error occurred.
|
|
492
|
+
*/
|
|
493
|
+
onRehydrateStorage?: PersistOptions<S, PersistedState>["onRehydrateStorage"];
|
|
494
|
+
/**
|
|
495
|
+
* A function that determines which parts of the state should be persisted.
|
|
496
|
+
* By default, the entire state is persisted.
|
|
497
|
+
*/
|
|
498
|
+
partialize?: (state: Readonly<S>) => PersistedState;
|
|
499
|
+
/**
|
|
500
|
+
* The throttle rate for the persist operation in milliseconds.
|
|
501
|
+
* @default iOS: time.seconds(3) | Android: time.seconds(5)
|
|
502
|
+
*/
|
|
503
|
+
persistThrottleMs?: PersistReturn extends Promise<unknown> ? undefined : number;
|
|
504
|
+
/**
|
|
505
|
+
* A function to serialize the state and version for storage.
|
|
506
|
+
* If not provided, the storage adapter's `serializer` is used before falling back to the default implementation.
|
|
507
|
+
*/
|
|
508
|
+
serializer?: (storageValue: StorageValue<PersistedState>) => string;
|
|
509
|
+
/**
|
|
510
|
+
* Custom storage implementation. If async, `setState` will return a Promise that resolves
|
|
511
|
+
* when the state is persisted. If sync, `setState` will return void.
|
|
512
|
+
*/
|
|
513
|
+
storage?: PersistReturn extends Promise<unknown> ? AsyncStorageInterface : SyncStorageInterface;
|
|
514
|
+
/**
|
|
515
|
+
* The unique key for the persisted store.
|
|
516
|
+
*/
|
|
517
|
+
storageKey: string;
|
|
518
|
+
/**
|
|
519
|
+
* The version of the store's schema.
|
|
520
|
+
* Useful for handling schema changes across app versions.
|
|
521
|
+
* @default 0
|
|
522
|
+
*/
|
|
523
|
+
version?: number;
|
|
524
|
+
};
|
|
525
|
+
type EnforceStorageKey<Options> = {
|
|
526
|
+
storageKey: string;
|
|
527
|
+
} extends Options ? Options : never;
|
|
528
|
+
type BaseStoreOptions<S, PersistedState extends Partial<S> = Partial<S>, PersistReturn = void> = (PersistConfig<S, PersistedState, PersistReturn> & {
|
|
529
|
+
sync?: S extends Record<string, unknown> ? SyncOption<S> : undefined;
|
|
530
|
+
}) | ({
|
|
531
|
+
sync: S extends Record<string, unknown> ? SyncWithoutStorageOption<NoInfer<S>> : undefined;
|
|
532
|
+
} & UndefinedPersistKeys<S, PersistedState, PersistReturn>);
|
|
533
|
+
/**
|
|
534
|
+
* The `sync` option can be:
|
|
535
|
+
* - `SyncConfig` object
|
|
536
|
+
* - `string` (shorthand for `{ key: string }`)
|
|
537
|
+
* - `true` (inherits key from `storageKey` — only valid with persistence)
|
|
538
|
+
*/
|
|
539
|
+
type SyncOption<S extends Record<string, unknown>> = SyncConfig<S> | string | true;
|
|
540
|
+
type SyncWithoutStorageOption<S extends Record<string, unknown>> = string | (Omit<SyncConfig<S>, "injectStorageMetadata" | "key"> & {
|
|
541
|
+
injectStorageMetadata?: never;
|
|
542
|
+
key: SyncWithoutStorageKey<SyncConfig<S>>;
|
|
543
|
+
});
|
|
544
|
+
type SyncWithoutStorageKey<Config> = Config extends {
|
|
545
|
+
key?: infer Key;
|
|
546
|
+
} ? Extract<Key, string> extends never ? string : Extract<Key, string> : string;
|
|
547
|
+
type UndefinedPersistKeys<S, PersistedState extends Partial<S>, PersistReturn> = { [K in keyof PersistConfig<S, PersistedState, PersistReturn>]?: undefined };
|
|
548
|
+
/**
|
|
549
|
+
* Expanded options for custom debounce behavior.
|
|
550
|
+
*/
|
|
551
|
+
type DebounceOptions = {
|
|
552
|
+
delay: number;
|
|
553
|
+
leading?: boolean;
|
|
554
|
+
maxWait?: number;
|
|
555
|
+
trailing?: boolean;
|
|
556
|
+
};
|
|
557
|
+
//#endregion
|
|
558
|
+
//#region src/createBaseStore.d.ts
|
|
559
|
+
/**
|
|
560
|
+
* Creates a base store without persistence.
|
|
561
|
+
* @param createState - The state creator function for the base store.
|
|
562
|
+
* @returns A store with the specified state.
|
|
563
|
+
*/
|
|
564
|
+
declare function createBaseStore<S>(createState: StateCreator<S>): Store<S>;
|
|
565
|
+
/**
|
|
566
|
+
* Creates a base store with persistence.
|
|
567
|
+
* @param createState - The state creator function for the base store.
|
|
568
|
+
* @param options - The configuration options for persistence and sync.
|
|
569
|
+
* @returns A store with the specified state and persistence.
|
|
570
|
+
*/
|
|
571
|
+
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, PersistReturn>;
|
|
572
|
+
/**
|
|
573
|
+
* Creates a base store with async persistence.
|
|
574
|
+
* @param createState - The state creator function for the base store.
|
|
575
|
+
* @param options - The configuration options for persistence and sync.
|
|
576
|
+
* @returns A store with the specified state and persistence.
|
|
577
|
+
*/
|
|
578
|
+
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, PersistReturn>;
|
|
579
|
+
/**
|
|
580
|
+
* Creates a base store with optional persistence.
|
|
581
|
+
* @param createState - The state creator function for the base store.
|
|
582
|
+
* @param options - The configuration options for persistence and sync.
|
|
583
|
+
* @returns A store with the specified state and optional persistence.
|
|
584
|
+
*/
|
|
585
|
+
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>;
|
|
586
|
+
/**
|
|
587
|
+
* Creates a base store with optional async persistence.
|
|
588
|
+
* @param createState - The state creator function for the base store.
|
|
589
|
+
* @param options - The configuration options for persistence and sync.
|
|
590
|
+
* @returns A store with the specified state and optional persistence.
|
|
591
|
+
*/
|
|
592
|
+
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>;
|
|
593
|
+
//#endregion
|
|
594
|
+
//#region src/createDerivedStore.d.ts
|
|
595
|
+
/**
|
|
596
|
+
* ### `createDerivedStore`
|
|
597
|
+
*
|
|
598
|
+
* Creates a **read-only** store derived from one or more source stores.
|
|
599
|
+
*
|
|
600
|
+
* ---
|
|
601
|
+
* The `deriveFunction` is called whenever its dependencies change, producing a new derived state.
|
|
602
|
+
* Dependencies are automatically tracked through a special `$` helper, which supports:
|
|
603
|
+
*
|
|
604
|
+
* 1) **Selector-based** usage:
|
|
605
|
+
* ```ts
|
|
606
|
+
* $ => {
|
|
607
|
+
* const user = $(useUserStore, s => s.user, shallowEqual);
|
|
608
|
+
* const theme = $(useSettingsStore, s => s.appearance.theme);
|
|
609
|
+
* return { user, theme, isAdmin: user?.roles.includes('admin') };
|
|
610
|
+
* }
|
|
611
|
+
* ```
|
|
612
|
+
*
|
|
613
|
+
* 2) **Proxy-based** usage (auto-built selectors for nested properties):
|
|
614
|
+
* ```ts
|
|
615
|
+
* $ => {
|
|
616
|
+
* const { user } = $(useUserStore); // Subscribe to `user`
|
|
617
|
+
* const theme = $(useSettingsStore).appearance.theme; // Subscribe to `theme`
|
|
618
|
+
* return { isAdmin: user?.roles.includes('admin'), theme, user };
|
|
619
|
+
* }
|
|
620
|
+
* ```
|
|
621
|
+
*
|
|
622
|
+
* ---
|
|
623
|
+
* Derived stores automatically unsubscribe from all dependencies when no consumers remain, and
|
|
624
|
+
* resubscribe when new consumers appear. The returned store exposes:
|
|
625
|
+
*
|
|
626
|
+
* - A **store object** with `getState()`, `subscribe()`, and `destroy()`
|
|
627
|
+
* - In the React build, a **React hook** (`const state = derivedStore(selector, equalityFn?)`)
|
|
628
|
+
*
|
|
629
|
+
* ---
|
|
630
|
+
* You can optionally pass a second parameter (either an equality function or a config object)
|
|
631
|
+
* to enable debouncing, customize the equality function, or set `lockDependencies: true`.
|
|
632
|
+
*
|
|
633
|
+
* (When dependencies are locked, subscriptions created via `$` are established once and are
|
|
634
|
+
* not rebuilt on subsequent re-derives, which can be a performance win for certain workloads.)
|
|
635
|
+
*
|
|
636
|
+
* ---
|
|
637
|
+
* @example
|
|
638
|
+
* ```ts
|
|
639
|
+
* // Create a derived store
|
|
640
|
+
* const searchResultsStore = createDerivedStore($ => {
|
|
641
|
+
* const query = $(searchStore).query.trim().toLowerCase();
|
|
642
|
+
* const items = $(itemsStore).items;
|
|
643
|
+
* return findResults(query, items);
|
|
644
|
+
* }, shallowEqual);
|
|
645
|
+
*
|
|
646
|
+
* const results = searchResultsStore.getState();
|
|
647
|
+
* ```
|
|
648
|
+
*
|
|
649
|
+
* ---
|
|
650
|
+
* @param deriveFunction - Function that reads from other stores via `$` to produce derived state.
|
|
651
|
+
* @param optionsOrEqualityFn - Either an equality function or a config object (see `DeriveOptions`).
|
|
652
|
+
*
|
|
653
|
+
* @returns A read-only derived store. In the React build, it is also callable as a hook.
|
|
654
|
+
*/
|
|
655
|
+
declare function createDerivedStore<Derived>(deriveFunction: ($: DeriveGetter) => Derived, optionsOrEqualityFn?: DeriveOptions<Derived>): DerivedStore<Derived>;
|
|
656
|
+
//#endregion
|
|
657
|
+
//#region src/queryStore/queryParam.d.ts
|
|
658
|
+
declare const QUERY_PARAM_CONFIG: unique symbol;
|
|
659
|
+
/**
|
|
660
|
+
* Selects how a query parameter participates in the query key.
|
|
661
|
+
*/
|
|
662
|
+
type QueryParamKey<T> = false | ((value: T) => unknown);
|
|
663
|
+
/**
|
|
664
|
+
* A query value derived from stores via `$`.
|
|
665
|
+
*/
|
|
666
|
+
type ReactiveParam<T, State> = ($: DeriveGetter, store: StoreApi<State>) => T;
|
|
667
|
+
/**
|
|
668
|
+
* Query parameter wrapper for values whose fetcher value and key value differ.
|
|
669
|
+
*/
|
|
670
|
+
type QueryParamConfig<T, State> = {
|
|
671
|
+
readonly [QUERY_PARAM_CONFIG]: true;
|
|
672
|
+
readonly key: QueryParamKey<T>;
|
|
673
|
+
readonly value: NonFunction<T> | ReactiveParam<T, State>;
|
|
674
|
+
};
|
|
675
|
+
/**
|
|
676
|
+
* A direct, reactive, or key-configured query parameter.
|
|
677
|
+
*/
|
|
678
|
+
type QueryParam<T, State> = NonFunction<T> | ReactiveParam<T, State> | QueryParamConfig<T, State>;
|
|
679
|
+
/**
|
|
680
|
+
* Wraps a query parameter when its full fetcher value should be excluded
|
|
681
|
+
* from the query key or represented by a smaller key value.
|
|
682
|
+
*/
|
|
683
|
+
declare function queryParam<T, State>(value: NonFunction<T> | ReactiveParam<T, State>, options: {
|
|
684
|
+
key: QueryParamKey<T>;
|
|
685
|
+
}): QueryParamConfig<T, State>;
|
|
686
|
+
//#endregion
|
|
687
|
+
//#region src/queryStore/types.d.ts
|
|
688
|
+
/**
|
|
689
|
+
* Helper type that represents the store returned by `createQueryStore()`.
|
|
690
|
+
*/
|
|
691
|
+
type QueryStore<TData, TParams extends Record<string, unknown>, CustomState = unknown> = Store<QueryStoreState<TData, TParams, CustomState>>;
|
|
692
|
+
/**
|
|
693
|
+
* Configuration options for creating a query-enabled store.
|
|
694
|
+
*/
|
|
695
|
+
type QueryStoreConfig<TQueryFnData, TParams extends Record<string, unknown>, TData = TQueryFnData, CustomState = unknown, S extends QueryStoreState<TData, TParams, CustomState> = QueryStoreState<TData, TParams, CustomState>> = ([TQueryFnData] extends [TData] ? {
|
|
696
|
+
/**
|
|
697
|
+
* A function to transform the raw fetched data** (`TQueryFnData`) into another
|
|
698
|
+
* form (`TData`). If not provided, the raw data returned by `fetcher` is used.
|
|
699
|
+
*/
|
|
700
|
+
transform?: (data: TQueryFnData, params: TParams) => TData;
|
|
701
|
+
} : {
|
|
702
|
+
/**
|
|
703
|
+
* A function to transform the raw fetched data** (`TQueryFnData`) into another
|
|
704
|
+
* form (`TData`). If not provided, the raw data returned by `fetcher` is used.
|
|
705
|
+
*/
|
|
706
|
+
transform: (data: TQueryFnData, params: TParams) => TData;
|
|
707
|
+
}) & {
|
|
708
|
+
/**
|
|
709
|
+
* **A function responsible for fetching data from a remote source.**
|
|
710
|
+
* Receives parameters of type TParams and optionally an abort controller.
|
|
711
|
+
* Returns either a promise or a raw data value of type TQueryFnData.
|
|
712
|
+
*
|
|
713
|
+
* ---
|
|
714
|
+
* `abortController` is by default available, unless either:
|
|
715
|
+
* - `abortInterruptedFetches` is set to `false` in the store's config
|
|
716
|
+
* - The fetch was manually triggered with `skipStoreUpdates: true`
|
|
717
|
+
*/
|
|
718
|
+
fetcher: (params: TParams, abortController: AbortController | null) => TQueryFnData | Promise<TQueryFnData>;
|
|
719
|
+
/**
|
|
720
|
+
* Called after each failure handled by the query store.
|
|
721
|
+
* `willRetry` indicates whether another attempt was scheduled.
|
|
722
|
+
*/
|
|
723
|
+
onError?: (failure: OnErrorParams<TParams>) => void;
|
|
724
|
+
/**
|
|
725
|
+
* **A callback invoked whenever fresh data is successfully fetched.**
|
|
726
|
+
* Receives the transformed data and the store's set function, which can optionally be used to update store state.
|
|
727
|
+
*/
|
|
728
|
+
onFetched?: (info: OnFetchedParams<TData, TParams, CustomState, S>) => void;
|
|
729
|
+
/**
|
|
730
|
+
* **A function that overrides the default behavior of setting the fetched data in the store's query cache.**
|
|
731
|
+
* Receives an object containing the transformed data, the query parameters, the query key, and the store's set function.
|
|
732
|
+
*
|
|
733
|
+
* When using `setData`, it’s important to note that you are taking full responsibility for managing query data. If your
|
|
734
|
+
* query supports variable parameters (and thus multiple query keys) and you want to cache data for each key, you’ll need
|
|
735
|
+
* to manually handle storing data based on the provided `params` or `queryKey`. Naturally, you will also bear
|
|
736
|
+
* responsibility for pruning this data in the event you do not want it persisted indefinitely.
|
|
737
|
+
*
|
|
738
|
+
* Automatic refetching per your specified `staleTime` is still managed internally by the store. While no query *data*
|
|
739
|
+
* will be cached internally if `setData` is provided, metadata such as the last fetch time for each query key is still
|
|
740
|
+
* cached and tracked by the store, unless caching is fully disabled via `disableCache: true`.
|
|
741
|
+
*/
|
|
742
|
+
setData?: (info: SetDataParams<TData, TParams, CustomState, S>) => void;
|
|
743
|
+
/**
|
|
744
|
+
* If `true`, the store will abort any partially completed fetches when:
|
|
745
|
+
* - A new fetch is initiated due to a change in parameters
|
|
746
|
+
* - All components subscribed to the store via selectors are unmounted
|
|
747
|
+
* @default true
|
|
748
|
+
*/
|
|
749
|
+
abortInterruptedFetches?: boolean;
|
|
750
|
+
/**
|
|
751
|
+
* The maximum duration, in milliseconds, that fetched data is considered fresh.
|
|
752
|
+
* After this time, data is considered expired and will be refetched when requested.
|
|
753
|
+
* @default time.days(7)
|
|
754
|
+
*/
|
|
755
|
+
cacheTime?: number | ((params: TParams) => number);
|
|
756
|
+
/**
|
|
757
|
+
* If `true`, the store will log debug messages to the console.
|
|
758
|
+
* @default false
|
|
759
|
+
*/
|
|
760
|
+
debugMode?: boolean;
|
|
761
|
+
/**
|
|
762
|
+
* If `true`, the store will **not** trigger automatic refetches when data becomes stale. This is
|
|
763
|
+
* useful in cases where you want to refetch data on component mount if stale, but not automatically
|
|
764
|
+
* if data becomes stale while your component is already mounted.
|
|
765
|
+
* @default false
|
|
766
|
+
*/
|
|
767
|
+
disableAutoRefetching?: boolean;
|
|
768
|
+
/**
|
|
769
|
+
* Controls whether the store's caching mechanisms are disabled. When disabled, the store will always refetch
|
|
770
|
+
* data when params change, and fetched data will not be stored unless a `setData` function is provided.
|
|
771
|
+
* @default false
|
|
772
|
+
*/
|
|
773
|
+
disableCache?: boolean;
|
|
774
|
+
/**
|
|
775
|
+
* When `true`, the store actively fetches and refetches data as needed.
|
|
776
|
+
* When `false`, the store will not automatically fetch data until explicitly enabled.
|
|
777
|
+
* @default true
|
|
778
|
+
*/
|
|
779
|
+
enabled?: boolean | ReactiveParam<boolean, S>;
|
|
780
|
+
/**
|
|
781
|
+
* When `true`, the store's `getData` method will always return existing data from the cache if it exists,
|
|
782
|
+
* regardless of whether the cached data is expired, until the data is pruned following a successful refetch.
|
|
783
|
+
*
|
|
784
|
+
* Additionally, when params change while the store is enabled, `getData` will return the previous data until
|
|
785
|
+
* data for the new params is available.
|
|
786
|
+
* @default false
|
|
787
|
+
*/
|
|
788
|
+
keepPreviousData?: boolean;
|
|
789
|
+
/**
|
|
790
|
+
* Delay before triggering a fetch when parameters change.
|
|
791
|
+
* Accepts a number (ms), false (no throttling), or debounce options:
|
|
792
|
+
*
|
|
793
|
+
* `{ delay: number, leading?: boolean, trailing?: boolean, maxWait?: number }`
|
|
794
|
+
* @default false
|
|
795
|
+
*/
|
|
796
|
+
paramChangeThrottle?: false | number | DebounceOptions;
|
|
797
|
+
/**
|
|
798
|
+
* Reactive or static parameters to be passed to the fetcher.
|
|
799
|
+
*/
|
|
800
|
+
params?: QueryStoreParams<TParams, TData, S, CustomState>;
|
|
801
|
+
/**
|
|
802
|
+
* Whether failed queries should be retried.
|
|
803
|
+
* `false` or `0` disables retries, a number limits retries, and a function decides each failure.
|
|
804
|
+
* Numeric limits must be non-negative integers.
|
|
805
|
+
* Function policies have no implicit retry limit.
|
|
806
|
+
* @default 5
|
|
807
|
+
*/
|
|
808
|
+
retry?: RetryPolicy<TParams>;
|
|
809
|
+
/**
|
|
810
|
+
* Finite, non-negative delay before each retry, in milliseconds.
|
|
811
|
+
* @default Exponential backoff from 5 seconds, doubling after each failure and capped at 5 minutes
|
|
812
|
+
*/
|
|
813
|
+
retryDelay?: RetryDelay<TParams>;
|
|
814
|
+
/**
|
|
815
|
+
* The duration, in milliseconds, that data is considered fresh after fetching.
|
|
816
|
+
* After becoming stale, the store may automatically refetch data in the background if there are active subscribers.
|
|
817
|
+
* @default time.minutes(2)
|
|
818
|
+
*/
|
|
819
|
+
staleTime?: number | ReactiveParam<number, S>;
|
|
820
|
+
/**
|
|
821
|
+
* Suppresses warnings in the event a `staleTime` under the minimum is desired.
|
|
822
|
+
* @default false
|
|
823
|
+
*/
|
|
824
|
+
suppressStaleTimeWarning?: boolean;
|
|
825
|
+
};
|
|
826
|
+
/**
|
|
827
|
+
* The internal state structure managed by the query store.
|
|
828
|
+
*/
|
|
829
|
+
type QueryStoreInternalState<TData, TParams extends Record<string, unknown>> = {
|
|
830
|
+
/**
|
|
831
|
+
* Initiates a data fetch for the given parameters. If no parameters are provided,
|
|
832
|
+
* the store's current parameters are used.
|
|
833
|
+
* @param params - Optional parameters to pass to the fetcher function.
|
|
834
|
+
* @param options - Optional {@link FetchOptions} to customize the fetch behavior.
|
|
835
|
+
* @returns A promise that resolves when the fetch operation completes.
|
|
836
|
+
*/
|
|
837
|
+
fetch: (params?: Partial<TParams>, options?: FetchOptions) => Promise<TData | null>;
|
|
838
|
+
/**
|
|
839
|
+
* A lower-level helper that provides direct access to raw cache entries. If no query key
|
|
840
|
+
* or params are specified, the cache entry for the current parameters is returned.
|
|
841
|
+
* @param paramsOrQueryKey - Optional parameters or query key to retrieve the cache entry.
|
|
842
|
+
* @returns The relevant cache entry, or `null` if no entry is found.
|
|
843
|
+
*/
|
|
844
|
+
getCacheEntry: (paramsOrQueryKey?: TParams | Partial<TParams> | string) => CacheEntry<TData> | null;
|
|
845
|
+
/**
|
|
846
|
+
* Returns the cached data, if available, for the provided query key or parameters.
|
|
847
|
+
* If no query key or params are specified, data for the current parameters is returned.
|
|
848
|
+
* @param paramsOrQueryKey - Optional parameters or query key to retrieve cached data for.
|
|
849
|
+
* @returns The cached data, or `null` if no data is available.
|
|
850
|
+
*/
|
|
851
|
+
getData: (paramsOrQueryKey?: TParams | string) => CacheEntry<TData>["data"];
|
|
852
|
+
/**
|
|
853
|
+
* Returns expanded status information for the currently specified query parameters.
|
|
854
|
+
* Pass a status key to avoid building the full status object.
|
|
855
|
+
* @example
|
|
856
|
+
* ```ts
|
|
857
|
+
* const isInitialLoad = myQueryStore.getState().getStatus('isInitialLoad');
|
|
858
|
+
* ```
|
|
859
|
+
* @returns The requested status, or the full status object if no key is provided.
|
|
860
|
+
*/
|
|
861
|
+
getStatus(statusKey: keyof QueryStatusInfo): QueryStatusInfo[keyof QueryStatusInfo];
|
|
862
|
+
getStatus(): QueryStatusInfo;
|
|
863
|
+
getStatus(statusKey?: keyof QueryStatusInfo): QueryStatusInfo[keyof QueryStatusInfo] | QueryStatusInfo;
|
|
864
|
+
/**
|
|
865
|
+
* Determines if the current data is expired based on whether `cacheTime` has been exceeded.
|
|
866
|
+
* @param override - An optional override for the default cache time, in milliseconds.
|
|
867
|
+
* @returns `true` if the data is expired, otherwise `false`.
|
|
868
|
+
*/
|
|
869
|
+
isDataExpired: (override?: number) => boolean;
|
|
870
|
+
/**
|
|
871
|
+
* Determines if the current data is stale based on whether `staleTime` has been exceeded.
|
|
872
|
+
* Stale data may be refreshed automatically in the background.
|
|
873
|
+
* @param override - An optional override for the default stale time, in milliseconds.
|
|
874
|
+
* @returns `true` if the data is stale, otherwise `false`.
|
|
875
|
+
*/
|
|
876
|
+
isStale: (override?: number) => boolean;
|
|
877
|
+
/**
|
|
878
|
+
* Tears down param subscriptions and timers and resets fetch state. Optionally resets store state.
|
|
879
|
+
* @param resetStoreState - If `true`, the store's state will be reset to its initial state.
|
|
880
|
+
* @default false
|
|
881
|
+
*/
|
|
882
|
+
reset: (resetStoreState?: boolean) => void;
|
|
883
|
+
/**
|
|
884
|
+
* Indicates whether the store should actively fetch data.
|
|
885
|
+
* When `false`, the store won't automatically refetch data.
|
|
886
|
+
*/
|
|
887
|
+
enabled: boolean;
|
|
888
|
+
/**
|
|
889
|
+
* The most recent error encountered during a fetch operation, if any.
|
|
890
|
+
*/
|
|
891
|
+
error: Error | null;
|
|
892
|
+
/**
|
|
893
|
+
* The timestamp of the last successful fetch, or null if no successful fetch has occurred.
|
|
894
|
+
*/
|
|
895
|
+
lastFetchedAt: number | null;
|
|
896
|
+
/**
|
|
897
|
+
* A cache of fetched data and metadata, keyed by generated query keys.
|
|
898
|
+
*/
|
|
899
|
+
queryCache: Record<string, CacheEntry<TData> | undefined>;
|
|
900
|
+
/**
|
|
901
|
+
* The current query key, generated deterministically from store parameters.
|
|
902
|
+
*/
|
|
903
|
+
queryKey: string;
|
|
904
|
+
/**
|
|
905
|
+
* The current status of the query's remote data fetching operation.
|
|
906
|
+
*/
|
|
907
|
+
status: QueryStatus;
|
|
908
|
+
};
|
|
909
|
+
/**
|
|
910
|
+
* The full state structure managed by the query store. This type is generally internal,
|
|
911
|
+
* though the state it defines can be accessed via the store's public interface.
|
|
912
|
+
*/
|
|
913
|
+
type QueryStoreState<TData, TParams extends Record<string, unknown>, CustomState = unknown> = QueryStoreInternalState<TData, TParams> & CustomState;
|
|
914
|
+
/**
|
|
915
|
+
* Defines additional options for a data fetch operation.
|
|
916
|
+
*/
|
|
917
|
+
type FetchOptions = {
|
|
918
|
+
/**
|
|
919
|
+
* Overrides the store's default cacheTime for this fetch, which dictates when the data fetched in this operation
|
|
920
|
+
* will become eligible for pruning.
|
|
921
|
+
*
|
|
922
|
+
* Has no effect if `skipStoreUpdates` is set to `true`.
|
|
923
|
+
*/
|
|
924
|
+
cacheTime?: number;
|
|
925
|
+
/**
|
|
926
|
+
* Forces a fetch request even if there is fresh data available in the cache.
|
|
927
|
+
*
|
|
928
|
+
* Note: If a pending fetch matches the forced fetch's params, the pending promise *will* be returned.
|
|
929
|
+
* @default false
|
|
930
|
+
*/
|
|
931
|
+
force?: boolean;
|
|
932
|
+
/**
|
|
933
|
+
* If `true`, the fetch will simply return the data without any internal handling or side effects,
|
|
934
|
+
* running in parallel with any other ongoing fetches. Use together with `force: true` if you want to
|
|
935
|
+
* guarantee that a fresh fetch is triggered regardless of the current store state.
|
|
936
|
+
*
|
|
937
|
+
* ---
|
|
938
|
+
* If set to `'withCache'`, the fetch will similarly run in parallel without affecting the store, but the
|
|
939
|
+
* fetched data will be stored in the cache, as long as the store's config doesn't contain `disableCache: true`.
|
|
940
|
+
* @default false
|
|
941
|
+
*/
|
|
942
|
+
skipStoreUpdates?: boolean | "withCache";
|
|
943
|
+
/**
|
|
944
|
+
* Overrides the store's default staleTime for this fetch, which dictates how fresh data must be to be returned
|
|
945
|
+
* from the cache.
|
|
946
|
+
*/
|
|
947
|
+
staleTime?: number;
|
|
948
|
+
/**
|
|
949
|
+
* If `true`, the fetch operation will throw an error if the fetch fails.
|
|
950
|
+
* @default false
|
|
951
|
+
*/
|
|
952
|
+
throwOnError?: boolean;
|
|
953
|
+
/**
|
|
954
|
+
* Dictates whether the store's `queryKey` should be updated based on the params used in the fetch operation.
|
|
955
|
+
* Useful if for instance you want to cache the manually fetched data, but skip updating the store's current
|
|
956
|
+
* `queryKey` (which determines where `getData()` points to).
|
|
957
|
+
*
|
|
958
|
+
* ---
|
|
959
|
+
* Manual fetches default to `false`. Internal query-store fetches default to the store's `keepPreviousData`
|
|
960
|
+
* behavior. When `skipStoreUpdates` is set, the query key is never updated.
|
|
961
|
+
*/
|
|
962
|
+
updateQueryKey?: boolean;
|
|
963
|
+
};
|
|
964
|
+
/**
|
|
965
|
+
* A set of constants representing the various stages of a query's remote data fetching process.
|
|
966
|
+
*/
|
|
967
|
+
declare const QueryStatuses: {
|
|
968
|
+
readonly Error: "error";
|
|
969
|
+
readonly Idle: "idle";
|
|
970
|
+
readonly Loading: "loading";
|
|
971
|
+
readonly Success: "success";
|
|
972
|
+
};
|
|
973
|
+
/**
|
|
974
|
+
* Represents the current status of the query's remote data fetching operation.
|
|
975
|
+
*
|
|
976
|
+
* Possible values:
|
|
977
|
+
* - **`'error'`**: The most recent request encountered an error.
|
|
978
|
+
* - **`'idle'`**: No request in progress, no error, no data yet.
|
|
979
|
+
* - **`'loading'`**: A request is currently in progress.
|
|
980
|
+
* - **`'success'`**: The most recent request has succeeded and data is available.
|
|
981
|
+
*/
|
|
982
|
+
type QueryStatus = (typeof QueryStatuses)[keyof typeof QueryStatuses];
|
|
983
|
+
/**
|
|
984
|
+
* Expanded status information for the currently specified query parameters.
|
|
985
|
+
*/
|
|
986
|
+
type QueryStatusInfo = {
|
|
987
|
+
isError: boolean;
|
|
988
|
+
isIdle: boolean;
|
|
989
|
+
isInitialLoad: boolean;
|
|
990
|
+
isLoading: boolean;
|
|
991
|
+
isSuccess: boolean;
|
|
992
|
+
};
|
|
993
|
+
/** Error metadata for a query key's latest failed fetch. */
|
|
994
|
+
type QueryErrorInfo = {
|
|
995
|
+
error: Error;
|
|
996
|
+
lastFailedAt: number;
|
|
997
|
+
retryCount: number; /** Whether the retry policy allows another attempt after this failure. */
|
|
998
|
+
retryAllowed: boolean;
|
|
999
|
+
};
|
|
1000
|
+
/**
|
|
1001
|
+
* Represents an entry in the query cache, which stores fetched data along with metadata,
|
|
1002
|
+
* and error information in the event the most recent fetch failed.
|
|
1003
|
+
*/
|
|
1004
|
+
type CacheEntry<T> = {
|
|
1005
|
+
cacheTime: number;
|
|
1006
|
+
data: T | null;
|
|
1007
|
+
} & ({
|
|
1008
|
+
errorInfo: QueryErrorInfo;
|
|
1009
|
+
lastFetchedAt: null;
|
|
1010
|
+
} | {
|
|
1011
|
+
errorInfo: QueryErrorInfo | null;
|
|
1012
|
+
lastFetchedAt: number;
|
|
1013
|
+
});
|
|
1014
|
+
/**
|
|
1015
|
+
* Internal helper type for the config’s params clause.
|
|
1016
|
+
*/
|
|
1017
|
+
type QueryStoreParams<TParams extends Record<string, unknown>, TData, S extends QueryStoreState<TData, TParams, CustomState>, CustomState = unknown> = [TParams] extends [Record<string, never>] ? undefined : { [K in keyof TParams]: QueryParam<TParams[K], S> };
|
|
1018
|
+
/**
|
|
1019
|
+
* The keys that make up the internal state of the store.
|
|
1020
|
+
*/
|
|
1021
|
+
type InternalStateKeys = keyof QueryStoreInternalState<unknown, Record<string, unknown>>;
|
|
1022
|
+
/**
|
|
1023
|
+
* Params available to retry policy and delay callbacks.
|
|
1024
|
+
*/
|
|
1025
|
+
type RetryFailureParams<TParams extends Record<string, unknown>> = {
|
|
1026
|
+
readonly error: Error;
|
|
1027
|
+
readonly params: TParams;
|
|
1028
|
+
readonly queryKey: string;
|
|
1029
|
+
/**
|
|
1030
|
+
* Retry attempts already performed in the current sequence.
|
|
1031
|
+
* `0` after the originating request fails, `1` after the first retry fails, and so on.
|
|
1032
|
+
*/
|
|
1033
|
+
readonly retryCount: number;
|
|
1034
|
+
};
|
|
1035
|
+
/**
|
|
1036
|
+
* A handled query failure and whether another attempt was scheduled.
|
|
1037
|
+
*/
|
|
1038
|
+
type OnErrorParams<TParams extends Record<string, unknown>> = RetryFailureParams<TParams> & {
|
|
1039
|
+
readonly willRetry: boolean;
|
|
1040
|
+
};
|
|
1041
|
+
/**
|
|
1042
|
+
* Whether failed queries should be retried.
|
|
1043
|
+
*
|
|
1044
|
+
* `false` or `0` disables retries, a number limits retries, and a function decides each failure.
|
|
1045
|
+
*
|
|
1046
|
+
* Numeric limits must be non-negative integers. Function policies have no implicit retry limit.
|
|
1047
|
+
*/
|
|
1048
|
+
type RetryPolicy<TParams extends Record<string, unknown>> = false | number | ((failure: RetryFailureParams<TParams>) => boolean);
|
|
1049
|
+
/**
|
|
1050
|
+
* The finite, non-negative delay before each retry, in milliseconds.
|
|
1051
|
+
*/
|
|
1052
|
+
type RetryDelay<TParams extends Record<string, unknown>> = number | ((failure: RetryFailureParams<TParams>) => number);
|
|
1053
|
+
/**
|
|
1054
|
+
* Helper type for defining `onFetched` parameters.
|
|
1055
|
+
*/
|
|
1056
|
+
type OnFetchedParams<TData, TParams extends Record<string, unknown> = Record<string, never>, CustomState = unknown, S extends QueryStoreState<TData, TParams, CustomState> = QueryStoreState<TData, TParams, CustomState>> = {
|
|
1057
|
+
data: TData;
|
|
1058
|
+
fetch: (params?: TParams | Partial<TParams>, options?: FetchOptions) => Promise<TData | null>;
|
|
1059
|
+
params: TParams;
|
|
1060
|
+
set: (update: SetPartial<S>) => void;
|
|
1061
|
+
};
|
|
1062
|
+
/**
|
|
1063
|
+
* Helper type for defining `setData` parameters.
|
|
1064
|
+
*/
|
|
1065
|
+
type SetDataParams<TData, TParams extends Record<string, unknown> = Record<string, never>, CustomState = unknown, S extends QueryStoreState<TData, TParams, CustomState> = QueryStoreState<TData, TParams, CustomState>> = {
|
|
1066
|
+
data: TData;
|
|
1067
|
+
params: TParams;
|
|
1068
|
+
queryKey: string;
|
|
1069
|
+
set: (update: SetPartial<S>) => void;
|
|
1070
|
+
};
|
|
1071
|
+
//#endregion
|
|
1072
|
+
//#region src/types/objects.d.ts
|
|
1073
|
+
/**
|
|
1074
|
+
* Forces TypeScript to expand a type for clearer IDE display.
|
|
1075
|
+
*/
|
|
1076
|
+
type Prettify<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;
|
|
1077
|
+
/**
|
|
1078
|
+
* Enforce no overlapping keys between two objects.
|
|
1079
|
+
*/
|
|
1080
|
+
type NoOverlap<A, B> = B & Record<Extract<keyof A, keyof B>, never>;
|
|
1081
|
+
//#endregion
|
|
1082
|
+
//#region src/internal/logger.d.ts
|
|
1083
|
+
interface Logger {
|
|
1084
|
+
debug: (message: string, context?: Record<string, unknown>) => void;
|
|
1085
|
+
error: {
|
|
1086
|
+
<T extends Error>(error: T, context?: Record<string, unknown>): void;
|
|
1087
|
+
<T extends string>(error: T, context?: Record<string, unknown>): void;
|
|
1088
|
+
};
|
|
1089
|
+
info: (message: string, context?: Record<string, unknown>) => void;
|
|
1090
|
+
warn: (message: string, context?: Record<string, unknown>) => void;
|
|
1091
|
+
}
|
|
1092
|
+
//#endregion
|
|
1093
|
+
//#region src/internal/config.d.ts
|
|
1094
|
+
/**
|
|
1095
|
+
* Global configuration for all stores.
|
|
1096
|
+
*/
|
|
1097
|
+
type StoresConfig = {
|
|
1098
|
+
/**
|
|
1099
|
+
* Custom logger for debug output. Defaults to a no-op logger in production.
|
|
1100
|
+
*/
|
|
1101
|
+
logger: Logger;
|
|
1102
|
+
/**
|
|
1103
|
+
* Default options used by all query stores.
|
|
1104
|
+
*/
|
|
1105
|
+
queryStoreDefaults: QueryStoreDefaults;
|
|
1106
|
+
/**
|
|
1107
|
+
* Storage backend for persisted stores. Defaults to `localStorage` in browsers,
|
|
1108
|
+
* MMKV in React Native.
|
|
1109
|
+
*/
|
|
1110
|
+
storage: AsyncStorageInterface | SyncStorageInterface;
|
|
1111
|
+
/**
|
|
1112
|
+
* Prefix for storage keys built by the default storage adapter.
|
|
1113
|
+
* Should include a delimiter, e.g., `'myapp:'`.
|
|
1114
|
+
* @default 'stores:'
|
|
1115
|
+
*/
|
|
1116
|
+
storageKeyPrefix: string;
|
|
1117
|
+
/**
|
|
1118
|
+
* Sync engine for cross-client state synchronization. Defaults to cross-tab sync
|
|
1119
|
+
* in browsers, no-op in other environments.
|
|
1120
|
+
*/
|
|
1121
|
+
syncEngine: SyncEngine;
|
|
1122
|
+
};
|
|
1123
|
+
type QueryStoreDefaults = Prettify<ConfigDefaults<QueryStoreConfig<unknown, Record<string, unknown>>, "disableCache" | "enabled" | "params", "onError" | "retry" | "retryDelay">> & {
|
|
1124
|
+
/**
|
|
1125
|
+
* Minimum stale time for auto-refetching query stores under which to log warnings in development.
|
|
1126
|
+
* `false` disables warnings.
|
|
1127
|
+
* @default false
|
|
1128
|
+
*/
|
|
1129
|
+
minStaleTime?: number | false;
|
|
1130
|
+
};
|
|
1131
|
+
type ConfigDefaults<C, Excluded extends keyof C = never, AllowedFunctions extends keyof C = never> = Omit<{ [K in keyof C as K extends AllowedFunctions ? K : NonFunction<C[K]> extends undefined ? never : K]?: K extends AllowedFunctions ? C[K] : NonFunction<C[K]> }, Excluded>;
|
|
1132
|
+
/**
|
|
1133
|
+
* Configures global defaults for all stores.
|
|
1134
|
+
*
|
|
1135
|
+
* If used, must be called before creating any stores.
|
|
1136
|
+
*
|
|
1137
|
+
* @see {@link StoresConfig}
|
|
1138
|
+
*
|
|
1139
|
+
* @example
|
|
1140
|
+
* ```ts
|
|
1141
|
+
* configureStores({
|
|
1142
|
+
* logger: { debug: console.debug, error: console.error },
|
|
1143
|
+
* storageKeyPrefix: 'myapp:',
|
|
1144
|
+
* });
|
|
1145
|
+
* ```
|
|
1146
|
+
*/
|
|
1147
|
+
declare function configureStores(config: Partial<StoresConfig>): void;
|
|
1148
|
+
//#endregion
|
|
1149
|
+
//#region src/internal/errors.d.ts
|
|
1150
|
+
/**
|
|
1151
|
+
* Error reported or thrown by the stores package itself.
|
|
1152
|
+
*
|
|
1153
|
+
* If an underlying thrown value caused the failure, it is available as `cause`.
|
|
1154
|
+
*/
|
|
1155
|
+
declare class StoresError extends Error {
|
|
1156
|
+
cause?: unknown;
|
|
1157
|
+
constructor(message: string, cause?: unknown);
|
|
1158
|
+
}
|
|
1159
|
+
//#endregion
|
|
1160
|
+
//#region src/internal/queryStore/queryStoreDefaults.d.ts
|
|
1161
|
+
/**
|
|
1162
|
+
* Exponential backoff: starts at `baseDelay` (5s), doubles each retry, capped at `maxDelay` (5m).
|
|
1163
|
+
*/
|
|
1164
|
+
declare function defaultRetryDelay(retryCount: number): number;
|
|
1165
|
+
//#endregion
|
|
1166
|
+
//#region src/store/stateUpdate.d.ts
|
|
1167
|
+
/**
|
|
1168
|
+
* Applies a `setState` payload to the current state.
|
|
1169
|
+
*/
|
|
1170
|
+
declare function applyStateUpdate<S>(state: S, update: SetPartial<S>, replace?: boolean): S;
|
|
1171
|
+
//#endregion
|
|
1172
|
+
//#region src/utils/serialization.d.ts
|
|
1173
|
+
declare function replacer(_: string, value: unknown): unknown;
|
|
1174
|
+
declare function reviver(_: string, value: unknown): unknown;
|
|
1175
|
+
//#endregion
|
|
1176
|
+
//#region src/internal/storeUtils.d.ts
|
|
1177
|
+
/**
|
|
1178
|
+
* Calls the appropriate reset or destroy method on the store, if available.
|
|
1179
|
+
* Handles both `DerivedStore` and `QueryStore`.
|
|
1180
|
+
*/
|
|
1181
|
+
declare function destroyStore(store: BaseStore<unknown> | StoreApi<unknown> | QueryStore<unknown, Record<string, unknown>, unknown>, options?: {
|
|
1182
|
+
clearQueryCache?: boolean;
|
|
1183
|
+
}): void;
|
|
1184
|
+
declare function destroyStores(stores: Partial<Record<string, BaseStore<unknown> | StoreApi<unknown>>> | (BaseStore<unknown> | StoreApi<unknown> | undefined)[], options?: {
|
|
1185
|
+
clearQueryCache?: boolean;
|
|
1186
|
+
skipDestroy?: (store: BaseStore<unknown> | StoreApi<unknown>) => boolean;
|
|
1187
|
+
}): void;
|
|
1188
|
+
/**
|
|
1189
|
+
* Returns the name of the store, either from the `persist` options or the store itself.
|
|
1190
|
+
*/
|
|
1191
|
+
declare function getStoreName(store: BaseStore<unknown>): string;
|
|
1192
|
+
/**
|
|
1193
|
+
* Checks if a store is a `DerivedStore` and reveals its internal `getSnapshot` method.
|
|
1194
|
+
*/
|
|
1195
|
+
declare function hasGetSnapshot<T extends BaseStore<unknown> | StoreApi<unknown>>(store: T): store is T & {
|
|
1196
|
+
getSnapshot: () => InferStoreState<T>;
|
|
1197
|
+
};
|
|
1198
|
+
/**
|
|
1199
|
+
* Checks if a store is a `QueryStore`.
|
|
1200
|
+
*/
|
|
1201
|
+
declare function isQueryStore<T extends object>(store: T): store is Extract<T, BaseStore<QueryStoreState<unknown, Record<string, unknown>, unknown>>>;
|
|
1202
|
+
/**
|
|
1203
|
+
* Checks if a store is a `DerivedStore`.
|
|
1204
|
+
*/
|
|
1205
|
+
declare function isDerivedStore<T extends BaseStore<unknown> | StoreApi<unknown>>(store: T): store is T & {
|
|
1206
|
+
destroy: () => void;
|
|
1207
|
+
flushUpdates: () => void;
|
|
1208
|
+
};
|
|
1209
|
+
/**
|
|
1210
|
+
* Checks if a store is persisted.
|
|
1211
|
+
*/
|
|
1212
|
+
declare function isPersistedStore<T extends BaseStore<unknown> | PersistedStore<unknown>>(store: T): store is T & {
|
|
1213
|
+
persist: PersistedStore<InferStoreState<T>>["persist"];
|
|
1214
|
+
};
|
|
1215
|
+
/**
|
|
1216
|
+
* Checks if a store is a virtual store.
|
|
1217
|
+
*/
|
|
1218
|
+
declare function isVirtualStore<T extends BaseStore<unknown> | StoreApi<unknown>>(store: T): store is T & BaseStore<InferStoreState<T>>;
|
|
1219
|
+
//#endregion
|
|
1220
|
+
//#region src/utils/core.d.ts
|
|
1221
|
+
/**
|
|
1222
|
+
* Returns the argument provided.
|
|
1223
|
+
*/
|
|
1224
|
+
declare function identity<T>(value: T): T;
|
|
1225
|
+
declare function identity<T, _>(value: T): T;
|
|
1226
|
+
/**
|
|
1227
|
+
* Creates a null-prototype object using the runtime-optimal path:
|
|
1228
|
+
* - React Native: direct literal `{ __proto__: null }`
|
|
1229
|
+
* - Web/Node: `Object.create` with a shared, frozen null prototype
|
|
1230
|
+
*/
|
|
1231
|
+
declare function nullObject<T extends Record<string, unknown> | object = Record<string, unknown>>(): T;
|
|
1232
|
+
//#endregion
|
|
1233
|
+
//#region src/internal/createStoreActions.d.ts
|
|
1234
|
+
/**
|
|
1235
|
+
* Given a store instance, produces a new object containing only its actions.
|
|
1236
|
+
*
|
|
1237
|
+
* Intended for export alongside the associated store.
|
|
1238
|
+
*
|
|
1239
|
+
* @param store - The store to create actions for.
|
|
1240
|
+
* @param bundledMethods - Optional extra methods to bundle into the actions object.
|
|
1241
|
+
*
|
|
1242
|
+
* @example
|
|
1243
|
+
* export const useCounterStore = createRainbowStore(set => ({
|
|
1244
|
+
* count: 0,
|
|
1245
|
+
* increment: () => set(state => ({ count: state.count + 1 })),
|
|
1246
|
+
* }));
|
|
1247
|
+
*
|
|
1248
|
+
* export const exampleActions = createStoreActions(useExampleStore);
|
|
1249
|
+
* exampleActions.increment();
|
|
1250
|
+
*/
|
|
1251
|
+
declare function createStoreActions<Store extends StoreApi<unknown>>(store: Store): StoreActions<Store>;
|
|
1252
|
+
declare function createStoreActions<Store extends StoreApi<unknown>, Bundled extends FunctionRecord>(store: Store, bundledMethods: NoOverlap<InferStoreState<Store>, Bundled>): StoreActions<Store> & Bundled;
|
|
1253
|
+
//#endregion
|
|
1254
|
+
//#region src/utils/equality.d.ts
|
|
1255
|
+
/**
|
|
1256
|
+
* **Worklet compatible**
|
|
1257
|
+
*
|
|
1258
|
+
* Performs a deep equality check between two values.
|
|
1259
|
+
*
|
|
1260
|
+
* This function recursively compares two values, checking if they are equal. For objects,
|
|
1261
|
+
* it validates that both have the same keys and that each corresponding value is deeply equal.
|
|
1262
|
+
* For non-objects, it uses strict equality.
|
|
1263
|
+
*
|
|
1264
|
+
* @param obj1 - The first value to compare.
|
|
1265
|
+
* @param obj2 - The second value to compare.
|
|
1266
|
+
* @returns `true` if the values are deeply equal; otherwise, `false`.
|
|
1267
|
+
*/
|
|
1268
|
+
declare function deepEqual<U>(obj1: U, obj2: U): boolean;
|
|
1269
|
+
/**
|
|
1270
|
+
* **Worklet compatible**
|
|
1271
|
+
*
|
|
1272
|
+
* Performs a shallow equality check between two values.
|
|
1273
|
+
*
|
|
1274
|
+
* For non-objects, uses strict equality (===). For objects, checks that both have identical
|
|
1275
|
+
* keys and compares their values using `Object.is` without recursing into nested objects.
|
|
1276
|
+
*
|
|
1277
|
+
* Ideal for preventing re-renders due to top-level object recreation.
|
|
1278
|
+
*
|
|
1279
|
+
* @param obj1 - The first value to compare.
|
|
1280
|
+
* @param obj2 - The second value to compare.
|
|
1281
|
+
* @returns `true` if the values are shallowly equal; otherwise, `false`.
|
|
1282
|
+
*/
|
|
1283
|
+
declare function shallowEqual<U>(obj1: U, obj2: U): boolean;
|
|
1284
|
+
//#endregion
|
|
1285
|
+
//#region src/utils/time.d.ts
|
|
1286
|
+
type TimeInMs = number;
|
|
1287
|
+
type TimeUtils = {
|
|
1288
|
+
/** Returns the input value unchanged, in milliseconds */ms: (ms: number) => TimeInMs; /** Converts seconds to milliseconds */
|
|
1289
|
+
seconds: (seconds: number) => TimeInMs; /** Converts minutes to milliseconds */
|
|
1290
|
+
minutes: (minutes: number) => TimeInMs; /** Converts hours to milliseconds */
|
|
1291
|
+
hours: (hours: number) => TimeInMs; /** Converts days to milliseconds */
|
|
1292
|
+
days: (days: number) => TimeInMs; /** Converts weeks to milliseconds */
|
|
1293
|
+
weeks: (weeks: number) => TimeInMs; /** Represents infinite time */
|
|
1294
|
+
infinity: typeof Infinity; /** Represents zero time */
|
|
1295
|
+
zero: 0;
|
|
1296
|
+
};
|
|
1297
|
+
/**
|
|
1298
|
+
* Worklet-compatible utility object for defining time values.
|
|
1299
|
+
*
|
|
1300
|
+
* All methods convert the input unit to milliseconds.
|
|
1301
|
+
*
|
|
1302
|
+
* @example
|
|
1303
|
+
* time.seconds(5) // 5 seconds
|
|
1304
|
+
* time.minutes(2) // 2 minutes
|
|
1305
|
+
* time.hours(1) // 1 hour
|
|
1306
|
+
* time.days(5) // 5 days
|
|
1307
|
+
* time.weeks(2) // 2 weeks
|
|
1308
|
+
* ––
|
|
1309
|
+
* time.infinity // Infinity
|
|
1310
|
+
* time.zero // 0
|
|
1311
|
+
*/
|
|
1312
|
+
declare const time: TimeUtils;
|
|
1313
|
+
//#endregion
|
|
1314
|
+
//#region src/queryStore/queryKey.d.ts
|
|
1315
|
+
/**
|
|
1316
|
+
* Generates a deterministic query store `queryKey` from the given
|
|
1317
|
+
* key payload, consistent with internally generated keys.
|
|
1318
|
+
*/
|
|
1319
|
+
declare function getQueryKey<TKeyPayload extends Record<string, unknown>>(keyPayload: TKeyPayload): string;
|
|
1320
|
+
/**
|
|
1321
|
+
* Parses a query store `queryKey` into the key payload it encodes.
|
|
1322
|
+
*/
|
|
1323
|
+
declare function parseQueryKey<TKeyPayload extends Record<string, unknown> = Record<string, unknown>>(queryKey: string): TKeyPayload;
|
|
1324
|
+
//#endregion
|
|
1325
|
+
//#region src/createQueryStore.d.ts
|
|
1326
|
+
/**
|
|
1327
|
+
* Creates a persisted, query-enabled store with data fetching capabilities (sync storage).
|
|
1328
|
+
*
|
|
1329
|
+
* @template TQueryFnData - The raw data type returned by the fetcher
|
|
1330
|
+
* @template TParams - Parameters passed to the fetcher function
|
|
1331
|
+
* @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
|
|
1332
|
+
* @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
|
|
1333
|
+
*/
|
|
1334
|
+
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, PersistReturn>;
|
|
1335
|
+
/**
|
|
1336
|
+
* Creates a persisted, query-enabled store with data fetching capabilities (async storage).
|
|
1337
|
+
*
|
|
1338
|
+
* @template TQueryFnData - The raw data type returned by the fetcher
|
|
1339
|
+
* @template TParams - Parameters passed to the fetcher function
|
|
1340
|
+
* @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
|
|
1341
|
+
* @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
|
|
1342
|
+
*/
|
|
1343
|
+
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, PersistReturn>;
|
|
1344
|
+
/**
|
|
1345
|
+
* Creates a persisted, query-enabled store with data fetching capabilities (sync storage).
|
|
1346
|
+
*
|
|
1347
|
+
* @template TQueryFnData - The raw data type returned by the fetcher
|
|
1348
|
+
* @template TParams - Parameters passed to the fetcher function
|
|
1349
|
+
* @template CustomState - User-defined custom store state
|
|
1350
|
+
* @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
|
|
1351
|
+
* @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
|
|
1352
|
+
*/
|
|
1353
|
+
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, PersistReturn>;
|
|
1354
|
+
/**
|
|
1355
|
+
* Creates a persisted, query-enabled store with data fetching capabilities (async storage).
|
|
1356
|
+
*
|
|
1357
|
+
* @template TQueryFnData - The raw data type returned by the fetcher
|
|
1358
|
+
* @template TParams - Parameters passed to the fetcher function
|
|
1359
|
+
* @template CustomState - User-defined custom store state
|
|
1360
|
+
* @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
|
|
1361
|
+
* @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
|
|
1362
|
+
*/
|
|
1363
|
+
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, PersistReturn>;
|
|
1364
|
+
/**
|
|
1365
|
+
* Creates a query-enabled store with data fetching capabilities.
|
|
1366
|
+
*
|
|
1367
|
+
* @template TQueryFnData - The raw data type returned by the fetcher
|
|
1368
|
+
* @template TParams - Parameters passed to the fetcher function
|
|
1369
|
+
* @template CustomState - User-defined custom store state
|
|
1370
|
+
* @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
|
|
1371
|
+
*/
|
|
1372
|
+
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>>;
|
|
1373
|
+
/**
|
|
1374
|
+
* Creates a query-enabled store with data fetching capabilities.
|
|
1375
|
+
*
|
|
1376
|
+
* @template TQueryFnData - The raw data type returned by the fetcher
|
|
1377
|
+
* @template TParams - Parameters passed to the fetcher function
|
|
1378
|
+
* @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
|
|
1379
|
+
*/
|
|
1380
|
+
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>>;
|
|
1381
|
+
/**
|
|
1382
|
+
* Creates a conditionally persisted, query-enabled store with data-fetching capabilities
|
|
1383
|
+
* and custom state (sync storage).
|
|
1384
|
+
*
|
|
1385
|
+
* `options.persist` may be `undefined` – the returned store exposes `persist?`.
|
|
1386
|
+
*
|
|
1387
|
+
* @template TQueryFnData - The raw data type returned by the fetcher
|
|
1388
|
+
* @template TParams - Parameters passed to the fetcher function
|
|
1389
|
+
* @template CustomState - User-defined custom store state
|
|
1390
|
+
* @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
|
|
1391
|
+
* @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
|
|
1392
|
+
*/
|
|
1393
|
+
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>;
|
|
1394
|
+
/**
|
|
1395
|
+
* Creates a conditionally persisted, query-enabled store with data-fetching capabilities
|
|
1396
|
+
* and custom state (async storage).
|
|
1397
|
+
*
|
|
1398
|
+
* `options.persist` may be `undefined` – the returned store exposes `persist?`.
|
|
1399
|
+
*
|
|
1400
|
+
* @template TQueryFnData - The raw data type returned by the fetcher
|
|
1401
|
+
* @template TParams - Parameters passed to the fetcher function
|
|
1402
|
+
* @template CustomState - User-defined custom store state
|
|
1403
|
+
* @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
|
|
1404
|
+
* @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
|
|
1405
|
+
*/
|
|
1406
|
+
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>;
|
|
1407
|
+
/**
|
|
1408
|
+
* Creates a conditionally persisted, query-enabled store with data fetching capabilities (sync storage).
|
|
1409
|
+
*
|
|
1410
|
+
* `options.persist` may be `undefined` – the returned store exposes `persist?`.
|
|
1411
|
+
*
|
|
1412
|
+
* @template TQueryFnData - The raw data type returned by the fetcher
|
|
1413
|
+
* @template TParams - Parameters passed to the fetcher function
|
|
1414
|
+
* @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
|
|
1415
|
+
* @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
|
|
1416
|
+
*/
|
|
1417
|
+
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> | undefined): OptionallyPersistedStore<QueryStoreState<TData, TParams>, PersistedState, PersistReturn>;
|
|
1418
|
+
/**
|
|
1419
|
+
* Creates a conditionally persisted, query-enabled store with data fetching capabilities (async storage).
|
|
1420
|
+
*
|
|
1421
|
+
* `options.persist` may be `undefined` – the returned store exposes `persist?`.
|
|
1422
|
+
*
|
|
1423
|
+
* @template TQueryFnData - The raw data type returned by the fetcher
|
|
1424
|
+
* @template TParams - Parameters passed to the fetcher function
|
|
1425
|
+
* @template TData - The transformed data type, if applicable (defaults to `TQueryFnData`)
|
|
1426
|
+
* @template PersistedState - The persisted state type, if a stricter type than `Partial<CustomState>` is desired
|
|
1427
|
+
*/
|
|
1428
|
+
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> | undefined): OptionallyPersistedStore<QueryStoreState<TData, TParams>, PersistedState, PersistReturn>;
|
|
1429
|
+
//#endregion
|
|
1430
|
+
//#region src/createVirtualStore.d.ts
|
|
1431
|
+
type MethodOverrides<Store extends BaseStore<unknown>> = Partial<Pick<Store, "getState" | "setState">>;
|
|
1432
|
+
type VirtualStore<Store extends BaseStore<unknown>> = OptionallyPersistedStore<InferStoreState<Store>, InferPersistedState<Store>, InferSetStateReturn<Store>>;
|
|
1433
|
+
type VirtualStoreOptions = {
|
|
1434
|
+
debugMode?: boolean;
|
|
1435
|
+
/**
|
|
1436
|
+
* Whether to lock dependencies (see: {@link DeriveOptions}) for the virtual store.
|
|
1437
|
+
* @default true
|
|
1438
|
+
*/
|
|
1439
|
+
lockDependencies?: boolean;
|
|
1440
|
+
};
|
|
1441
|
+
/**
|
|
1442
|
+
* ### `createVirtualStore`
|
|
1443
|
+
*
|
|
1444
|
+
* Returns a stable store interface backed by different store instances over time.
|
|
1445
|
+
* When dependencies change, the derive function runs and creates a new store, then
|
|
1446
|
+
* all subscriptions rebind automatically. Only depend on state that should trigger
|
|
1447
|
+
* new store creation.
|
|
1448
|
+
*
|
|
1449
|
+
* ---
|
|
1450
|
+
* 💡 **Note:** `lockDependencies` (see: {@link DeriveOptions}) is enabled by default.
|
|
1451
|
+
* Ensure that any `$` dependencies in your `createStore` function are called
|
|
1452
|
+
* consistently. If they are not, set `lockDependencies` to `false`.
|
|
1453
|
+
*
|
|
1454
|
+
* ---
|
|
1455
|
+
* @param createStore - Derive function that returns a store instance
|
|
1456
|
+
* @param overrides - Optional method overrides (e.g., `getState(id?: string)`)
|
|
1457
|
+
*
|
|
1458
|
+
* @example
|
|
1459
|
+
* ```ts
|
|
1460
|
+
* const useUserAssetsStore = createVirtualStore($ => {
|
|
1461
|
+
* const address = $(useWalletsStore).accountAddress;
|
|
1462
|
+
* return createUserAssetsStore(address);
|
|
1463
|
+
* });
|
|
1464
|
+
* ```
|
|
1465
|
+
*/
|
|
1466
|
+
declare function createVirtualStore<Store extends BaseStore<InferStoreState<Store>>>(createStore: ($: DeriveGetter) => Store, options?: VirtualStoreOptions): VirtualStore<Store>;
|
|
1467
|
+
declare function createVirtualStore<Store extends BaseStore<InferStoreState<Store>>, Overrides extends MethodOverrides<Store>>(createStore: ($: DeriveGetter) => Store, overrides: (getStore: () => Store) => Overrides, options?: VirtualStoreOptions): VirtualStore<Store> & Overrides;
|
|
1468
|
+
//#endregion
|
|
1469
|
+
export { type AsyncStorageInterface, type BaseStore, type BaseStoreOptions, type CacheEntry, type DebounceOptions, type DeriveGetter, type DeriveOptions, type DerivedStore, type Deserializer, type EnforceStorageKey, type EqualityFn, type FetchOptions, type FieldMetadata, type InferPersistedState, type InferSetStateReturn, type InferStoreState, type InternalStateKeys, type Listener, type ListenerArgs, type NoInfer, type NormalizedSyncConfig, type OnErrorParams, type OnFetchedParams, type OptionallyPersistedStore, type PersistConfig, type PersistedStore, type QueryErrorInfo, type QueryParam, type QueryParamConfig, type QueryParamKey, type QueryStatus, type QueryStatusInfo, QueryStatuses, type QueryStore, type QueryStoreConfig, type QueryStoreInternalState, type QueryStoreParams, type QueryStoreState, type ReactiveParam, type RetryDelay, type RetryFailureParams, type RetryPolicy, type Selector, type SelectorArgs, type Serializer, type SetDataParams, type SetFull, type SetPartial, type SetState, type SetStateArgs, type SetStateOverloads, type SetStatePartialArgs, type SetStateReplaceArgs, type StateCreator, type StorageValue, type Store, type StoreActions, type StoreMutators, type StoreMutatorsWithSelector, StoresError, type SubscribableStore, type SubscribeArgs, type SubscribeFn, type SubscribeOptions, type SubscribeOverloads, type SyncConfig, type SyncEngine, type SyncHandle, type SyncMergeFn, type SyncOption, type SyncRegistration, type SyncStateKey, type SyncStorageInterface, type SyncUpdate, type SyncValues, type Timeout, type UnsubscribeFn, type UseBoundStoreWithEqualityFn, type UseStoreCallSignatures, type WithFlushUpdates, type WithGetSnapshot, applyStateUpdate, configureStores, createBaseStore, createDerivedStore, createQueryStore, createStoreActions, createVirtualStore, deepEqual, defaultRetryDelay, destroyStore, destroyStores, getQueryKey, getStoreName, hasGetSnapshot, identity, isDerivedStore, isPersistedStore, isQueryStore, isVirtualStore, nullObject, parseQueryKey, queryParam, replacer, reviver, shallowEqual, time };
|