@oxog/state 1.3.0 → 1.3.2

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.cts CHANGED
@@ -1,425 +1,5 @@
1
- /**
2
- * Deep partial type for nested optional properties.
3
- *
4
- * @typeParam T - The type to make partially deep
5
- *
6
- * @example
7
- * ```typescript
8
- * type User = {
9
- * name: string;
10
- * profile: { age: number; city: string; };
11
- * };
12
- *
13
- * const partial: DeepPartial<User> = {
14
- * name: 'John',
15
- * profile: { age: 30 } // city is optional
16
- * };
17
- * ```
18
- */
19
- type DeepPartial<T> = T extends object ? {
20
- [P in keyof T]?: DeepPartial<T[P]>;
21
- } : T;
22
- /**
23
- * Action function that receives state and optional arguments, returning a partial state update.
24
- *
25
- * @typeParam TState - The store state type
26
- * @typeParam TArgs - The action argument types tuple
27
- *
28
- * @example
29
- * ```typescript
30
- * type CounterAction = Action<{ count: number }, [number: number]>;
31
- *
32
- * const incrementBy: CounterAction = (state, amount) => ({
33
- * count: state.count + amount
34
- * });
35
- * ```
36
- */
37
- type Action<TState, TArgs extends unknown[] = any[]> = (state: TState, ...args: TArgs) => Partial<TState> | void | Promise<Partial<TState> | void>;
38
- /**
39
- * Collection of actions indexed by name.
40
- *
41
- * @typeParam TState - The store state type
42
- *
43
- * @example
44
- * ```typescript
45
- * const actions: Actions<{ count: number }> = {
46
- * increment: (state) => ({ count: state.count + 1 }),
47
- * decrement: (state) => ({ count: state.count - 1 })
48
- * };
49
- * ```
50
- */
51
- type Actions<TState> = Record<string, Action<TState, any[]>>;
52
- /**
53
- * The bound form of an action: the `state` argument is supplied by the store.
54
- *
55
- * @example
56
- * ```typescript
57
- * type Fn = BoundAction<(state: { n: number }, by: number) => { n: number }>;
58
- * // (by: number) => { n: number }
59
- * ```
60
- */
61
- type BoundAction<F> = F extends (state: any, ...args: infer A) => infer R ? (...args: A) => R : never;
62
- /**
63
- * Bound versions of a map of actions.
64
- */
65
- type BoundActions<TActions> = {
66
- [K in keyof TActions]: BoundAction<TActions[K]>;
67
- };
68
- /**
69
- * Bound versions of the inline (`$`-prefixed) actions of an initial state,
70
- * keyed without the `$` prefix.
71
- */
72
- type InlineActions<T> = {
73
- [K in keyof T as K extends `$${infer Name}` ? T[K] extends (...args: any[]) => any ? Name : never : never]: BoundAction<T[K]>;
74
- };
75
- /**
76
- * An initial state without its inline (`$`-prefixed) action functions.
77
- */
78
- type StateWithoutInlineActions<T> = [Extract<keyof T, `$${string}`>] extends [never] ? T : {
79
- [K in keyof T as K extends `$${string}` ? T[K] extends (...args: any[]) => any ? never : K : K]: T[K];
80
- };
81
- /**
82
- * The state type of a store created from `initialState` and `actions`:
83
- * data plus every bound action.
84
- */
85
- type StateWithActions<T, TActions = {}> = [Extract<keyof T, `$${string}`>] extends [never] ? [keyof TActions] extends [never] ? T : T & BoundActions<TActions> : StateWithoutInlineActions<T> & InlineActions<T> & BoundActions<TActions>;
86
- /**
87
- * The store returned by `createStore`: the store API plus every bound action
88
- * as a method.
89
- */
90
- type CreatedStore<T, TActions = {}> = StoreBuilder<StateWithActions<T, TActions>> & InlineActions<T> & BoundActions<TActions>;
91
- /**
92
- * Selector function to extract a slice of state.
93
- *
94
- * @typeParam TState - The store state type
95
- * @typeParam TSelected - The selected value type
96
- *
97
- * @example
98
- * ```typescript
99
- * const selectCount: Selector<{ count: number; name: string }, number> =
100
- * (state) => state.count;
101
- * ```
102
- */
103
- type Selector<TState, TSelected> = (state: TState) => TSelected;
104
- /**
105
- * Equality function for comparing two values.
106
- *
107
- * @typeParam T - The type to compare
108
- *
109
- * @example
110
- * ```typescript
111
- * const shallowEquality: EqualityFn<{ a: number }> = (a, b) =>
112
- * a.a === b.a;
113
- * ```
114
- */
115
- type EqualityFn<T> = (a: T, b: T) => boolean;
116
- /**
117
- * Listener function called when state changes.
118
- *
119
- * @typeParam TState - The store state type
120
- *
121
- * @example
122
- * ```typescript
123
- * const listener: Listener<{ count: number }> = (state, prevState) => {
124
- * console.log(`Count changed from ${prevState.count} to ${state.count}`);
125
- * };
126
- * ```
127
- */
128
- type Listener<TState> = (state: TState, prevState: TState) => void;
129
- /**
130
- * Storage interface for persisting state.
131
- *
132
- * @example
133
- * ```typescript
134
- * const sessionStorage: StorageLike = {
135
- * getItem: (key) => sessionStorage.getItem(key),
136
- * setItem: (key, value) => sessionStorage.setItem(key, value),
137
- * removeItem: (key) => sessionStorage.removeItem(key)
138
- * };
139
- * ```
140
- */
141
- interface StorageLike$1 {
142
- /** Get an item from storage */
143
- getItem(key: string): string | null;
144
- /** Set an item in storage */
145
- setItem(key: string, value: string): void;
146
- /** Remove an item from storage */
147
- removeItem(key: string): void;
148
- }
149
- /**
150
- * Store configuration options.
151
- *
152
- * @typeParam TState - The store state type
153
- *
154
- * @example
155
- * ```typescript
156
- * const options: StoreOptions<{ count: number }> = {
157
- * name: 'Counter',
158
- * devtools: true
159
- * };
160
- * ```
161
- */
162
- interface StoreOptions<TState> {
163
- /** Initial state */
164
- initialState: TState;
165
- /** Store name for debugging */
166
- name?: string;
167
- /** Enable/disable devtools (default: true in development) */
168
- devtools?: boolean;
169
- }
170
- /**
171
- * Plugin interface for extending store functionality.
172
- *
173
- * @typeParam TState - The store state type
174
- *
175
- * @example
176
- * ```typescript
177
- * const loggerPlugin: Plugin<{ count: number }> = {
178
- * name: 'logger',
179
- * version: '1.0.0',
180
- * install(store) {
181
- * store.subscribe((state) => console.log('State:', state));
182
- * }
183
- * };
184
- * ```
185
- */
186
- interface Plugin<TState = unknown> {
187
- /** Unique plugin identifier (kebab-case) */
188
- name: string;
189
- /** Semantic version (e.g., "1.0.0") */
190
- version: string;
191
- /** Other plugins this plugin depends on */
192
- dependencies?: string[];
193
- /**
194
- * Called when plugin is registered.
195
- *
196
- * @param store - The store instance
197
- * @param options - Plugin-specific options
198
- */
199
- install: (store: Store<TState>, options?: unknown) => void;
200
- /**
201
- * Called after all plugins are installed.
202
- *
203
- * @param store - The store instance
204
- */
205
- onInit?: (store: Store<TState>) => void | Promise<void>;
206
- /**
207
- * Called when plugin is unregistered.
208
- */
209
- onDestroy?: () => void | Promise<void>;
210
- /**
211
- * Called on state change.
212
- *
213
- * @param state - New state
214
- * @param prevState - Previous state
215
- */
216
- onStateChange?: (state: TState, prevState: TState) => void;
217
- /**
218
- * Called on error in store.
219
- *
220
- * @param error - The error that occurred
221
- */
222
- onError?: (error: Error) => void;
223
- }
224
- /**
225
- * Store instance with state management methods.
226
- *
227
- * @typeParam TState - The store state type
228
- *
229
- * @example
230
- * ```typescript
231
- * const store: Store<{ count: number }> = createStore({ count: 0 });
232
- * const state = store.getState(); // { count: 0 }
233
- * store.setState({ count: 1 });
234
- * ```
235
- */
236
- interface Store<TState> {
237
- /** Get current state snapshot */
238
- getState(): TState;
239
- /**
240
- * Update state with partial object or function.
241
- *
242
- * @param partial - Partial state or updater function
243
- *
244
- * @example
245
- * ```typescript
246
- * store.setState({ count: 10 });
247
- * store.setState((state) => ({ count: state.count + 1 }));
248
- * ```
249
- */
250
- setState(partial: Partial<TState> | ((state: TState) => Partial<TState>)): void;
251
- /**
252
- * Deep merge state.
253
- *
254
- * @param partial - Partial state to merge
255
- *
256
- * @example
257
- * ```typescript
258
- * store.merge({ user: { name: 'John' } });
259
- * ```
260
- */
261
- merge(partial: DeepPartial<TState>): void;
262
- /** Reset to initial state */
263
- reset(): void;
264
- /**
265
- * Subscribe to state changes.
266
- *
267
- * @param listener - Function called on state changes
268
- * @returns Unsubscribe function
269
- *
270
- * @example
271
- * ```typescript
272
- * const unsubscribe = store.subscribe((state) => console.log(state));
273
- * unsubscribe();
274
- * ```
275
- */
276
- subscribe(listener: Listener<TState>): () => void;
277
- /**
278
- * Subscribe to state changes with selector.
279
- *
280
- * @param selector - Function to extract state slice
281
- * @param listener - Function called when selected value changes
282
- * @param equalityFn - Optional custom equality function
283
- * @returns Unsubscribe function
284
- *
285
- * @example
286
- * ```typescript
287
- * const unsubscribe = store.subscribe(
288
- * (state) => state.count,
289
- * (count) => console.log('Count:', count)
290
- * );
291
- * ```
292
- */
293
- subscribe<TSelected>(selector: Selector<TState, TSelected>, listener: Listener<TSelected>, equalityFn?: EqualityFn<TSelected>): () => void;
294
- /**
295
- * Register a plugin.
296
- *
297
- * @param plugin - The plugin to register
298
- * @param options - Plugin-specific options
299
- * @returns The store instance for chaining
300
- *
301
- * @example
302
- * ```typescript
303
- * store.use(persist({ key: 'app' }));
304
- * ```
305
- */
306
- use(plugin: Plugin<TState>, options?: unknown): this;
307
- /** Destroy store and cleanup all resources */
308
- destroy(): void;
309
- }
310
- /**
311
- * Store builder interface for fluent API.
312
- *
313
- * @typeParam TState - The store state type
314
- *
315
- * @example
316
- * ```typescript
317
- * createStore({ count: 0 })
318
- * .action('increment', (s) => ({ count: s.count + 1 }))
319
- * .action('decrement', (s) => ({ count: s.count - 1 }));
320
- * ```
321
- */
322
- interface StoreBuilder<TState> extends Store<TState> {
323
- /**
324
- * Add an action to the store.
325
- *
326
- * @param name - Action name
327
- * @param fn - Action function
328
- * @returns The builder for chaining
329
- */
330
- action<K extends string, F extends Action<TState, any[]>>(name: K, fn: F): this & {
331
- [P in K]: BoundAction<F>;
332
- };
333
- }
334
- /**
335
- * Error codes for store errors.
336
- */
337
- declare enum StoreErrorCode {
338
- /** Store was destroyed and cannot be used */
339
- STORE_DESTROYED = "STORE_DESTROYED",
340
- /** Plugin with same name already registered */
341
- PLUGIN_EXISTS = "PLUGIN_EXISTS",
342
- /** Required plugin dependency not found */
343
- PLUGIN_DEPENDENCY_MISSING = "PLUGIN_DEPENDENCY_MISSING",
344
- /** Invalid state update argument */
345
- INVALID_STATE_UPDATE = "INVALID_STATE_UPDATE",
346
- /** Action threw an error */
347
- ACTION_ERROR = "ACTION_ERROR"
348
- }
349
- /**
350
- * Store error class.
351
- */
352
- declare class StoreError extends Error {
353
- code: StoreErrorCode;
354
- constructor(code: StoreErrorCode, message: string);
355
- }
356
-
357
- /**
358
- * Batch multiple state updates into a single notification.
359
- *
360
- * This reduces the number of subscriber notifications when making multiple
361
- * state updates in sequence. All updates within the batch function will
362
- * result in only one notification to subscribers.
363
- *
364
- * @param fn - Function containing state updates
365
- * @returns The return value of fn
366
- *
367
- * @example
368
- * ```typescript
369
- * import { batch, createStore } from '@oxog/state';
370
- *
371
- * const store = createStore({ count: 0, name: '' });
372
- *
373
- * // Without batch - 3 re-renders in React
374
- * store.setState({ count: 1 });
375
- * store.setState({ count: 2 });
376
- * store.setState({ name: 'John' });
377
- *
378
- * // With batch - 1 re-render in React
379
- * batch(() => {
380
- * store.setState({ count: 1 });
381
- * store.setState({ count: 2 });
382
- * store.setState({ name: 'John' });
383
- * });
384
- * ```
385
- */
386
- declare function batch<T>(fn: () => T): T;
387
-
388
- /**
389
- * Create a new reactive store.
390
- *
391
- * Supports three action definition styles:
392
- * - **Inline**: Actions defined within state object (functions starting with $)
393
- * - **Separate**: Actions passed as second argument
394
- * - **Fluent**: Actions added via `.action()` method
395
- *
396
- * @typeParam TState - The type of the store state
397
- * @param initialState - Initial state object, may include inline actions
398
- * @param actions - Optional separate actions object
399
- * @returns A new Store instance
400
- *
401
- * @example
402
- * ```typescript
403
- * // Style A: Inline actions (prefix with $)
404
- * const store = createStore({
405
- * count: 0,
406
- * $increment: (state) => ({ count: state.count + 1 }),
407
- * });
408
- *
409
- * // Style B: Separate actions
410
- * const store = createStore(
411
- * { count: 0 },
412
- * { increment: (state) => ({ count: state.count + 1 }) }
413
- * );
414
- *
415
- * // Style C: Fluent builder
416
- * const store = createStore({ count: 0 })
417
- * .action('increment', (state) => ({ count: state.count + 1 }));
418
- * ```
419
- */
420
- declare function createStore<TState, TActions extends {
421
- [K in keyof TActions]: Action<TState, any[]>;
422
- } = {}>(initialState: TState, actions?: TActions & Record<string, Action<TState, any[]>>): CreatedStore<TState, TActions>;
1
+ import { Store, Selector, EqualityFn } from './vanilla.cjs';
2
+ export { Action, Actions, BoundAction, BoundActions, Computed, ComputedOptions, CreatedStore, DeepPartial, DevtoolsOptions, EffectCleanup, EffectDefinition, EffectFn, EffectUtils, EffectsOptions, EqualityCheck, ExtractStateType, FederatedState, Federation, FederationListener, FederationOptions, GetSlice, HistoryOptions, HistoryStore, InlineActions, Listener, LogLevel, LoggerOptions, MiddlewareFn, MiddlewareGetState, MiddlewareSetState, MiddlewareStoreApi, MiddlewareSubscribe, MockStorage, MockedAction, PersistOptions, Plugin, SelectorFn, SelectorOptions, SetSlice, SliceCreator, SliceDefinition, StateAssertion, StateChange, StateCreatorFn, StateWithActions, StateWithoutInlineActions, StorageLike, StoreBuilder, StoreError, StoreError as StoreErrorClass, StoreErrorCode, StoreOptions, StoreSpy, StoreState, SubscribeOptions, SyncOptions, TestStore, TestStoreOptions, TransactionFn, ValidateOptions, ValidationAPI, ValidationError, ValidationResult, ValidationTiming, ValidatorFn, assertState, batch, combineComputed, combineEffects, combineSlices, combineValidators, compose, computed, createAsyncValidator, createDebouncedEffect, createEffect, createFederatedComputed, createFederatedSelector, createFederation, createFieldValidator, createLogger, createMockStorage, createNamespacedSlice, createSimpleEffect, createSimpleMiddleware, createSlice, createStorage, createStore, createSubscriber, createTestStore, createValidator, createWithMiddleware, deepClone, deepEqual, deepMerge, delay, devtools, effects, extendStore, flushMicrotasks, hasHistory, history, identity, immer, isFunction, logger, memoizeSelector, middlewareCompat, mockAction, omit, persist, pick, produce, resetSlices, selector, sessionStorage, shallowEqual, snapshot, spyOnStore, stateDiff, subscribeOnce, subscribeToMany, subscribeWithOptions, sync, toMiddlewareApi, triggerSync, validate, waitForFederated } from './vanilla.cjs';
423
3
 
424
4
  /**
425
5
  * React hook for subscribing to store state changes.
@@ -670,2189 +250,4 @@ declare function useTransientSubscribe<TState, TSelected>(store: Store<TState>,
670
250
  */
671
251
  declare function useSetState<TState>(store: Store<TState>): (partial: Partial<TState> | ((state: TState) => Partial<TState>)) => void;
672
252
 
673
- /**
674
- * Enhanced subscription system with advanced options.
675
- *
676
- * @module subscribe
677
- */
678
-
679
- /**
680
- * Options for enhanced subscriptions.
681
- *
682
- * @typeParam T - The store state type
683
- * @typeParam U - The selected value type
684
- *
685
- * @example
686
- * ```typescript
687
- * const options: SubscribeOptions<State, number> = {
688
- * debounce: 100,
689
- * fireImmediately: true,
690
- * when: (state) => state.isReady
691
- * };
692
- * ```
693
- */
694
- interface SubscribeOptions<T, U = T> {
695
- /** Custom equality function for comparing selected values */
696
- equalityFn?: EqualityFn<U>;
697
- /** Fire callback immediately with current state */
698
- fireImmediately?: boolean;
699
- /** Debounce notifications (ms) */
700
- debounce?: number;
701
- /** Throttle notifications (ms) */
702
- throttle?: number;
703
- /** Only fire when condition is met */
704
- when?: (state: T, prevState: T) => boolean;
705
- }
706
- /**
707
- * Enhanced subscribe function with advanced options.
708
- *
709
- * @param store - The store to subscribe to
710
- * @param selectorOrListener - Selector function or direct listener
711
- * @param listenerOrOptions - Listener function or options (if no selector)
712
- * @param options - Subscription options
713
- * @returns Unsubscribe function
714
- *
715
- * @example
716
- * ```typescript
717
- * // With debounce
718
- * const unsubscribe = subscribeWithOptions(
719
- * store,
720
- * (state) => state.searchQuery,
721
- * (query) => performSearch(query),
722
- * { debounce: 300 }
723
- * );
724
- *
725
- * // With throttle and condition
726
- * const unsubscribe = subscribeWithOptions(
727
- * store,
728
- * (state) => state.scrollPosition,
729
- * (pos) => updateUI(pos),
730
- * { throttle: 16, when: (state) => state.isVisible }
731
- * );
732
- *
733
- * // Fire immediately
734
- * const unsubscribe = subscribeWithOptions(
735
- * store,
736
- * (state) => state.user,
737
- * (user) => console.log('User:', user),
738
- * { fireImmediately: true }
739
- * );
740
- * ```
741
- */
742
- declare function subscribeWithOptions<TState, TSelected>(store: Store<TState>, selector: Selector<TState, TSelected>, listener: Listener<TSelected>, options?: SubscribeOptions<TState, TSelected>): () => void;
743
- /**
744
- * Create a subscription factory with preset options.
745
- *
746
- * @param defaultOptions - Default options for all subscriptions
747
- * @returns A subscribe function with preset options
748
- *
749
- * @example
750
- * ```typescript
751
- * const debouncedSubscribe = createSubscriber({ debounce: 100 });
752
- *
753
- * const unsubscribe = debouncedSubscribe(
754
- * store,
755
- * (state) => state.input,
756
- * (input) => validate(input)
757
- * );
758
- * ```
759
- */
760
- declare function createSubscriber<TState = any>(defaultOptions?: SubscribeOptions<TState, any>): <S extends TState, TSelected>(store: Store<S>, selector: Selector<S, TSelected>, listener: Listener<TSelected>, options?: SubscribeOptions<S, TSelected>) => () => void;
761
- /**
762
- * Subscribe to multiple selectors with a single listener.
763
- *
764
- * @param store - The store to subscribe to
765
- * @param selectors - Object of named selectors
766
- * @param listener - Listener called when any selector value changes
767
- * @param options - Subscription options
768
- * @returns Unsubscribe function
769
- *
770
- * @example
771
- * ```typescript
772
- * const unsubscribe = subscribeToMany(
773
- * store,
774
- * {
775
- * count: (s) => s.count,
776
- * name: (s) => s.name,
777
- * },
778
- * ({ count, name }) => console.log(`${name}: ${count}`)
779
- * );
780
- * ```
781
- */
782
- declare function subscribeToMany<TState, TSelectors extends Record<string, Selector<TState, any>>>(store: Store<TState>, selectors: TSelectors, listener: (values: {
783
- [K in keyof TSelectors]: ReturnType<TSelectors[K]>;
784
- }) => void, options?: Omit<SubscribeOptions<TState, any>, 'equalityFn'>): () => void;
785
- /**
786
- * Subscribe only once - automatically unsubscribes after first call.
787
- *
788
- * @param store - The store to subscribe to
789
- * @param selector - Selector function
790
- * @param listener - Listener called once when value changes
791
- * @param options - Subscription options
792
- * @returns Unsubscribe function (can be called to cancel before trigger)
793
- *
794
- * @example
795
- * ```typescript
796
- * // Wait for user to be loaded
797
- * subscribeOnce(
798
- * store,
799
- * (state) => state.user,
800
- * (user) => console.log('User loaded:', user),
801
- * { when: (state) => state.user !== null }
802
- * );
803
- * ```
804
- */
805
- declare function subscribeOnce<TState, TSelected>(store: Store<TState>, selector: Selector<TState, TSelected>, listener: Listener<TSelected>, options?: SubscribeOptions<TState, TSelected>): () => void;
806
-
807
- /**
808
- * Computed values (derived state) with memoization.
809
- *
810
- * @module computed
811
- */
812
-
813
- /**
814
- * Options for computed values.
815
- *
816
- * @typeParam _TState - The store state type (unused, kept for compatibility)
817
- * @typeParam U - The computed value type
818
- */
819
- interface ComputedOptions<_TState, U> {
820
- /** Custom equality for caching */
821
- equals?: EqualityFn<U>;
822
- /** Lazy evaluation (only compute when accessed) */
823
- lazy?: boolean;
824
- /** Keep last N values in cache for time-travel debugging */
825
- cacheSize?: number;
826
- }
827
- /**
828
- * Computed value interface with getter and utilities.
829
- */
830
- interface Computed<U> {
831
- /** Get the computed value */
832
- (): U;
833
- /** Get value (alias) */
834
- get(): U;
835
- /** Force recomputation */
836
- invalidate(): void;
837
- /** Subscribe to value changes */
838
- subscribe(listener: (value: U, prevValue: U) => void): () => void;
839
- /** Get cache history (if cacheSize > 1) */
840
- getHistory(): U[];
841
- /** Destroy and cleanup */
842
- destroy(): void;
843
- }
844
- /**
845
- * Create a computed (derived) value from store state.
846
- *
847
- * Computed values are memoized and only recompute when dependencies change.
848
- *
849
- * @param store - The store to derive from
850
- * @param selector - Function to compute the derived value
851
- * @param options - Computed options
852
- * @returns A computed value accessor
853
- *
854
- * @example
855
- * ```typescript
856
- * const store = createStore({ items: [], filter: 'all' });
857
- *
858
- * // Simple computed
859
- * const filteredItems = computed(store, (state) => {
860
- * if (state.filter === 'all') return state.items;
861
- * return state.items.filter(item => item.status === state.filter);
862
- * });
863
- *
864
- * console.log(filteredItems()); // Get computed value
865
- *
866
- * // With caching for debugging
867
- * const total = computed(
868
- * store,
869
- * (state) => state.items.reduce((sum, item) => sum + item.price, 0),
870
- * { cacheSize: 10 }
871
- * );
872
- *
873
- * console.log(total.getHistory()); // See past values
874
- * ```
875
- */
876
- declare function computed<TState, TComputed>(store: Store<TState>, selector: Selector<TState, TComputed>, options?: ComputedOptions<TState, TComputed>): Computed<TComputed>;
877
- /**
878
- * Create a computed value that depends on other computed values.
879
- *
880
- * @param computeds - Array of computed values to depend on
881
- * @param combiner - Function to combine the computed values
882
- * @param options - Computed options
883
- * @returns A combined computed value
884
- *
885
- * @example
886
- * ```typescript
887
- * const subtotal = computed(store, (s) => s.items.reduce((sum, i) => sum + i.price, 0));
888
- * const tax = computed(store, (s) => s.taxRate);
889
- *
890
- * const total = combineComputed(
891
- * [subtotal, tax],
892
- * ([subtotalVal, taxVal]) => subtotalVal * (1 + taxVal)
893
- * );
894
- *
895
- * console.log(total()); // Subtotal + tax
896
- * ```
897
- */
898
- declare function combineComputed<TInputs extends Computed<any>[], TOutput>(computeds: [...TInputs], combiner: (values: {
899
- [K in keyof TInputs]: TInputs[K] extends Computed<infer U> ? U : never;
900
- }) => TOutput, options?: Omit<ComputedOptions<any, TOutput>, 'lazy'>): Computed<TOutput>;
901
- /**
902
- * Create a memoized selector for use with store.subscribe.
903
- *
904
- * @param selector - The selector function to memoize
905
- * @param equals - Custom equality function
906
- * @returns A memoized selector
907
- *
908
- * @example
909
- * ```typescript
910
- * const selectExpensiveComputation = memoizeSelector(
911
- * (state: State) => expensiveOperation(state.data)
912
- * );
913
- *
914
- * store.subscribe(selectExpensiveComputation, (result) => {
915
- * console.log('Result:', result);
916
- * });
917
- * ```
918
- */
919
- declare function memoizeSelector<TState, TSelected>(selector: Selector<TState, TSelected>, equals?: EqualityFn<TSelected>): Selector<TState, TSelected>;
920
-
921
- /**
922
- * Slices pattern for modular store composition.
923
- *
924
- * @module slices
925
- */
926
-
927
- /**
928
- * SetSlice function type for updating slice state.
929
- */
930
- type SetSlice<TState> = (partial: Partial<TState> | ((state: TState) => Partial<TState>)) => void;
931
- /**
932
- * GetSlice function type for getting current state.
933
- */
934
- type GetSlice<TState> = () => TState;
935
- /**
936
- * Slice creator function signature.
937
- *
938
- * @typeParam TState - The full store state type
939
- * @typeParam TSlice - The slice state type
940
- */
941
- type SliceCreator<TState, TSlice extends Partial<TState>> = (set: SetSlice<TState>, get: GetSlice<TState>, store: Store<TState>) => TSlice;
942
- /**
943
- * Slice definition with state and actions.
944
- */
945
- interface SliceDefinition<TState, TSlice extends Partial<TState>> {
946
- /** Slice name for debugging */
947
- name: string;
948
- /** Slice creator function */
949
- creator: SliceCreator<TState, TSlice>;
950
- }
951
- /**
952
- * Create a slice definition for use with combineSlices.
953
- *
954
- * Slices are modular pieces of state and actions that can be combined
955
- * to create a complete store.
956
- *
957
- * @param name - Slice name for debugging
958
- * @param creator - Slice creator function
959
- * @returns A slice definition
960
- *
961
- * @example
962
- * ```typescript
963
- * // Define a counter slice
964
- * const counterSlice = createSlice('counter', (set, get) => ({
965
- * count: 0,
966
- * increment: () => set((s) => ({ count: s.count + 1 })),
967
- * decrement: () => set((s) => ({ count: s.count - 1 })),
968
- * reset: () => set({ count: 0 }),
969
- * }));
970
- *
971
- * // Define a user slice
972
- * const userSlice = createSlice('user', (set, get) => ({
973
- * user: null as User | null,
974
- * setUser: (user: User) => set({ user }),
975
- * logout: () => set({ user: null }),
976
- * }));
977
- *
978
- * // Combine slices into a store
979
- * const store = combineSlices(counterSlice, userSlice);
980
- *
981
- * // Use the store
982
- * store.increment();
983
- * store.setUser({ name: 'John' });
984
- * ```
985
- */
986
- declare function createSlice<TState = any, TSlice extends Partial<TState> = Partial<TState>>(name: string, creator: SliceCreator<TState, TSlice>): SliceDefinition<TState, TSlice>;
987
- /**
988
- * Internal slice creator type for type inference.
989
- */
990
- type InferSlice<T> = T extends SliceDefinition<any, infer S> ? S : never;
991
- /**
992
- * Combined state type from multiple slices.
993
- */
994
- type UnionToIntersection<U> = (U extends unknown ? (value: U) => void : never) extends (value: infer I) => void ? I : never;
995
- type CombinedState<TSlices extends SliceDefinition<any, any>[]> = UnionToIntersection<{
996
- [K in keyof TSlices]: InferSlice<TSlices[K]>;
997
- }[number]> extends infer I ? {
998
- [K in keyof I]: I[K];
999
- } : never;
1000
- /**
1001
- * Combine multiple slices into a single store.
1002
- *
1003
- * @param slices - Slice definitions to combine
1004
- * @returns A store with combined state and actions
1005
- *
1006
- * @example
1007
- * ```typescript
1008
- * const counterSlice = createSlice('counter', (set) => ({
1009
- * count: 0,
1010
- * increment: () => set((s) => ({ count: s.count + 1 })),
1011
- * }));
1012
- *
1013
- * const userSlice = createSlice('user', (set) => ({
1014
- * user: null,
1015
- * setUser: (user) => set({ user }),
1016
- * }));
1017
- *
1018
- * const store = combineSlices(counterSlice, userSlice);
1019
- *
1020
- * // Type-safe access to all slice methods
1021
- * store.increment();
1022
- * store.setUser({ name: 'John' });
1023
- * ```
1024
- */
1025
- declare function combineSlices<TSlices extends SliceDefinition<any, any>[]>(...slices: TSlices): Store<CombinedState<TSlices>> & CombinedState<TSlices>;
1026
- /**
1027
- * Create a namespaced slice that prefixes all state keys.
1028
- *
1029
- * @param namespace - The namespace prefix
1030
- * @param creator - Slice creator function
1031
- * @returns A namespaced slice definition
1032
- *
1033
- * @example
1034
- * ```typescript
1035
- * const settingsSlice = createNamespacedSlice('settings', (set) => ({
1036
- * theme: 'dark',
1037
- * language: 'en',
1038
- * setTheme: (theme) => set({ theme }),
1039
- * }));
1040
- *
1041
- * // State will be: { settings: { theme: 'dark', language: 'en' } }
1042
- * // Actions will be: setTheme
1043
- * ```
1044
- */
1045
- declare function createNamespacedSlice<TSlice extends Record<string, any>>(namespace: string, creator: (set: (partial: Partial<TSlice>) => void, get: () => TSlice) => TSlice): SliceDefinition<Record<string, any>, Record<string, any>>;
1046
- /**
1047
- * Extend an existing store with additional slices.
1048
- *
1049
- * @param store - The existing store
1050
- * @param slices - Additional slices to add
1051
- * @returns The extended store
1052
- *
1053
- * @example
1054
- * ```typescript
1055
- * const baseStore = createStore({ count: 0 });
1056
- *
1057
- * const extendedStore = extendStore(
1058
- * baseStore,
1059
- * createSlice('user', (set) => ({
1060
- * user: null,
1061
- * setUser: (user) => set({ user }),
1062
- * }))
1063
- * );
1064
- * ```
1065
- */
1066
- declare function extendStore<TState, TSlices extends SliceDefinition<TState & any, any>[]>(store: Store<TState>, ...slices: TSlices): Store<TState & CombinedState<TSlices>> & CombinedState<TSlices>;
1067
- /**
1068
- * Reset specific slices to their initial state.
1069
- *
1070
- * @param store - The store
1071
- * @param sliceNames - Names of slices to reset
1072
- *
1073
- * @example
1074
- * ```typescript
1075
- * // Reset only the user slice
1076
- * resetSlices(store, 'user');
1077
- *
1078
- * // Reset multiple slices
1079
- * resetSlices(store, 'user', 'cart');
1080
- * ```
1081
- */
1082
- declare function resetSlices<TState>(store: Store<TState>, ...sliceNames: string[]): void;
1083
-
1084
- /**
1085
- * Store Federation - Multi-store coordination and communication.
1086
- *
1087
- * Enables coordinated updates across multiple stores with
1088
- * atomic transactions and unified state access.
1089
- *
1090
- * @module federation
1091
- */
1092
-
1093
- /**
1094
- * Extract state type from a Store.
1095
- */
1096
- type StoreState<S> = S extends Store<infer T> ? T : never;
1097
- /**
1098
- * Map of store names to their state types.
1099
- */
1100
- type FederatedState<Stores extends Record<string, Store<any>>> = {
1101
- [K in keyof Stores]: StoreState<Stores[K]>;
1102
- };
1103
- /**
1104
- * Federation listener callback.
1105
- */
1106
- type FederationListener<Stores extends Record<string, Store<any>>> = (state: FederatedState<Stores>, prevState: FederatedState<Stores>, changedStore: keyof Stores) => void;
1107
- /**
1108
- * Federation transaction function.
1109
- */
1110
- type TransactionFn<Stores extends Record<string, Store<any>>> = (stores: Stores) => void | Promise<void>;
1111
- /**
1112
- * Federation options.
1113
- */
1114
- interface FederationOptions {
1115
- /** Name for debugging */
1116
- name?: string;
1117
- /** Enable transaction logging */
1118
- debug?: boolean;
1119
- }
1120
- /**
1121
- * Federation interface for coordinating multiple stores.
1122
- */
1123
- interface Federation<Stores extends Record<string, Store<any>>> {
1124
- /** Access to individual stores */
1125
- readonly stores: Stores;
1126
- /** Get combined state from all stores */
1127
- getState(): FederatedState<Stores>;
1128
- /** Subscribe to any store change */
1129
- subscribe(listener: FederationListener<Stores>): () => void;
1130
- /** Atomic multi-store update (synchronous) */
1131
- transaction(fn: TransactionFn<Stores>): void;
1132
- /** Async transaction with rollback on error */
1133
- transactionAsync(fn: TransactionFn<Stores>): Promise<void>;
1134
- /** Get a specific store */
1135
- getStore<K extends keyof Stores>(name: K): Stores[K];
1136
- /** Subscribe to the changes of one member store. */
1137
- subscribeStore<K extends keyof Stores>(name: K, listener: (state: StoreState<Stores[K]>, prevState: StoreState<Stores[K]>) => void): () => void;
1138
- /** Destroy federation and unsubscribe from all stores */
1139
- destroy(): void;
1140
- }
1141
- /**
1142
- * Create a federation of multiple stores.
1143
- *
1144
- * @param stores - Object containing named stores
1145
- * @param options - Federation options
1146
- * @returns A federation instance
1147
- *
1148
- * @example
1149
- * ```typescript
1150
- * import { createStore, createFederation } from '@oxog/state';
1151
- *
1152
- * // Create individual stores
1153
- * const userStore = createStore({
1154
- * user: null,
1155
- * setUser: (state, user) => ({ user }),
1156
- * });
1157
- *
1158
- * const cartStore = createStore({
1159
- * items: [],
1160
- * addItem: (state, item) => ({ items: [...state.items, item] }),
1161
- * clear: () => ({ items: [] }),
1162
- * });
1163
- *
1164
- * const settingsStore = createStore({
1165
- * theme: 'light',
1166
- * setTheme: (state, theme) => ({ theme }),
1167
- * });
1168
- *
1169
- * // Create federation
1170
- * const federation = createFederation({
1171
- * user: userStore,
1172
- * cart: cartStore,
1173
- * settings: settingsStore,
1174
- * });
1175
- *
1176
- * // Get combined state
1177
- * const state = federation.getState();
1178
- * // { user: { user: null, ... }, cart: { items: [], ... }, settings: { theme: 'light', ... } }
1179
- *
1180
- * // Subscribe to any store change
1181
- * federation.subscribe((state, prevState, changedStore) => {
1182
- * console.log(`${changedStore} changed:`, state[changedStore]);
1183
- * });
1184
- *
1185
- * // Atomic cross-store transaction
1186
- * federation.transaction(({ user, cart }) => {
1187
- * cart.setState({ items: [] });
1188
- * user.setState({ user: null });
1189
- * });
1190
- * ```
1191
- */
1192
- declare function createFederation<Stores extends Record<string, Store<any>>>(stores: Stores, options?: FederationOptions): Federation<Stores>;
1193
- /**
1194
- * Create a selector that combines state from multiple stores.
1195
- *
1196
- * @param federation - The federation instance
1197
- * @param selector - Selector function
1198
- * @returns A function that returns the selected value
1199
- *
1200
- * @example
1201
- * ```typescript
1202
- * const getCartTotal = createFederatedSelector(
1203
- * federation,
1204
- * (state) => {
1205
- * const items = state.cart.items;
1206
- * const discount = state.user.user?.discount || 0;
1207
- * const total = items.reduce((sum, item) => sum + item.price, 0);
1208
- * return total * (1 - discount);
1209
- * }
1210
- * );
1211
- *
1212
- * const total = getCartTotal();
1213
- * ```
1214
- */
1215
- declare function createFederatedSelector<Stores extends Record<string, Store<any>>, R>(federation: Federation<Stores>, selector: (state: FederatedState<Stores>) => R): () => R;
1216
- /**
1217
- * Create a computed value from federated state.
1218
- *
1219
- * @param federation - The federation instance
1220
- * @param selector - Selector function
1221
- * @param equalityFn - Optional equality function for caching
1222
- * @returns Object with get() and subscribe() methods
1223
- *
1224
- * @example
1225
- * ```typescript
1226
- * const isLoggedIn = createFederatedComputed(
1227
- * federation,
1228
- * (state) => state.user.user !== null
1229
- * );
1230
- *
1231
- * // Get current value
1232
- * if (isLoggedIn.get()) {
1233
- * showDashboard();
1234
- * }
1235
- *
1236
- * // Subscribe to changes
1237
- * isLoggedIn.subscribe((value) => {
1238
- * console.log('Login status:', value);
1239
- * });
1240
- * ```
1241
- */
1242
- declare function createFederatedComputed<Stores extends Record<string, Store<any>>, R>(federation: Federation<Stores>, selector: (state: FederatedState<Stores>) => R, equalityFn?: (a: R, b: R) => boolean): {
1243
- get(): R;
1244
- subscribe(listener: (value: R, prevValue: R) => void): () => void;
1245
- };
1246
- /**
1247
- * Wait for a condition across federated stores.
1248
- *
1249
- * @param federation - The federation instance
1250
- * @param predicate - Condition to wait for
1251
- * @param timeout - Optional timeout in ms
1252
- * @returns Promise that resolves when condition is met
1253
- *
1254
- * @example
1255
- * ```typescript
1256
- * // Wait for user to be logged in and cart to have items
1257
- * await waitForFederated(
1258
- * federation,
1259
- * (state) => state.user.user !== null && state.cart.items.length > 0,
1260
- * 5000 // 5 second timeout
1261
- * );
1262
- *
1263
- * // Now proceed with checkout
1264
- * checkout();
1265
- * ```
1266
- */
1267
- declare function waitForFederated<Stores extends Record<string, Store<any>>>(federation: Federation<Stores>, predicate: (state: FederatedState<Stores>) => boolean, timeout?: number): Promise<FederatedState<Stores>>;
1268
-
1269
- /**
1270
- * Plugin-specific types and interfaces.
1271
- */
1272
-
1273
- /**
1274
- * Persist plugin options.
1275
- */
1276
- interface PersistOptions<TState> {
1277
- /** Storage key */
1278
- key: string;
1279
- /** Storage implementation (defaults to localStorage) */
1280
- storage?: StorageLike;
1281
- /** List of state keys to persist (whitelist) */
1282
- whitelist?: Array<keyof TState>;
1283
- /** List of state keys to exclude (blacklist) */
1284
- blacklist?: Array<keyof TState>;
1285
- /** Custom function to select which parts of state to persist */
1286
- partialize?: (state: TState) => Partial<TState>;
1287
- /** Custom merge strategy for hydration */
1288
- merge?: (persistedState: Partial<TState>, currentState: TState) => TState;
1289
- /** Version for migration support */
1290
- version?: number;
1291
- /** Migration function between versions */
1292
- migrate?: (persistedState: unknown, version: number) => TState;
1293
- /** Custom serialization */
1294
- serialize?: (state: Partial<TState>) => string;
1295
- /** Custom deserialization */
1296
- deserialize?: (str: string) => Partial<TState>;
1297
- /** Encryption function */
1298
- encrypt?: (data: string) => string;
1299
- /** Decryption function */
1300
- decrypt?: (data: string) => string;
1301
- /** Debounce writes to storage (ms) */
1302
- writeDebounce?: number;
1303
- /** Called when hydration starts */
1304
- onRehydrateStorage?: (state: TState | undefined) => void;
1305
- /** Called when hydration completes */
1306
- onHydrationComplete?: (state: TState) => void;
1307
- /** Called on persistence error */
1308
- onPersistError?: (error: Error) => void;
1309
- }
1310
- /**
1311
- * Storage interface for persistence.
1312
- */
1313
- interface StorageLike {
1314
- getItem(key: string): string | null;
1315
- setItem(key: string, value: string): void;
1316
- removeItem(key: string): void;
1317
- }
1318
- /**
1319
- * Devtools plugin options.
1320
- */
1321
- interface DevtoolsOptions {
1322
- /** Store name for DevTools */
1323
- name?: string;
1324
- /** Enable/disable DevTools */
1325
- enabled?: boolean;
1326
- /** Maximum number of states to keep in history */
1327
- maxAge?: number;
1328
- }
1329
- /**
1330
- * History plugin options.
1331
- */
1332
- interface HistoryOptions<TState> {
1333
- /** Maximum number of past states to keep */
1334
- limit?: number;
1335
- /** Keys to track for history (empty array tracks all) */
1336
- keys?: Array<keyof TState>;
1337
- }
1338
- /**
1339
- * Sync plugin options.
1340
- */
1341
- interface SyncOptions {
1342
- /** Channel name for BroadcastChannel */
1343
- channel?: string;
1344
- }
1345
- /**
1346
- * Selector plugin options.
1347
- */
1348
- interface SelectorOptions<TState> {
1349
- /** Map of computed selectors */
1350
- selectors: {
1351
- [K in keyof TState]?: (state: TState) => TState[K];
1352
- };
1353
- }
1354
- /**
1355
- * History-enabled store interface.
1356
- */
1357
- interface HistoryStore<TState> extends Store<TState> {
1358
- undo(): void;
1359
- redo(): void;
1360
- clearHistory(): void;
1361
- canUndo(): boolean;
1362
- canRedo(): boolean;
1363
- }
1364
-
1365
- /**
1366
- * Persist plugin - Save and restore state from storage.
1367
- *
1368
- * Automatically persists state to localStorage, sessionStorage, or any
1369
- * storage implementation. State is restored on store creation.
1370
- *
1371
- * @example
1372
- * ```typescript
1373
- * import { createStore, persist } from '@oxog/state';
1374
- *
1375
- * const store = createStore({ count: 0, user: null })
1376
- * .use(persist({
1377
- * key: 'my-app',
1378
- * storage: localStorage,
1379
- * whitelist: ['count'] // Only persist count
1380
- * }));
1381
- * ```
1382
- */
1383
-
1384
- /**
1385
- * SessionStorage implementation.
1386
- */
1387
- declare const sessionStorage: StorageLike;
1388
- /**
1389
- * Create a persist plugin.
1390
- *
1391
- * @param options - Plugin options
1392
- * @returns A persist plugin
1393
- *
1394
- * @example
1395
- * ```typescript
1396
- * import { persist, sessionStorage } from '@oxog/state';
1397
- *
1398
- * // Using localStorage (default)
1399
- * const store = createStore({ count: 0 })
1400
- * .use(persist({ key: 'counter' }));
1401
- *
1402
- * // Using sessionStorage
1403
- * const store = createStore({ count: 0 })
1404
- * .use(persist({ key: 'counter', storage: sessionStorage }));
1405
- *
1406
- * // With whitelist
1407
- * const store = createStore({ count: 0, temp: '' })
1408
- * .use(persist({ key: 'app', whitelist: ['count'] }));
1409
- *
1410
- * // With encryption
1411
- * const store = createStore({ secret: 'data' })
1412
- * .use(persist({
1413
- * key: 'secure',
1414
- * encrypt: (data) => btoa(data),
1415
- * decrypt: (data) => atob(data),
1416
- * }));
1417
- *
1418
- * // With debounce and migration
1419
- * const store = createStore({ count: 0 })
1420
- * .use(persist({
1421
- * key: 'app',
1422
- * writeDebounce: 1000,
1423
- * version: 2,
1424
- * migrate: (state, version) => {
1425
- * if (version < 2) return { ...state, newField: 'default' };
1426
- * return state;
1427
- * },
1428
- * }));
1429
- * ```
1430
- */
1431
- declare function persist<TState>(options: PersistOptions<TState>): Plugin<TState>;
1432
- /**
1433
- * Create a custom storage from a storage object.
1434
- *
1435
- * @param storage - Any object with getItem, setItem, removeItem
1436
- * @returns A StorageLike interface
1437
- *
1438
- * @example
1439
- * ```typescript
1440
- * import { createStorage } from '@oxog/state';
1441
- *
1442
- * const AsyncStorage = createStorage({
1443
- * getItem: async (key) => await AsyncStorage.getItem(key),
1444
- * setItem: async (key, value) => await AsyncStorage.setItem(key, value),
1445
- * removeItem: async (key) => await AsyncStorage.removeItem(key),
1446
- * });
1447
- * ```
1448
- */
1449
- declare function createStorage(storage: StorageLike): StorageLike;
1450
-
1451
- /**
1452
- * Devtools plugin - Redux DevTools integration.
1453
- *
1454
- * Connects to Redux DevTools extension for debugging state changes.
1455
- *
1456
- * @example
1457
- * ```typescript
1458
- * import { createStore, devtools } from '@oxog/state';
1459
- *
1460
- * const store = createStore({ count: 0 })
1461
- * .use(devtools({ name: 'Counter' }));
1462
- * ```
1463
- */
1464
-
1465
- /**
1466
- * Create a DevTools plugin.
1467
- *
1468
- * @param options - Plugin options
1469
- * @returns A DevTools plugin
1470
- *
1471
- * @example
1472
- * ```typescript
1473
- * import { devtools } from '@oxog/state';
1474
- *
1475
- * // Basic usage
1476
- * const store = createStore({ count: 0 })
1477
- * .use(devtools({ name: 'My Store' }));
1478
- *
1479
- * // Disabled in production
1480
- * const store = createStore({ count: 0 })
1481
- * .use(devtools({
1482
- * name: 'My Store',
1483
- * enabled: process.env.NODE_ENV === 'development'
1484
- * }));
1485
- * ```
1486
- */
1487
- declare function devtools<TState>(options?: DevtoolsOptions): Plugin<TState>;
1488
-
1489
- /**
1490
- * History plugin - Undo/redo functionality.
1491
- *
1492
- * Tracks state changes and provides undo/redo methods.
1493
- *
1494
- * @example
1495
- * ```typescript
1496
- * import { createStore, history } from '@oxog/state';
1497
- *
1498
- * const store = createStore({ count: 0 })
1499
- * .use(history({ limit: 100 }));
1500
- *
1501
- * // Now store has undo() and redo() methods
1502
- * store.setState({ count: 1 });
1503
- * store.setState({ count: 2 });
1504
- * store.undo(); // { count: 1 }
1505
- * store.redo(); // { count: 2 }
1506
- * ```
1507
- */
1508
-
1509
- /**
1510
- * Create a history plugin.
1511
- *
1512
- * @param options - Plugin options
1513
- * @returns A history plugin
1514
- *
1515
- * @example
1516
- * ```typescript
1517
- * import { history } from '@oxog/state';
1518
- *
1519
- * // Default options
1520
- * const store = createStore({ count: 0 })
1521
- * .use(history());
1522
- *
1523
- * // Custom limit
1524
- * const store = createStore({ count: 0 })
1525
- * .use(history({ limit: 50 }));
1526
- *
1527
- * // Track specific keys only
1528
- * const store = createStore({ count: 0, temp: '' })
1529
- * .use(history({ keys: ['count'] }));
1530
- * ```
1531
- */
1532
- declare function history<TState>(options?: HistoryOptions<TState>): Plugin<TState>;
1533
- /**
1534
- * Check if a store has history capabilities.
1535
- *
1536
- * @param store - The store to check
1537
- * @returns true if store supports undo/redo
1538
- *
1539
- * @example
1540
- * ```typescript
1541
- * import { hasHistory } from '@oxog/state';
1542
- *
1543
- * if (hasHistory(store)) {
1544
- * store.undo();
1545
- * store.redo();
1546
- * }
1547
- * ```
1548
- */
1549
- declare function hasHistory<TState>(store: Store<TState>): store is HistoryStore<TState>;
1550
-
1551
- /**
1552
- * Sync plugin - Cross-tab state synchronization.
1553
- *
1554
- * Synchronizes state across browser tabs using BroadcastChannel API.
1555
- *
1556
- * @example
1557
- * ```typescript
1558
- * import { createStore, sync } from '@oxog/state';
1559
- *
1560
- * const store = createStore({ count: 0 })
1561
- * .use(sync({ channel: 'my-app-state' }));
1562
- *
1563
- * // State changes will sync across all tabs
1564
- * ```
1565
- */
1566
-
1567
- /**
1568
- * Create a sync plugin.
1569
- *
1570
- * @param options - Plugin options
1571
- * @returns A sync plugin
1572
- *
1573
- * @example
1574
- * ```typescript
1575
- * import { sync } from '@oxog/state';
1576
- *
1577
- * // Default channel name
1578
- * const store = createStore({ count: 0 })
1579
- * .use(sync());
1580
- *
1581
- * // Custom channel name
1582
- * const store = createStore({ count: 0 })
1583
- * .use(sync({ channel: 'my-app' }));
1584
- * ```
1585
- */
1586
- declare function sync<TState>(options?: SyncOptions): Plugin<TState>;
1587
- /**
1588
- * Manually trigger a sync broadcast.
1589
- *
1590
- * @param store - The store to sync
1591
- * @param channel - The channel to broadcast on
1592
- *
1593
- * @example
1594
- * ```typescript
1595
- * import { createStore, sync, triggerSync } from '@oxog/state';
1596
- *
1597
- * const store = createStore({ count: 0 })
1598
- * .use(sync({ channel: 'my-app' }));
1599
- *
1600
- * // Manually trigger sync
1601
- * triggerSync(store, 'my-app');
1602
- * ```
1603
- */
1604
- declare function triggerSync<TState>(store: Store<TState>, channel?: string): void;
1605
-
1606
- /**
1607
- * Immer plugin - Immutable updates with mutable syntax.
1608
- *
1609
- * Uses Proxy to enable writing immutable state updates with mutable syntax.
1610
- *
1611
- * @example
1612
- * ```typescript
1613
- * import { createStore, immer } from '@oxog/state';
1614
- *
1615
- * const store = createStore({
1616
- * users: [{ name: 'John', age: 30 }]
1617
- * }).use(immer());
1618
- *
1619
- * // Now you can write mutable-style updates
1620
- * store.setState((draft) => {
1621
- * draft.users[0].age = 31; // Mutate draft directly
1622
- * });
1623
- * ```
1624
- */
1625
-
1626
- /**
1627
- * Produce a new state by applying mutations to a draft.
1628
- *
1629
- * Copy-on-write: only the objects and arrays on the path of a change are
1630
- * copied, untouched branches keep their identity, and `base` is never
1631
- * mutated. If the recipe returns an object, that object is the result.
1632
- *
1633
- * @param base - The base state
1634
- * @param recipe - The mutation function
1635
- * @returns The new state
1636
- *
1637
- * @example
1638
- * ```typescript
1639
- * import { produce } from '@oxog/state';
1640
- *
1641
- * const state = { users: [{ name: 'John', age: 30 }] };
1642
- * const newState = produce(state, (draft) => {
1643
- * draft.users[0].age = 31;
1644
- * });
1645
- * // state is unchanged; newState.users[0].age === 31
1646
- * ```
1647
- */
1648
- declare function produce<T>(base: T, recipe: (draft: T) => T | Partial<T> | void): T;
1649
- /**
1650
- * Create an immer plugin.
1651
- *
1652
- * With the plugin installed, `setState` accepts a recipe that mutates a
1653
- * draft. Regular updaters that return a partial state keep working.
1654
- *
1655
- * @returns An immer plugin
1656
- *
1657
- * @example
1658
- * ```typescript
1659
- * import { createStore, immer } from '@oxog/state';
1660
- *
1661
- * const store = createStore({
1662
- * items: [{ id: 1, name: 'Item 1' }]
1663
- * }).use(immer());
1664
- *
1665
- * // Now setState can accept a mutable recipe function
1666
- * store.setState((draft) => {
1667
- * draft.items[0].name = 'Updated Item';
1668
- * draft.items.push({ id: 2, name: 'Item 2' });
1669
- * });
1670
- * ```
1671
- */
1672
- declare function immer<TState>(): Plugin<TState>;
1673
-
1674
- /**
1675
- * Selector plugin - Computed/derived values.
1676
- *
1677
- * Define computed values that automatically update when dependencies change.
1678
- *
1679
- * @example
1680
- * ```typescript
1681
- * import { createStore, selector } from '@oxog/state';
1682
- *
1683
- * const store = createStore({
1684
- * items: [] as { status: string }[],
1685
- * filter: 'all',
1686
- * filteredItems: [] as { status: string }[],
1687
- * itemCount: 0,
1688
- * })
1689
- * .use(selector({
1690
- * selectors: {
1691
- * // Computed: filtered items
1692
- * filteredItems: (state) =>
1693
- * state.filter === 'all' ? state.items : state.items.filter((item) => item.status === state.filter),
1694
- * // Computed: item count
1695
- * itemCount: (state) => state.items.length,
1696
- * },
1697
- * }));
1698
- *
1699
- * // Access computed values
1700
- * const state = store.getState();
1701
- * console.log(state.filteredItems); // Computed value
1702
- * ```
1703
- */
1704
-
1705
- /**
1706
- * Create a selector plugin for computed values.
1707
- *
1708
- * @param options - Plugin options with selectors
1709
- * @returns A selector plugin
1710
- *
1711
- * @example
1712
- * ```typescript
1713
- * import { selector } from '@oxog/state';
1714
- *
1715
- * const store = createStore({
1716
- * items: [{ price: 10 }, { price: 20 }],
1717
- * taxRate: 0.1,
1718
- * })
1719
- * .use(selector({
1720
- * // Computed total
1721
- * total: (state) =>
1722
- * state.items.reduce((sum: number, item: any) => sum + item.price, 0),
1723
- *
1724
- * // Computed total with tax
1725
- * totalWithTax: (state) => {
1726
- * const total = state.items.reduce((sum: number, item: any) => sum + item.price, 0);
1727
- * return total * (1 + state.taxRate);
1728
- * },
1729
- * }));
1730
- * ```
1731
- */
1732
- declare function selector<TState>(options: SelectorOptions<TState>): Plugin<TState>;
1733
-
1734
- /**
1735
- * Logger plugin for console logging state changes.
1736
- *
1737
- * @module plugins/logger
1738
- */
1739
-
1740
- /**
1741
- * Log level for filtering messages.
1742
- */
1743
- type LogLevel = 'debug' | 'info' | 'warn' | 'error';
1744
- /**
1745
- * Logger options.
1746
- */
1747
- interface LoggerOptions<TState = unknown> {
1748
- /** Log level filter (default: 'debug') */
1749
- level?: LogLevel;
1750
- /** Custom logger (default: console) */
1751
- logger?: Console;
1752
- /** Use collapsed console groups (default: true) */
1753
- collapsed?: boolean;
1754
- /** Show state diff (default: true) */
1755
- diff?: boolean;
1756
- /** Colorize output (default: true in browsers) */
1757
- colors?: boolean;
1758
- /** Show timestamp (default: true) */
1759
- timestamp?: boolean;
1760
- /** Filter function to skip certain changes */
1761
- filter?: (state: TState, prevState: TState) => boolean;
1762
- /** Transform state before logging */
1763
- stateTransformer?: (state: TState) => unknown;
1764
- /** Custom action name (default: 'STATE_CHANGE') */
1765
- actionName?: string | ((state: TState, prevState: TState) => string);
1766
- /** Name for this logger instance */
1767
- name?: string;
1768
- /** Enabled flag (default: true) */
1769
- enabled?: boolean;
1770
- }
1771
- /**
1772
- * Create a logger plugin.
1773
- *
1774
- * @param options - Logger options
1775
- * @returns A logger plugin
1776
- *
1777
- * @example
1778
- * ```typescript
1779
- * import { createStore, logger } from '@oxog/state';
1780
- *
1781
- * // Basic usage
1782
- * const store = createStore({ count: 0 })
1783
- * .use(logger());
1784
- *
1785
- * // With options
1786
- * const store = createStore({ count: 0 })
1787
- * .use(logger({
1788
- * level: 'info',
1789
- * collapsed: false,
1790
- * diff: true,
1791
- * name: 'CounterStore',
1792
- * }));
1793
- *
1794
- * // Disabled in production
1795
- * const store = createStore({ count: 0 })
1796
- * .use(logger({
1797
- * enabled: process.env.NODE_ENV !== 'production',
1798
- * }));
1799
- * ```
1800
- */
1801
- declare function logger<TState = unknown>(options?: LoggerOptions<TState>): Plugin<TState>;
1802
- /**
1803
- * Create a logger with preset options.
1804
- *
1805
- * @param defaultOptions - Default options
1806
- * @returns A logger factory function
1807
- *
1808
- * @example
1809
- * ```typescript
1810
- * const devLogger = createLogger({
1811
- * enabled: process.env.NODE_ENV === 'development',
1812
- * collapsed: true,
1813
- * });
1814
- *
1815
- * const store = createStore({ count: 0 })
1816
- * .use(devLogger({ name: 'Counter' }));
1817
- * ```
1818
- */
1819
- declare function createLogger<TState = unknown>(defaultOptions?: LoggerOptions<TState>): (options?: LoggerOptions<TState>) => Plugin<TState>;
1820
-
1821
- /**
1822
- * Effects plugin for managing side effects.
1823
- *
1824
- * Provides a declarative way to handle async operations,
1825
- * API calls, and other side effects in response to state changes.
1826
- *
1827
- * @module plugins/effects
1828
- */
1829
-
1830
- /**
1831
- * Effect cleanup function.
1832
- */
1833
- type EffectCleanup = () => void;
1834
- /**
1835
- * Effect function that runs when dependencies change.
1836
- */
1837
- type EffectFn<T> = (value: T, prevValue: T, utils: EffectUtils) => void | EffectCleanup | Promise<void | EffectCleanup>;
1838
- /**
1839
- * Utilities available to effects.
1840
- */
1841
- interface EffectUtils {
1842
- /** Get current store state */
1843
- getState: () => unknown;
1844
- /**
1845
- * Set store state. Ignored once this run is no longer active (superseded
1846
- * by a newer run, cancelled, or the store was destroyed), so a slow earlier
1847
- * run cannot overwrite the result of a later one.
1848
- */
1849
- setState: (partial: any) => void;
1850
- /** Check if this run is still active (not superseded, cancelled or destroyed) */
1851
- isActive: () => boolean;
1852
- /** Cancel this run */
1853
- cancel: () => void;
1854
- /** Run a callback only if this run is active */
1855
- onlyIfActive: <T>(fn: () => T) => T | undefined;
1856
- /** Aborted when this run is superseded, cancelled or the store is destroyed (pass it to fetch). */
1857
- signal: AbortSignal;
1858
- }
1859
- /**
1860
- * Effect definition for the effects plugin.
1861
- */
1862
- interface EffectDefinition<TState, TSelected = TState> {
1863
- /** Selector to watch */
1864
- selector: Selector<TState, TSelected>;
1865
- /** Effect function */
1866
- effect: EffectFn<TSelected>;
1867
- /** Custom equality function */
1868
- equalityFn?: EqualityFn<TSelected>;
1869
- /** Fire effect immediately with current value */
1870
- fireImmediately?: boolean;
1871
- /** Debounce effect (ms) */
1872
- debounce?: number;
1873
- /** Effect name for debugging */
1874
- name?: string;
1875
- }
1876
- /**
1877
- * Options for the effects plugin.
1878
- */
1879
- interface EffectsOptions<TState> {
1880
- /** Array of effect definitions */
1881
- effects: EffectDefinition<TState, any>[];
1882
- /** Error handler for effect errors */
1883
- onError?: (error: Error, effectName?: string) => void;
1884
- }
1885
- /**
1886
- * Create an effects plugin.
1887
- *
1888
- * @param options - Effects configuration
1889
- * @returns An effects plugin
1890
- *
1891
- * @example
1892
- * ```typescript
1893
- * import { createStore, effects } from '@oxog/state';
1894
- *
1895
- * const store = createStore({
1896
- * userId: null,
1897
- * user: null,
1898
- * loading: false,
1899
- * }).use(effects({
1900
- * effects: [
1901
- * {
1902
- * name: 'fetchUser',
1903
- * selector: (s) => s.userId,
1904
- * effect: async (userId, _prev, { setState, isActive }) => {
1905
- * if (!userId) return;
1906
- *
1907
- * setState({ loading: true });
1908
- * try {
1909
- * const user = await fetchUser(userId);
1910
- * if (isActive()) {
1911
- * setState({ user, loading: false });
1912
- * }
1913
- * } catch (error) {
1914
- * if (isActive()) {
1915
- * setState({ user: null, loading: false });
1916
- * }
1917
- * }
1918
- * },
1919
- * },
1920
- * ],
1921
- * }));
1922
- * ```
1923
- */
1924
- declare function effects<TState>(options: EffectsOptions<TState>): Plugin<TState>;
1925
- /**
1926
- * Create an effect definition helper.
1927
- *
1928
- * @param name - Effect name
1929
- * @param selector - Selector to watch
1930
- * @param effect - Effect function
1931
- * @param options - Additional options
1932
- * @returns Effect definition
1933
- *
1934
- * @example
1935
- * ```typescript
1936
- * const fetchUserEffect = createEffect(
1937
- * 'fetchUser',
1938
- * (s) => s.userId,
1939
- * async (userId, _prev, { setState }) => {
1940
- * const user = await api.getUser(userId);
1941
- * setState({ user });
1942
- * },
1943
- * { fireImmediately: true }
1944
- * );
1945
- *
1946
- * const store = createStore({ userId: null, user: null })
1947
- * .use(effects({ effects: [fetchUserEffect] }));
1948
- * ```
1949
- */
1950
- declare function createEffect<TState, TSelected>(name: string, selector: Selector<TState, TSelected>, effect: EffectFn<TSelected>, options?: Omit<EffectDefinition<TState, TSelected>, 'name' | 'selector' | 'effect'>): EffectDefinition<TState, TSelected>;
1951
- /**
1952
- * Create a simple effect that runs on any state change.
1953
- *
1954
- * @param effect - Effect function
1955
- * @param options - Effect options
1956
- * @returns Effect definition
1957
- *
1958
- * @example
1959
- * ```typescript
1960
- * const logEffect = createSimpleEffect(
1961
- * (state, prevState) => {
1962
- * console.log('State changed:', state);
1963
- * }
1964
- * );
1965
- * ```
1966
- */
1967
- declare function createSimpleEffect<TState>(effect: (state: TState, prevState: TState, utils: EffectUtils) => void | EffectCleanup, options?: Omit<EffectDefinition<TState, TState>, 'selector' | 'effect'>): EffectDefinition<TState, TState>;
1968
- /**
1969
- * Combine multiple effect definitions.
1970
- *
1971
- * @param effectDefs - Effect definitions to combine
1972
- * @returns Combined effects options
1973
- *
1974
- * @example
1975
- * ```typescript
1976
- * const store = createStore({ ... })
1977
- * .use(effects(combineEffects(
1978
- * fetchUserEffect,
1979
- * saveToStorageEffect,
1980
- * analyticsEffect,
1981
- * )));
1982
- * ```
1983
- */
1984
- declare function combineEffects<TState>(...effectDefs: EffectDefinition<TState, any>[]): EffectsOptions<TState>;
1985
- /**
1986
- * Create a debounced effect that only fires after a delay.
1987
- *
1988
- * @param delay - Debounce delay in ms
1989
- * @param selector - Selector to watch
1990
- * @param effect - Effect function
1991
- * @returns Effect definition
1992
- *
1993
- * @example
1994
- * ```typescript
1995
- * const searchEffect = createDebouncedEffect(
1996
- * 300,
1997
- * (s) => s.searchQuery,
1998
- * async (query, _prev, { setState }) => {
1999
- * const results = await api.search(query);
2000
- * setState({ searchResults: results });
2001
- * }
2002
- * );
2003
- * ```
2004
- */
2005
- declare function createDebouncedEffect<TState, TSelected>(delay: number, selector: Selector<TState, TSelected>, effect: EffectFn<TSelected>, options?: Omit<EffectDefinition<TState, TSelected>, 'selector' | 'effect' | 'debounce'>): EffectDefinition<TState, TSelected>;
2006
-
2007
- /**
2008
- * Validation plugin for state schema validation.
2009
- *
2010
- * Provides schema-agnostic validation with support for Zod, Yup,
2011
- * or custom validation functions.
2012
- *
2013
- * @module plugins/validate
2014
- */
2015
-
2016
- /**
2017
- * Validation error type.
2018
- */
2019
- interface ValidationError {
2020
- /** Path to the invalid field */
2021
- path: string[];
2022
- /** Error message */
2023
- message: string;
2024
- /** Validation rule that failed */
2025
- rule?: string;
2026
- /** The invalid value */
2027
- value?: unknown;
2028
- }
2029
- /**
2030
- * Validation result.
2031
- */
2032
- interface ValidationResult {
2033
- /** Whether validation passed */
2034
- valid: boolean;
2035
- /** List of validation errors */
2036
- errors: ValidationError[];
2037
- }
2038
- /**
2039
- * Custom validator function type.
2040
- */
2041
- type ValidatorFn<T> = (state: T) => boolean | ValidationResult | ValidationError[];
2042
- /**
2043
- * Zod-like schema interface.
2044
- */
2045
- interface ZodLikeSchema<T> {
2046
- safeParse(data: unknown): {
2047
- success: boolean;
2048
- error?: {
2049
- issues: Array<{
2050
- path: (string | number)[];
2051
- message: string;
2052
- code?: string;
2053
- }>;
2054
- };
2055
- data?: T;
2056
- };
2057
- }
2058
- /**
2059
- * Yup-like schema interface.
2060
- */
2061
- interface YupLikeSchema<T> {
2062
- validateSync(data: unknown, options?: {
2063
- abortEarly?: boolean;
2064
- }): T;
2065
- validate(data: unknown, options?: {
2066
- abortEarly?: boolean;
2067
- }): Promise<T>;
2068
- }
2069
- /**
2070
- * Validation timing options.
2071
- */
2072
- type ValidationTiming = 'change' | 'commit' | 'manual';
2073
- /**
2074
- * Blocks inference from the schema, so the state type comes from the store
2075
- * (`store.use(validate(...))`) and `paths` stays typed with a Zod/Yup schema.
2076
- */
2077
- type NoInferState<T> = [T][T extends any ? 0 : never];
2078
- /**
2079
- * Validation plugin options.
2080
- */
2081
- interface ValidateOptions<T> {
2082
- /** Schema to validate against (Zod, Yup, or custom function) */
2083
- schema: ZodLikeSchema<unknown> | YupLikeSchema<unknown> | ValidatorFn<NoInferState<T>>;
2084
- /**
2085
- * When to validate: 'change' (after every state change) or 'manual' (only
2086
- * when validate() is called). 'commit' is currently handled like 'manual'.
2087
- */
2088
- on?: ValidationTiming;
2089
- /** Callback when validation fails */
2090
- onError?: (errors: ValidationError[]) => void;
2091
- /**
2092
- * Make validate() throw on failure. Validation on change runs inside a
2093
- * store listener, so there the error is reported through the store's error
2094
- * handling (console.error / plugin onError) and the update is kept.
2095
- */
2096
- throwOnError?: boolean;
2097
- /** Only validate these paths (keys of state) */
2098
- paths?: Array<keyof T>;
2099
- /** Name for debugging */
2100
- name?: string;
2101
- }
2102
- /**
2103
- * Validation API added to store.
2104
- */
2105
- interface ValidationAPI {
2106
- /** Manually trigger validation */
2107
- validate(): ValidationResult;
2108
- /** Check if current state is valid */
2109
- isValid(): boolean;
2110
- /** Get current validation errors */
2111
- getErrors(): ValidationError[];
2112
- /** Clear validation errors */
2113
- clearErrors(): void;
2114
- }
2115
- /**
2116
- * Create a validation plugin.
2117
- *
2118
- * @param options - Validation options
2119
- * @returns A validation plugin
2120
- *
2121
- * @example
2122
- * ```typescript
2123
- * import { createStore, validate } from '@oxog/state';
2124
- * import { z } from 'zod';
2125
- *
2126
- * // With Zod schema
2127
- * const userSchema = z.object({
2128
- * name: z.string().min(1),
2129
- * age: z.number().min(0),
2130
- * email: z.string().email(),
2131
- * });
2132
- *
2133
- * const store = createStore({ name: '', age: 0, email: '' })
2134
- * .use(validate({
2135
- * schema: userSchema,
2136
- * on: 'change',
2137
- * onError: (errors) => console.log('Validation errors:', errors),
2138
- * }));
2139
- *
2140
- * // Manual validation
2141
- * const result = store.validate();
2142
- * if (!result.valid) {
2143
- * console.log(result.errors);
2144
- * }
2145
- *
2146
- * // Check if valid
2147
- * if (store.isValid()) {
2148
- * submitForm();
2149
- * }
2150
- * ```
2151
- *
2152
- * @example
2153
- * ```typescript
2154
- * // With custom validator function
2155
- * const store = createStore({ password: '', confirmPassword: '' })
2156
- * .use(validate({
2157
- * schema: (state) => {
2158
- * const errors = [];
2159
- * if (state.password.length < 8) {
2160
- * errors.push({
2161
- * path: ['password'],
2162
- * message: 'Password must be at least 8 characters',
2163
- * });
2164
- * }
2165
- * if (state.password !== state.confirmPassword) {
2166
- * errors.push({
2167
- * path: ['confirmPassword'],
2168
- * message: 'Passwords must match',
2169
- * });
2170
- * }
2171
- * return errors;
2172
- * },
2173
- * on: 'change',
2174
- * }));
2175
- * ```
2176
- *
2177
- * @example
2178
- * ```typescript
2179
- * // With partial validation
2180
- * const store = createStore({ name: '', age: 0, temp: '' })
2181
- * .use(validate({
2182
- * schema: userSchema,
2183
- * paths: ['name', 'age'], // Only validate these fields
2184
- * }));
2185
- * ```
2186
- */
2187
- declare function validate<TState>(options: ValidateOptions<TState>): Plugin<TState>;
2188
- /**
2189
- * Create a simple boolean validator.
2190
- *
2191
- * @param predicate - Validation predicate function
2192
- * @param message - Error message when validation fails
2193
- * @returns A validator function
2194
- *
2195
- * @example
2196
- * ```typescript
2197
- * const isPositive = createValidator(
2198
- * (state) => state.count >= 0,
2199
- * 'Count must be positive'
2200
- * );
2201
- *
2202
- * const store = createStore({ count: 0 })
2203
- * .use(validate({ schema: isPositive }));
2204
- * ```
2205
- */
2206
- declare function createValidator<T>(predicate: (state: T) => boolean, message: string): (state: T) => ValidationResult;
2207
- /**
2208
- * Combine multiple validators into one.
2209
- *
2210
- * @param validators - Array of validator functions
2211
- * @returns Combined validator function
2212
- *
2213
- * @example
2214
- * ```typescript
2215
- * const combinedValidator = combineValidators(
2216
- * createValidator((s) => s.name.length > 0, 'Name required'),
2217
- * createValidator((s) => s.age >= 18, 'Must be 18+'),
2218
- * );
2219
- *
2220
- * const store = createStore({ name: '', age: 0 })
2221
- * .use(validate({ schema: combinedValidator }));
2222
- * ```
2223
- */
2224
- declare function combineValidators<T>(...validators: ValidatorFn<T>[]): (state: T) => ValidationResult;
2225
- /**
2226
- * Create a field-level validator.
2227
- *
2228
- * @param field - Field name to validate
2229
- * @param predicate - Validation predicate for field value
2230
- * @param message - Error message when validation fails
2231
- * @returns A validator function
2232
- *
2233
- * @example
2234
- * ```typescript
2235
- * const emailValidator = createFieldValidator(
2236
- * 'email',
2237
- * (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email),
2238
- * 'Invalid email format'
2239
- * );
2240
- *
2241
- * const store = createStore({ email: '' })
2242
- * .use(validate({ schema: emailValidator }));
2243
- * ```
2244
- */
2245
- declare function createFieldValidator<T, K extends keyof T>(field: K, predicate: (value: T[K], state: T) => boolean, message: string): (state: T) => ValidationResult;
2246
- /**
2247
- * Create an async validator (for server-side validation).
2248
- *
2249
- * @param validator - Async validation function
2250
- * @returns A promise that resolves to validation result
2251
- *
2252
- * @example
2253
- * ```typescript
2254
- * const checkUsername = createAsyncValidator(async (state) => {
2255
- * const exists = await api.checkUsername(state.username);
2256
- * return exists
2257
- * ? [{ path: ['username'], message: 'Username already taken' }]
2258
- * : [];
2259
- * });
2260
- *
2261
- * // Manual validation
2262
- * const result = await checkUsername(store.getState());
2263
- * ```
2264
- */
2265
- declare function createAsyncValidator<T>(validator: (state: T) => Promise<ValidationError[]>): (state: T) => Promise<ValidationResult>;
2266
-
2267
- /**
2268
- * Deep clone a value, creating copies of nested objects and arrays.
2269
- *
2270
- * Handles:
2271
- * - Primitives (returned as-is)
2272
- * - null and undefined (returned as-is)
2273
- * - Date objects
2274
- * - Arrays
2275
- * - Plain objects
2276
- * - Circular references
2277
- * - Other objects (returned as-is, not cloned)
2278
- *
2279
- * @typeParam T - The type to clone
2280
- * @param value - The value to clone
2281
- * @param seen - Internal map for tracking circular references
2282
- * @returns A deep clone of the value
2283
- *
2284
- * @example
2285
- * ```typescript
2286
- * const original = { a: 1, b: { c: 2 } };
2287
- * const cloned = deepClone(original);
2288
- * cloned.b.c = 3;
2289
- * console.log(original.b.c); // 2 (unchanged)
2290
- * ```
2291
- */
2292
- declare function deepClone<T>(value: T, seen?: WeakMap<object, unknown>): T;
2293
-
2294
- /**
2295
- * Deep equality check for two values.
2296
- *
2297
- * Recursively compares objects and arrays.
2298
- * Uses Object.is for primitive comparison.
2299
- *
2300
- * @param a - First value
2301
- * @param b - Second value
2302
- * @returns true if values are deeply equal
2303
- *
2304
- * @example
2305
- * ```typescript
2306
- * deepEqual(1, 1); // true
2307
- * deepEqual({ a: { b: 1 } }, { a: { b: 1 } }); // true
2308
- * deepEqual({ a: { b: 1 } }, { a: { b: 2 } }); // false
2309
- * deepEqual([1, 2], [1, 2]); // true
2310
- * deepEqual([1, 2], [1, 2, 3]); // false
2311
- * ```
2312
- */
2313
- declare function deepEqual(a: unknown, b: unknown): boolean;
2314
-
2315
- /**
2316
- * Shallow equality check for two values.
2317
- *
2318
- * Uses Object.is for comparison, which handles NaN correctly
2319
- * and distinguishes between +0 and -0.
2320
- *
2321
- * @param a - First value
2322
- * @param b - Second value
2323
- * @returns true if values are shallowly equal
2324
- *
2325
- * @example
2326
- * ```typescript
2327
- * shallowEqual(1, 1); // true
2328
- * shallowEqual({ a: 1 }, { a: 1 }); // true
2329
- * shallowEqual({ a: 1 }, { a: 2 }); // false
2330
- * shallowEqual(NaN, NaN); // true
2331
- * ```
2332
- */
2333
- declare function shallowEqual(a: unknown, b: unknown): boolean;
2334
-
2335
- /**
2336
- * Deep merge a partial object into a target object.
2337
- *
2338
- * Creates a new object with nested objects merged recursively.
2339
- * Arrays are replaced, not merged.
2340
- *
2341
- * @typeParam T - The target type
2342
- * @param target - The target object
2343
- * @param source - The partial source to merge
2344
- * @returns A new merged object
2345
- *
2346
- * @example
2347
- * ```typescript
2348
- * const target = { a: 1, b: { c: 2, d: 3 } };
2349
- * const source = { b: { c: 10 }, e: 4 };
2350
- * const merged = deepMerge(target, source);
2351
- * // { a: 1, b: { c: 10, d: 3 }, e: 4 }
2352
- * ```
2353
- */
2354
-
2355
- declare function deepMerge<T>(target: T, source: Partial<T> | DeepPartial<T>): T;
2356
- declare function deepMerge<T, S extends object>(target: T, source: S): T & S;
2357
-
2358
- /**
2359
- * Type guard to check if a value is a function.
2360
- *
2361
- * @param value - The value to check
2362
- * @returns true if the value is a function
2363
- *
2364
- * @example
2365
- * ```typescript
2366
- * const value: unknown = () => {};
2367
- * if (isFunction(value)) {
2368
- * value(); // TypeScript knows this is a function
2369
- * }
2370
- * ```
2371
- */
2372
- declare function isFunction(value: unknown): value is (...args: any[]) => any;
2373
-
2374
- /**
2375
- * Pick specified properties from an object.
2376
- *
2377
- * Creates a new object with only the specified keys.
2378
- *
2379
- * @typeParam T - The object type
2380
- * @typeParam K - The keys to pick
2381
- * @param obj - The source object
2382
- * @param keys - The keys to pick
2383
- * @returns A new object with only the picked keys
2384
- *
2385
- * @example
2386
- * ```typescript
2387
- * const user = { name: 'John', age: 30, city: 'NYC' };
2388
- * const picked = pick(user, ['name', 'age']);
2389
- * // { name: 'John', age: 30 }
2390
- * ```
2391
- */
2392
- declare function pick<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Pick<T, K>;
2393
-
2394
- /**
2395
- * Omit specified properties from an object.
2396
- *
2397
- * Creates a new object without the specified keys.
2398
- *
2399
- * @typeParam T - The object type
2400
- * @typeParam K - The keys to omit
2401
- * @param obj - The source object
2402
- * @param keys - The keys to omit
2403
- * @returns A new object without the omitted keys
2404
- *
2405
- * @example
2406
- * ```typescript
2407
- * const user = { name: 'John', age: 30, city: 'NYC' };
2408
- * const omitted = omit(user, ['age', 'city']);
2409
- * // { name: 'John' }
2410
- * ```
2411
- */
2412
- declare function omit<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Omit<T, K>;
2413
-
2414
- /**
2415
- * Identity function that returns its input.
2416
- *
2417
- * Useful as a default selector when no transformation is needed.
2418
- *
2419
- * @typeParam T - The value type
2420
- * @param value - The value to return
2421
- * @returns The same value
2422
- *
2423
- * @example
2424
- * ```typescript
2425
- * const selector = identity;
2426
- * selector(42); // 42
2427
- * selector('hello'); // 'hello'
2428
- * ```
2429
- */
2430
- declare function identity<T>(value: T): T;
2431
-
2432
- /**
2433
- * Testing utilities for @oxog/state.
2434
- *
2435
- * Provides helpers for testing stores, state changes,
2436
- * and async effects in unit tests.
2437
- *
2438
- * @module testing
2439
- */
2440
-
2441
- /**
2442
- * Mock storage for testing persist plugin.
2443
- */
2444
- interface MockStorage {
2445
- getItem(key: string): string | null;
2446
- setItem(key: string, value: string): void;
2447
- removeItem(key: string): void;
2448
- clear(): void;
2449
- getAll(): Record<string, string>;
2450
- }
2451
- /**
2452
- * Create a mock storage for testing.
2453
- *
2454
- * @returns A mock storage implementation
2455
- *
2456
- * @example
2457
- * ```typescript
2458
- * import { createMockStorage, persist } from '@oxog/state';
2459
- *
2460
- * const mockStorage = createMockStorage();
2461
- *
2462
- * const store = createStore({ count: 0 })
2463
- * .use(persist({ key: 'test', storage: mockStorage }));
2464
- *
2465
- * store.setState({ count: 5 });
2466
- * expect(mockStorage.getItem('test')).toBe('{"count":5}');
2467
- * ```
2468
- */
2469
- declare function createMockStorage(): MockStorage;
2470
- /**
2471
- * State change record for tracking.
2472
- */
2473
- interface StateChange<TState> {
2474
- state: TState;
2475
- prevState: TState;
2476
- timestamp: number;
2477
- }
2478
- /**
2479
- * Store spy for testing state changes.
2480
- */
2481
- interface StoreSpy<TState> {
2482
- /** All recorded state changes */
2483
- changes: StateChange<TState>[];
2484
- /** Get the last state change */
2485
- lastChange: () => StateChange<TState> | undefined;
2486
- /** Get the last state */
2487
- lastState: () => TState | undefined;
2488
- /** Reset recorded changes */
2489
- reset: () => void;
2490
- /** Unsubscribe from store */
2491
- unsubscribe: () => void;
2492
- /** Wait for a specific state condition */
2493
- waitFor: (predicate: (state: TState) => boolean, timeout?: number) => Promise<TState>;
2494
- /** Wait for a specific number of changes */
2495
- waitForChanges: (count: number, timeout?: number) => Promise<StateChange<TState>[]>;
2496
- }
2497
- /**
2498
- * Create a spy to track store state changes.
2499
- *
2500
- * @param store - The store to spy on
2501
- * @returns A store spy object
2502
- *
2503
- * @example
2504
- * ```typescript
2505
- * import { createStore, spyOnStore } from '@oxog/state';
2506
- *
2507
- * const store = createStore({ count: 0 });
2508
- * const spy = spyOnStore(store);
2509
- *
2510
- * store.setState({ count: 1 });
2511
- * store.setState({ count: 2 });
2512
- *
2513
- * expect(spy.changes).toHaveLength(2);
2514
- * expect(spy.lastState()?.count).toBe(2);
2515
- * ```
2516
- */
2517
- declare function spyOnStore<TState>(store: Store<TState>): StoreSpy<TState>;
2518
- /**
2519
- * Test helper for asserting state values.
2520
- */
2521
- interface StateAssertion<TState> {
2522
- /** Assert the current state equals expected */
2523
- toEqual: (expected: Partial<TState>) => void;
2524
- /** Assert a selector value equals expected */
2525
- toHaveSelected: <T>(selector: Selector<TState, T>, expected: T) => void;
2526
- /** Assert state matches a predicate */
2527
- toMatch: (predicate: (state: TState) => boolean) => void;
2528
- }
2529
- /**
2530
- * Create assertions for a store's state.
2531
- *
2532
- * @param store - The store to assert on
2533
- * @returns State assertion helpers
2534
- *
2535
- * @example
2536
- * ```typescript
2537
- * import { createStore, assertState } from '@oxog/state';
2538
- *
2539
- * const store = createStore({ count: 0, name: 'test' });
2540
- * const assert = assertState(store);
2541
- *
2542
- * assert.toEqual({ count: 0 });
2543
- * assert.toHaveSelected(s => s.name, 'test');
2544
- * assert.toMatch(s => s.count >= 0);
2545
- * ```
2546
- */
2547
- declare function assertState<TState>(store: Store<TState>): StateAssertion<TState>;
2548
- /**
2549
- * Options for test store creation.
2550
- */
2551
- interface TestStoreOptions<TState> {
2552
- /** Initial state */
2553
- initialState: TState;
2554
- /** Whether to enable spy automatically */
2555
- spy?: boolean;
2556
- }
2557
- /**
2558
- * Test store wrapper with built-in utilities.
2559
- */
2560
- interface TestStore<TState> {
2561
- /** The underlying store */
2562
- store: Store<TState>;
2563
- /** State spy (if enabled) */
2564
- spy?: StoreSpy<TState>;
2565
- /** State assertions */
2566
- assert: StateAssertion<TState>;
2567
- /** Reset store to initial state */
2568
- reset: () => void;
2569
- /** Destroy store and cleanup */
2570
- destroy: () => void;
2571
- }
2572
- /**
2573
- * Create a test store with built-in utilities.
2574
- *
2575
- * @param options - Test store options
2576
- * @returns A test store wrapper
2577
- *
2578
- * @example
2579
- * ```typescript
2580
- * import { createTestStore } from '@oxog/state';
2581
- *
2582
- * describe('Counter', () => {
2583
- * let testStore: TestStore<{ count: number }>;
2584
- *
2585
- * beforeEach(() => {
2586
- * testStore = createTestStore({ initialState: { count: 0 }, spy: true });
2587
- * });
2588
- *
2589
- * afterEach(() => {
2590
- * testStore.destroy();
2591
- * });
2592
- *
2593
- * it('should increment count', () => {
2594
- * testStore.store.setState({ count: 1 });
2595
- * testStore.assert.toEqual({ count: 1 });
2596
- * expect(testStore.spy?.changes).toHaveLength(1);
2597
- * });
2598
- * });
2599
- * ```
2600
- */
2601
- declare function createTestStore<TState>(options: TestStoreOptions<TState>): TestStore<TState>;
2602
- /**
2603
- * Wait for a specified amount of time.
2604
- *
2605
- * @param ms - Milliseconds to wait
2606
- * @returns A promise that resolves after the delay
2607
- *
2608
- * @example
2609
- * ```typescript
2610
- * await delay(100);
2611
- * ```
2612
- */
2613
- declare function delay(ms: number): Promise<void>;
2614
- /**
2615
- * Run a function and wait for all pending microtasks.
2616
- *
2617
- * @param fn - Function to run
2618
- * @returns A promise that resolves after microtasks complete
2619
- *
2620
- * @example
2621
- * ```typescript
2622
- * await flushMicrotasks(() => {
2623
- * store.setState({ count: 1 });
2624
- * });
2625
- * ```
2626
- */
2627
- declare function flushMicrotasks(fn?: () => void): Promise<void>;
2628
- /**
2629
- * Wrap a store action for testing with call tracking.
2630
- */
2631
- interface MockedAction<TArgs extends any[], TReturn> {
2632
- /** Call the action */
2633
- (...args: TArgs): TReturn;
2634
- /** Number of times called */
2635
- callCount: number;
2636
- /** Arguments from each call */
2637
- calls: TArgs[];
2638
- /** Reset call tracking */
2639
- reset: () => void;
2640
- }
2641
- /**
2642
- * Create a mocked action for testing.
2643
- *
2644
- * @param fn - The original function
2645
- * @returns A mocked action with call tracking
2646
- *
2647
- * @example
2648
- * ```typescript
2649
- * const mockIncrement = mockAction((amount: number) => {
2650
- * store.setState(s => ({ count: s.count + amount }));
2651
- * });
2652
- *
2653
- * mockIncrement(5);
2654
- * mockIncrement(3);
2655
- *
2656
- * expect(mockIncrement.callCount).toBe(2);
2657
- * expect(mockIncrement.calls).toEqual([[5], [3]]);
2658
- * ```
2659
- */
2660
- declare function mockAction<TArgs extends any[], TReturn>(fn: (...args: TArgs) => TReturn): MockedAction<TArgs, TReturn>;
2661
- /**
2662
- * Create a snapshot of the current store state.
2663
- *
2664
- * @param store - The store to snapshot
2665
- * @returns A deep clone of the current state
2666
- *
2667
- * @example
2668
- * ```typescript
2669
- * const before = snapshot(store);
2670
- * store.setState({ count: 5 });
2671
- * const after = snapshot(store);
2672
- *
2673
- * expect(before.count).toBe(0);
2674
- * expect(after.count).toBe(5);
2675
- * ```
2676
- */
2677
- declare function snapshot<TState>(store: Store<TState>): TState;
2678
- /**
2679
- * Compare two state snapshots and return differences.
2680
- *
2681
- * @param before - State before changes
2682
- * @param after - State after changes
2683
- * @returns Object containing changed keys and their values
2684
- *
2685
- * @example
2686
- * ```typescript
2687
- * const before = { count: 0, name: 'test' };
2688
- * const after = { count: 5, name: 'test' };
2689
- *
2690
- * const diff = stateDiff(before, after);
2691
- * // { count: { before: 0, after: 5 } }
2692
- * ```
2693
- */
2694
- declare function stateDiff<TState extends Record<string, any>>(before: TState, after: TState): Record<string, {
2695
- before: any;
2696
- after: any;
2697
- }>;
2698
-
2699
- /**
2700
- * Middleware Compatibility Layer
2701
- *
2702
- * Provides a generic middleware pattern for state management,
2703
- * enabling compatibility with various middleware ecosystems.
2704
- *
2705
- * @module compat/middleware
2706
- */
2707
-
2708
- /**
2709
- * Middleware-style SetState function.
2710
- */
2711
- type MiddlewareSetState<T> = {
2712
- (partial: Partial<T> | ((state: T) => Partial<T>), replace?: boolean): void;
2713
- };
2714
- /**
2715
- * Middleware-style GetState function.
2716
- */
2717
- type MiddlewareGetState<T> = () => T;
2718
- /**
2719
- * Middleware-style Subscribe function.
2720
- */
2721
- type MiddlewareSubscribe<T> = (listener: (state: T, prevState: T) => void) => () => void;
2722
- /**
2723
- * Generic StoreApi for middleware compatibility.
2724
- */
2725
- interface MiddlewareStoreApi<T> {
2726
- setState: MiddlewareSetState<T>;
2727
- getState: MiddlewareGetState<T>;
2728
- subscribe: MiddlewareSubscribe<T>;
2729
- destroy?: () => void;
2730
- }
2731
- /**
2732
- * State creator function for middleware pattern.
2733
- */
2734
- type StateCreatorFn<T, _Mps extends unknown[] = [], _Mcs extends unknown[] = []> = (set: MiddlewareSetState<T>, get: MiddlewareGetState<T>, api: MiddlewareStoreApi<T>) => T;
2735
- /**
2736
- * Generic Middleware type.
2737
- */
2738
- type MiddlewareFn<T, Mps extends unknown[] = [], Mcs extends unknown[] = []> = (creator: StateCreatorFn<T, Mps, Mcs>) => StateCreatorFn<T, Mps, Mcs>;
2739
- /**
2740
- * Convert an @oxog/state store to middleware-compatible API.
2741
- *
2742
- * @param store - An @oxog/state store
2743
- * @returns A middleware-compatible store API
2744
- *
2745
- * @example
2746
- * ```typescript
2747
- * import { createStore, toMiddlewareApi } from '@oxog/state';
2748
- *
2749
- * const store = createStore({ count: 0 });
2750
- * const api = toMiddlewareApi(store);
2751
- *
2752
- * // Use middleware-style API
2753
- * api.setState({ count: 1 });
2754
- * api.setState((state) => ({ count: state.count + 1 }));
2755
- * console.log(api.getState()); // { count: 2 }
2756
- * ```
2757
- */
2758
- declare function toMiddlewareApi<T>(store: Store<T>): MiddlewareStoreApi<T>;
2759
- /**
2760
- * Wrap a middleware to work as an @oxog/state plugin.
2761
- *
2762
- * @param middleware - A middleware function
2763
- * @param options - Optional middleware options
2764
- * @returns An @oxog/state plugin
2765
- *
2766
- * @example
2767
- * ```typescript
2768
- * import { createStore, middlewareCompat } from '@oxog/state';
2769
- *
2770
- * // Use external middleware with @oxog/state
2771
- * const store = createStore({ count: 0 })
2772
- * .use(middlewareCompat(someMiddleware, { name: 'MyStore' }));
2773
- * ```
2774
- */
2775
- declare function middlewareCompat<T>(middleware: MiddlewareFn<T>, _options?: Record<string, unknown>): Plugin<T>;
2776
- /**
2777
- * Create a store using middleware-style state creator.
2778
- *
2779
- * @param creator - Middleware-style state creator function
2780
- * @returns A store API
2781
- *
2782
- * @example
2783
- * ```typescript
2784
- * import { createWithMiddleware } from '@oxog/state';
2785
- *
2786
- * const store = createWithMiddleware((set, get) => ({
2787
- * count: 0,
2788
- * increment: () => set((state) => ({ count: state.count + 1 })),
2789
- * decrement: () => set((state) => ({ count: state.count - 1 })),
2790
- * reset: () => set({ count: 0 }),
2791
- * getDoubled: () => get().count * 2,
2792
- * }));
2793
- *
2794
- * store.getState().increment();
2795
- * console.log(store.getState().count); // 1
2796
- * ```
2797
- */
2798
- declare function createWithMiddleware<T extends object>(creator: StateCreatorFn<T>): MiddlewareStoreApi<T> & {
2799
- use: (plugin: Plugin<T>) => MiddlewareStoreApi<T>;
2800
- };
2801
- /**
2802
- * Create a simple middleware.
2803
- *
2804
- * @param name - Middleware name
2805
- * @param enhancer - Function that enhances the state creator
2806
- * @returns A middleware function
2807
- *
2808
- * @example
2809
- * ```typescript
2810
- * const loggerMiddleware = createSimpleMiddleware('logger', (creator) => (set, get, api) => {
2811
- * const loggedSet: typeof set = (partial, replace) => {
2812
- * console.log('Before:', get());
2813
- * set(partial, replace);
2814
- * console.log('After:', get());
2815
- * };
2816
- * return creator(loggedSet, get, api);
2817
- * });
2818
- *
2819
- * const store = createStore({ count: 0 })
2820
- * .use(middlewareCompat(loggerMiddleware));
2821
- * ```
2822
- */
2823
- declare function createSimpleMiddleware<T>(name: string, enhancer: (creator: StateCreatorFn<T>) => StateCreatorFn<T>): MiddlewareFn<T>;
2824
- /**
2825
- * Compose multiple middlewares.
2826
- *
2827
- * @param middlewares - Array of middlewares
2828
- * @returns A single composed middleware
2829
- *
2830
- * @example
2831
- * ```typescript
2832
- * import { compose, middlewareCompat } from '@oxog/state';
2833
- *
2834
- * const composedMiddleware = compose(
2835
- * loggerMiddleware,
2836
- * devtoolsMiddleware,
2837
- * persistMiddleware,
2838
- * );
2839
- *
2840
- * const store = createStore({ count: 0 })
2841
- * .use(middlewareCompat(composedMiddleware));
2842
- * ```
2843
- */
2844
- declare function compose<T>(...middlewares: MiddlewareFn<T>[]): MiddlewareFn<T>;
2845
- /**
2846
- * Type helper for extracting state type from a store API.
2847
- */
2848
- type ExtractStateType<S> = S extends MiddlewareStoreApi<infer T> ? T : never;
2849
- /**
2850
- * Type helper for selector function.
2851
- */
2852
- type SelectorFn<T, U> = (state: T) => U;
2853
- /**
2854
- * Type helper for equality function.
2855
- */
2856
- type EqualityCheck<T> = (a: T, b: T) => boolean;
2857
-
2858
- export { type Action, type Actions, type BoundAction, type BoundActions, type Computed, type ComputedOptions, type CreatedStore, type DeepPartial, type DevtoolsOptions, type EffectCleanup, type EffectDefinition, type EffectFn, type EffectUtils, type EffectsOptions, type EqualityCheck, type EqualityFn, type ExtractStateType, type FederatedState, type Federation, type FederationListener, type FederationOptions, type GetSlice, type HistoryOptions, type HistoryStore, type InlineActions, type Listener, type LogLevel, type LoggerOptions, type MiddlewareFn, type MiddlewareGetState, type MiddlewareSetState, type MiddlewareStoreApi, type MiddlewareSubscribe, type MockStorage, type MockedAction, type PersistOptions, type Plugin, type Selector, type SelectorFn, type SelectorOptions, type SetSlice, type SliceCreator, type SliceDefinition, type StateAssertion, type StateChange, type StateCreatorFn, type StateWithActions, type StateWithoutInlineActions, type StorageLike$1 as StorageLike, type Store, type StoreBuilder, StoreError, StoreError as StoreErrorClass, StoreErrorCode, type StoreOptions, type StoreSpy, type StoreState, type SubscribeOptions, type SyncOptions, type TestStore, type TestStoreOptions, type TransactionFn, type ValidateOptions, type ValidationAPI, type ValidationError, type ValidationResult, type ValidationTiming, type ValidatorFn, assertState, batch, combineComputed, combineEffects, combineSlices, combineValidators, compose, computed, createAsyncValidator, createDebouncedEffect, createEffect, createFederatedComputed, createFederatedSelector, createFederation, createFieldValidator, createLogger, createMockStorage, createNamespacedSlice, createSimpleEffect, createSimpleMiddleware, createSlice, createStorage, createStore, createSubscriber, createTestStore, createValidator, createWithMiddleware, deepClone, deepEqual, deepMerge, delay, devtools, effects, extendStore, flushMicrotasks, hasHistory, history, identity, immer, isFunction, logger, memoizeSelector, middlewareCompat, mockAction, omit, persist, pick, produce, resetSlices, selector, sessionStorage, shallowEqual, snapshot, spyOnStore, stateDiff, subscribeOnce, subscribeToMany, subscribeWithOptions, sync, toMiddlewareApi, triggerSync, useAction, useCreateStore, useSetState, useShallow, useStore, useStoreActions, useStoreSelector, useTransientSubscribe, validate, waitForFederated };
253
+ export { EqualityFn, Selector, Store, useAction, useCreateStore, useSetState, useShallow, useStore, useStoreActions, useStoreSelector, useTransientSubscribe };