@oxog/state 1.0.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +414 -101
- package/dist/iife/index.global.js +1 -47
- package/dist/index.cjs +2355 -314
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2100 -303
- package/dist/index.d.ts +2100 -303
- package/dist/index.js +2310 -316
- package/dist/index.js.map +1 -1
- package/package.json +23 -11
package/dist/index.d.cts
CHANGED
|
@@ -34,7 +34,7 @@ type DeepPartial<T> = T extends object ? {
|
|
|
34
34
|
* });
|
|
35
35
|
* ```
|
|
36
36
|
*/
|
|
37
|
-
type Action<TState, TArgs extends unknown[] = []> = (state: TState, ...args: TArgs) => Partial<TState> | Promise<Partial<TState
|
|
37
|
+
type Action<TState, TArgs extends unknown[] = any[]> = (state: TState, ...args: TArgs) => Partial<TState> | void | Promise<Partial<TState> | void>;
|
|
38
38
|
/**
|
|
39
39
|
* Collection of actions indexed by name.
|
|
40
40
|
*
|
|
@@ -48,7 +48,46 @@ type Action<TState, TArgs extends unknown[] = []> = (state: TState, ...args: TAr
|
|
|
48
48
|
* };
|
|
49
49
|
* ```
|
|
50
50
|
*/
|
|
51
|
-
type Actions<TState> = Record<string, Action<TState>>;
|
|
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>;
|
|
52
91
|
/**
|
|
53
92
|
* Selector function to extract a slice of state.
|
|
54
93
|
*
|
|
@@ -264,7 +303,7 @@ interface Store<TState> {
|
|
|
264
303
|
* store.use(persist({ key: 'app' }));
|
|
265
304
|
* ```
|
|
266
305
|
*/
|
|
267
|
-
use
|
|
306
|
+
use(plugin: Plugin<TState>, options?: unknown): this;
|
|
268
307
|
/** Destroy store and cleanup all resources */
|
|
269
308
|
destroy(): void;
|
|
270
309
|
}
|
|
@@ -288,7 +327,9 @@ interface StoreBuilder<TState> extends Store<TState> {
|
|
|
288
327
|
* @param fn - Action function
|
|
289
328
|
* @returns The builder for chaining
|
|
290
329
|
*/
|
|
291
|
-
action<K extends string
|
|
330
|
+
action<K extends string, F extends Action<TState, any[]>>(name: K, fn: F): this & {
|
|
331
|
+
[P in K]: BoundAction<F>;
|
|
332
|
+
};
|
|
292
333
|
}
|
|
293
334
|
/**
|
|
294
335
|
* Error codes for store errors.
|
|
@@ -313,6 +354,37 @@ declare class StoreError extends Error {
|
|
|
313
354
|
constructor(code: StoreErrorCode, message: string);
|
|
314
355
|
}
|
|
315
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
|
+
|
|
316
388
|
/**
|
|
317
389
|
* Create a new reactive store.
|
|
318
390
|
*
|
|
@@ -345,31 +417,9 @@ declare class StoreError extends Error {
|
|
|
345
417
|
* .action('increment', (state) => ({ count: state.count + 1 }));
|
|
346
418
|
* ```
|
|
347
419
|
*/
|
|
348
|
-
declare function createStore<TState
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
*
|
|
352
|
-
* @param fn - Function containing state updates
|
|
353
|
-
* @returns The return value of fn
|
|
354
|
-
*
|
|
355
|
-
* @example
|
|
356
|
-
* ```typescript
|
|
357
|
-
* import { batch } from '@oxog/state';
|
|
358
|
-
*
|
|
359
|
-
* // Without batch - 3 re-renders
|
|
360
|
-
* store.setState({ a: 1 });
|
|
361
|
-
* store.setState({ b: 2 });
|
|
362
|
-
* store.setState({ c: 3 });
|
|
363
|
-
*
|
|
364
|
-
* // With batch - 1 re-render
|
|
365
|
-
* batch(() => {
|
|
366
|
-
* store.setState({ a: 1 });
|
|
367
|
-
* store.setState({ b: 2 });
|
|
368
|
-
* store.setState({ c: 3 });
|
|
369
|
-
* });
|
|
370
|
-
* ```
|
|
371
|
-
*/
|
|
372
|
-
declare function batch<T>(fn: () => T): T;
|
|
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>;
|
|
373
423
|
|
|
374
424
|
/**
|
|
375
425
|
* React hook for subscribing to store state changes.
|
|
@@ -422,7 +472,9 @@ declare function useStore<TState, TSelected = TState>(store: Store<TState>, sele
|
|
|
422
472
|
/**
|
|
423
473
|
* React hook for creating and using a store.
|
|
424
474
|
*
|
|
425
|
-
* Creates a store on first render and destroys it
|
|
475
|
+
* Creates a store on first render and destroys it after the component
|
|
476
|
+
* unmounts. Safe under React StrictMode (the simulated unmount/remount in
|
|
477
|
+
* development does not destroy the store).
|
|
426
478
|
*
|
|
427
479
|
* @typeParam TState - The store state type
|
|
428
480
|
* @param initialState - The initial state
|
|
@@ -478,421 +530,1739 @@ declare function useCreateStore<TState>(initialState: TState): Store<TState>;
|
|
|
478
530
|
* ```
|
|
479
531
|
*/
|
|
480
532
|
declare function useAction<TState, TAction extends (...args: any[]) => any>(store: Store<TState>, actionName: string): TAction;
|
|
481
|
-
|
|
482
|
-
/**
|
|
483
|
-
* Plugin-specific types and interfaces.
|
|
484
|
-
*/
|
|
485
|
-
|
|
486
|
-
/**
|
|
487
|
-
* Persist plugin options.
|
|
488
|
-
*/
|
|
489
|
-
interface PersistOptions<TState> {
|
|
490
|
-
/** Storage key */
|
|
491
|
-
key: string;
|
|
492
|
-
/** Storage implementation (defaults to localStorage) */
|
|
493
|
-
storage?: StorageLike;
|
|
494
|
-
/** List of state keys to persist (whitelist) */
|
|
495
|
-
whitelist?: Array<keyof TState>;
|
|
496
|
-
/** List of state keys to exclude (blacklist) */
|
|
497
|
-
blacklist?: Array<keyof TState>;
|
|
498
|
-
}
|
|
499
|
-
/**
|
|
500
|
-
* Storage interface for persistence.
|
|
501
|
-
*/
|
|
502
|
-
interface StorageLike {
|
|
503
|
-
getItem(key: string): string | null;
|
|
504
|
-
setItem(key: string, value: string): void;
|
|
505
|
-
removeItem(key: string): void;
|
|
506
|
-
}
|
|
507
|
-
/**
|
|
508
|
-
* Devtools plugin options.
|
|
509
|
-
*/
|
|
510
|
-
interface DevtoolsOptions {
|
|
511
|
-
/** Store name for DevTools */
|
|
512
|
-
name?: string;
|
|
513
|
-
/** Enable/disable DevTools */
|
|
514
|
-
enabled?: boolean;
|
|
515
|
-
/** Maximum number of states to keep in history */
|
|
516
|
-
maxAge?: number;
|
|
517
|
-
}
|
|
518
|
-
/**
|
|
519
|
-
* History plugin options.
|
|
520
|
-
*/
|
|
521
|
-
interface HistoryOptions<TState> {
|
|
522
|
-
/** Maximum number of past states to keep */
|
|
523
|
-
limit?: number;
|
|
524
|
-
/** Keys to track for history (empty array tracks all) */
|
|
525
|
-
keys?: Array<keyof TState>;
|
|
526
|
-
}
|
|
527
|
-
/**
|
|
528
|
-
* Sync plugin options.
|
|
529
|
-
*/
|
|
530
|
-
interface SyncOptions {
|
|
531
|
-
/** Channel name for BroadcastChannel */
|
|
532
|
-
channel?: string;
|
|
533
|
-
}
|
|
534
|
-
/**
|
|
535
|
-
* Selector plugin options.
|
|
536
|
-
*/
|
|
537
|
-
interface SelectorOptions<TState> {
|
|
538
|
-
/** Map of computed selectors */
|
|
539
|
-
selectors: {
|
|
540
|
-
[K in keyof TState]?: (state: TState) => TState[K];
|
|
541
|
-
};
|
|
542
|
-
}
|
|
543
|
-
/**
|
|
544
|
-
* History-enabled store interface.
|
|
545
|
-
*/
|
|
546
|
-
interface HistoryStore<TState> extends Store<TState> {
|
|
547
|
-
undo(): void;
|
|
548
|
-
redo(): void;
|
|
549
|
-
clearHistory(): void;
|
|
550
|
-
canUndo(): boolean;
|
|
551
|
-
canRedo(): boolean;
|
|
552
|
-
}
|
|
553
|
-
|
|
554
533
|
/**
|
|
555
|
-
*
|
|
534
|
+
* Create a shallow equality wrapper for selectors.
|
|
556
535
|
*
|
|
557
|
-
*
|
|
558
|
-
*
|
|
536
|
+
* Use this hook to wrap selectors that return objects or arrays
|
|
537
|
+
* and you want to avoid re-renders when the content hasn't changed.
|
|
538
|
+
*
|
|
539
|
+
* @param selector - The selector function to wrap
|
|
540
|
+
* @returns A wrapped selector with shallow equality
|
|
559
541
|
*
|
|
560
542
|
* @example
|
|
561
543
|
* ```typescript
|
|
562
|
-
* import {
|
|
544
|
+
* import { useStore, useShallow } from '@oxog/state';
|
|
563
545
|
*
|
|
564
|
-
*
|
|
565
|
-
*
|
|
566
|
-
*
|
|
567
|
-
*
|
|
568
|
-
*
|
|
569
|
-
* }
|
|
546
|
+
* function UserInfo() {
|
|
547
|
+
* // Without useShallow - re-renders on every state change
|
|
548
|
+
* const { name, email } = useStore(store, s => ({ name: s.name, email: s.email }));
|
|
549
|
+
*
|
|
550
|
+
* // With useShallow - only re-renders when name or email actually changes
|
|
551
|
+
* const { name, email } = useStore(
|
|
552
|
+
* store,
|
|
553
|
+
* useShallow(s => ({ name: s.name, email: s.email }))
|
|
554
|
+
* );
|
|
555
|
+
* }
|
|
570
556
|
* ```
|
|
571
557
|
*/
|
|
572
|
-
|
|
573
|
-
/**
|
|
574
|
-
* SessionStorage implementation.
|
|
575
|
-
*/
|
|
576
|
-
declare const sessionStorage: StorageLike;
|
|
558
|
+
declare function useShallow<TState, TSelected extends object>(selector: Selector<TState, TSelected>): Selector<TState, TSelected>;
|
|
577
559
|
/**
|
|
578
|
-
*
|
|
560
|
+
* Hook for selecting multiple actions from a store.
|
|
579
561
|
*
|
|
580
|
-
*
|
|
581
|
-
*
|
|
562
|
+
* Returns stable references to actions that don't change between renders.
|
|
563
|
+
*
|
|
564
|
+
* @param store - The store instance
|
|
565
|
+
* @param actionNames - Names of actions to select
|
|
566
|
+
* @returns An object with the selected actions
|
|
582
567
|
*
|
|
583
568
|
* @example
|
|
584
569
|
* ```typescript
|
|
585
|
-
* import {
|
|
586
|
-
*
|
|
587
|
-
* // Using localStorage (default)
|
|
588
|
-
* const store = createStore({ count: 0 })
|
|
589
|
-
* .use(persist({ key: 'counter' }));
|
|
590
|
-
*
|
|
591
|
-
* // Using sessionStorage
|
|
592
|
-
* const store = createStore({ count: 0 })
|
|
593
|
-
* .use(persist({ key: 'counter', storage: sessionStorage }));
|
|
570
|
+
* import { useStoreActions } from '@oxog/state';
|
|
594
571
|
*
|
|
595
|
-
*
|
|
596
|
-
*
|
|
597
|
-
*
|
|
572
|
+
* function Counter() {
|
|
573
|
+
* const { increment, decrement, reset } = useStoreActions(
|
|
574
|
+
* store,
|
|
575
|
+
* 'increment',
|
|
576
|
+
* 'decrement',
|
|
577
|
+
* 'reset'
|
|
578
|
+
* );
|
|
598
579
|
*
|
|
599
|
-
*
|
|
600
|
-
*
|
|
601
|
-
*
|
|
580
|
+
* return (
|
|
581
|
+
* <>
|
|
582
|
+
* <button onClick={decrement}>-</button>
|
|
583
|
+
* <button onClick={increment}>+</button>
|
|
584
|
+
* <button onClick={reset}>Reset</button>
|
|
585
|
+
* </>
|
|
586
|
+
* );
|
|
587
|
+
* }
|
|
602
588
|
* ```
|
|
603
589
|
*/
|
|
604
|
-
declare function
|
|
590
|
+
declare function useStoreActions<TState, TKeys extends string[]>(store: Store<TState>, ...actionNames: TKeys): {
|
|
591
|
+
[K in TKeys[number]]: (...args: any[]) => any;
|
|
592
|
+
};
|
|
605
593
|
/**
|
|
606
|
-
*
|
|
594
|
+
* Hook for selecting multiple values with independent selectors.
|
|
607
595
|
*
|
|
608
|
-
*
|
|
609
|
-
*
|
|
596
|
+
* Each selector is tracked independently, so the component only
|
|
597
|
+
* re-renders when a selector's output actually changes.
|
|
598
|
+
*
|
|
599
|
+
* @param store - The store instance
|
|
600
|
+
* @param selectors - Object of named selectors
|
|
601
|
+
* @returns An object with selected values
|
|
610
602
|
*
|
|
611
603
|
* @example
|
|
612
604
|
* ```typescript
|
|
613
|
-
* import {
|
|
605
|
+
* import { useStoreSelector } from '@oxog/state';
|
|
614
606
|
*
|
|
615
|
-
*
|
|
616
|
-
*
|
|
617
|
-
*
|
|
618
|
-
*
|
|
619
|
-
*
|
|
607
|
+
* function Dashboard() {
|
|
608
|
+
* const { userCount, activeUsers, totalRevenue } = useStoreSelector(store, {
|
|
609
|
+
* userCount: s => s.users.length,
|
|
610
|
+
* activeUsers: s => s.users.filter(u => u.active).length,
|
|
611
|
+
* totalRevenue: s => s.orders.reduce((sum, o) => sum + o.total, 0),
|
|
612
|
+
* });
|
|
613
|
+
*
|
|
614
|
+
* return (
|
|
615
|
+
* <div>
|
|
616
|
+
* <p>Users: {userCount} ({activeUsers} active)</p>
|
|
617
|
+
* <p>Revenue: ${totalRevenue}</p>
|
|
618
|
+
* </div>
|
|
619
|
+
* );
|
|
620
|
+
* }
|
|
620
621
|
* ```
|
|
621
622
|
*/
|
|
622
|
-
declare function
|
|
623
|
-
|
|
623
|
+
declare function useStoreSelector<TState, TSelectors extends Record<string, Selector<TState, any>>>(store: Store<TState>, selectors: TSelectors): {
|
|
624
|
+
[K in keyof TSelectors]: ReturnType<TSelectors[K]>;
|
|
625
|
+
};
|
|
624
626
|
/**
|
|
625
|
-
*
|
|
627
|
+
* Hook for transient updates - subscribe without causing re-renders.
|
|
626
628
|
*
|
|
627
|
-
*
|
|
629
|
+
* Use this for side effects that don't need to update the UI.
|
|
630
|
+
*
|
|
631
|
+
* @param store - The store instance
|
|
632
|
+
* @param selector - Selector function
|
|
633
|
+
* @param callback - Callback to run on changes
|
|
628
634
|
*
|
|
629
635
|
* @example
|
|
630
636
|
* ```typescript
|
|
631
|
-
* import {
|
|
637
|
+
* import { useTransientSubscribe } from '@oxog/state';
|
|
632
638
|
*
|
|
633
|
-
*
|
|
634
|
-
*
|
|
639
|
+
* function Analytics() {
|
|
640
|
+
* // Track page views without re-rendering
|
|
641
|
+
* useTransientSubscribe(
|
|
642
|
+
* store,
|
|
643
|
+
* s => s.currentPage,
|
|
644
|
+
* (page) => analytics.track('pageview', { page })
|
|
645
|
+
* );
|
|
646
|
+
*
|
|
647
|
+
* return <div>...</div>;
|
|
648
|
+
* }
|
|
635
649
|
* ```
|
|
636
650
|
*/
|
|
637
|
-
|
|
651
|
+
declare function useTransientSubscribe<TState, TSelected>(store: Store<TState>, selector: Selector<TState, TSelected>, callback: (value: TSelected, prevValue: TSelected) => void, equalityFn?: EqualityFn<TSelected>): void;
|
|
638
652
|
/**
|
|
639
|
-
*
|
|
653
|
+
* Hook that returns the store's setState function with stable reference.
|
|
640
654
|
*
|
|
641
|
-
* @param
|
|
642
|
-
* @returns
|
|
655
|
+
* @param store - The store instance
|
|
656
|
+
* @returns The setState function
|
|
643
657
|
*
|
|
644
658
|
* @example
|
|
645
659
|
* ```typescript
|
|
646
|
-
*
|
|
660
|
+
* function Form() {
|
|
661
|
+
* const setState = useSetState(store);
|
|
647
662
|
*
|
|
648
|
-
*
|
|
649
|
-
*
|
|
650
|
-
*
|
|
663
|
+
* const handleChange = (e) => {
|
|
664
|
+
* setState({ [e.target.name]: e.target.value });
|
|
665
|
+
* };
|
|
651
666
|
*
|
|
652
|
-
*
|
|
653
|
-
*
|
|
654
|
-
* .use(devtools({
|
|
655
|
-
* name: 'My Store',
|
|
656
|
-
* enabled: process.env.NODE_ENV === 'development'
|
|
657
|
-
* }));
|
|
667
|
+
* return <input onChange={handleChange} />;
|
|
668
|
+
* }
|
|
658
669
|
* ```
|
|
659
670
|
*/
|
|
660
|
-
declare function
|
|
671
|
+
declare function useSetState<TState>(store: Store<TState>): (partial: Partial<TState> | ((state: TState) => Partial<TState>)) => void;
|
|
661
672
|
|
|
662
673
|
/**
|
|
663
|
-
*
|
|
674
|
+
* Enhanced subscription system with advanced options.
|
|
664
675
|
*
|
|
665
|
-
*
|
|
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
|
|
666
684
|
*
|
|
667
685
|
* @example
|
|
668
686
|
* ```typescript
|
|
669
|
-
*
|
|
670
|
-
*
|
|
671
|
-
*
|
|
672
|
-
*
|
|
673
|
-
*
|
|
674
|
-
* // Now store has undo() and redo() methods
|
|
675
|
-
* store.setState({ count: 1 });
|
|
676
|
-
* store.setState({ count: 2 });
|
|
677
|
-
* store.undo(); // { count: 1 }
|
|
678
|
-
* store.redo(); // { count: 2 }
|
|
687
|
+
* const options: SubscribeOptions<State, number> = {
|
|
688
|
+
* debounce: 100,
|
|
689
|
+
* fireImmediately: true,
|
|
690
|
+
* when: (state) => state.isReady
|
|
691
|
+
* };
|
|
679
692
|
* ```
|
|
680
693
|
*/
|
|
681
|
-
|
|
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
|
+
}
|
|
682
706
|
/**
|
|
683
|
-
*
|
|
707
|
+
* Enhanced subscribe function with advanced options.
|
|
684
708
|
*
|
|
685
|
-
* @param
|
|
686
|
-
* @
|
|
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
|
|
687
714
|
*
|
|
688
715
|
* @example
|
|
689
716
|
* ```typescript
|
|
690
|
-
*
|
|
691
|
-
*
|
|
692
|
-
*
|
|
693
|
-
*
|
|
694
|
-
*
|
|
717
|
+
* // With debounce
|
|
718
|
+
* const unsubscribe = subscribeWithOptions(
|
|
719
|
+
* store,
|
|
720
|
+
* (state) => state.searchQuery,
|
|
721
|
+
* (query) => performSearch(query),
|
|
722
|
+
* { debounce: 300 }
|
|
723
|
+
* );
|
|
695
724
|
*
|
|
696
|
-
* //
|
|
697
|
-
* const
|
|
698
|
-
*
|
|
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
|
+
* );
|
|
699
732
|
*
|
|
700
|
-
* //
|
|
701
|
-
* const
|
|
702
|
-
*
|
|
733
|
+
* // Fire immediately
|
|
734
|
+
* const unsubscribe = subscribeWithOptions(
|
|
735
|
+
* store,
|
|
736
|
+
* (state) => state.user,
|
|
737
|
+
* (user) => console.log('User:', user),
|
|
738
|
+
* { fireImmediately: true }
|
|
739
|
+
* );
|
|
703
740
|
* ```
|
|
704
741
|
*/
|
|
705
|
-
declare function
|
|
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>;
|
|
706
1533
|
/**
|
|
707
1534
|
* Check if a store has history capabilities.
|
|
708
1535
|
*
|
|
709
|
-
* @param store - The store to check
|
|
710
|
-
* @returns true if store supports undo/redo
|
|
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
|
|
711
1636
|
*
|
|
712
1637
|
* @example
|
|
713
1638
|
* ```typescript
|
|
714
|
-
* import {
|
|
1639
|
+
* import { produce } from '@oxog/state';
|
|
715
1640
|
*
|
|
716
|
-
*
|
|
717
|
-
*
|
|
718
|
-
*
|
|
719
|
-
* }
|
|
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
|
|
720
1646
|
* ```
|
|
721
1647
|
*/
|
|
722
|
-
declare function
|
|
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>;
|
|
723
1673
|
|
|
724
1674
|
/**
|
|
725
|
-
*
|
|
1675
|
+
* Selector plugin - Computed/derived values.
|
|
726
1676
|
*
|
|
727
|
-
*
|
|
1677
|
+
* Define computed values that automatically update when dependencies change.
|
|
728
1678
|
*
|
|
729
1679
|
* @example
|
|
730
1680
|
* ```typescript
|
|
731
|
-
* import { createStore,
|
|
1681
|
+
* import { createStore, selector } from '@oxog/state';
|
|
732
1682
|
*
|
|
733
|
-
* const store = createStore({
|
|
734
|
-
*
|
|
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
|
+
* }));
|
|
735
1698
|
*
|
|
736
|
-
* //
|
|
1699
|
+
* // Access computed values
|
|
1700
|
+
* const state = store.getState();
|
|
1701
|
+
* console.log(state.filteredItems); // Computed value
|
|
737
1702
|
* ```
|
|
738
1703
|
*/
|
|
739
1704
|
|
|
740
1705
|
/**
|
|
741
|
-
* Create a
|
|
1706
|
+
* Create a selector plugin for computed values.
|
|
742
1707
|
*
|
|
743
|
-
* @param options - Plugin options
|
|
744
|
-
* @returns A
|
|
1708
|
+
* @param options - Plugin options with selectors
|
|
1709
|
+
* @returns A selector plugin
|
|
745
1710
|
*
|
|
746
1711
|
* @example
|
|
747
1712
|
* ```typescript
|
|
748
|
-
* import {
|
|
1713
|
+
* import { selector } from '@oxog/state';
|
|
749
1714
|
*
|
|
750
|
-
*
|
|
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
|
|
751
1782
|
* const store = createStore({ count: 0 })
|
|
752
|
-
* .use(
|
|
1783
|
+
* .use(logger());
|
|
753
1784
|
*
|
|
754
|
-
* //
|
|
1785
|
+
* // With options
|
|
755
1786
|
* const store = createStore({ count: 0 })
|
|
756
|
-
* .use(
|
|
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
|
+
* }));
|
|
757
1799
|
* ```
|
|
758
1800
|
*/
|
|
759
|
-
declare function
|
|
1801
|
+
declare function logger<TState = unknown>(options?: LoggerOptions<TState>): Plugin<TState>;
|
|
760
1802
|
/**
|
|
761
|
-
*
|
|
1803
|
+
* Create a logger with preset options.
|
|
762
1804
|
*
|
|
763
|
-
* @param
|
|
764
|
-
* @
|
|
1805
|
+
* @param defaultOptions - Default options
|
|
1806
|
+
* @returns A logger factory function
|
|
765
1807
|
*
|
|
766
1808
|
* @example
|
|
767
1809
|
* ```typescript
|
|
768
|
-
*
|
|
1810
|
+
* const devLogger = createLogger({
|
|
1811
|
+
* enabled: process.env.NODE_ENV === 'development',
|
|
1812
|
+
* collapsed: true,
|
|
1813
|
+
* });
|
|
769
1814
|
*
|
|
770
1815
|
* const store = createStore({ count: 0 })
|
|
771
|
-
* .use(
|
|
772
|
-
*
|
|
773
|
-
* // Manually trigger sync
|
|
774
|
-
* triggerSync(store, 'my-app');
|
|
1816
|
+
* .use(devLogger({ name: 'Counter' }));
|
|
775
1817
|
* ```
|
|
776
1818
|
*/
|
|
777
|
-
declare function
|
|
1819
|
+
declare function createLogger<TState = unknown>(defaultOptions?: LoggerOptions<TState>): (options?: LoggerOptions<TState>) => Plugin<TState>;
|
|
778
1820
|
|
|
779
1821
|
/**
|
|
780
|
-
*
|
|
1822
|
+
* Effects plugin for managing side effects.
|
|
781
1823
|
*
|
|
782
|
-
*
|
|
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
|
|
783
1890
|
*
|
|
784
1891
|
* @example
|
|
785
1892
|
* ```typescript
|
|
786
|
-
* import { createStore,
|
|
1893
|
+
* import { createStore, effects } from '@oxog/state';
|
|
787
1894
|
*
|
|
788
1895
|
* const store = createStore({
|
|
789
|
-
*
|
|
790
|
-
*
|
|
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.
|
|
791
1927
|
*
|
|
792
|
-
*
|
|
793
|
-
*
|
|
794
|
-
*
|
|
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(),
|
|
795
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
|
+
* }));
|
|
796
2185
|
* ```
|
|
797
2186
|
*/
|
|
798
|
-
|
|
2187
|
+
declare function validate<TState>(options: ValidateOptions<TState>): Plugin<TState>;
|
|
799
2188
|
/**
|
|
800
|
-
*
|
|
2189
|
+
* Create a simple boolean validator.
|
|
801
2190
|
*
|
|
802
|
-
* @param
|
|
803
|
-
* @param
|
|
804
|
-
* @returns
|
|
2191
|
+
* @param predicate - Validation predicate function
|
|
2192
|
+
* @param message - Error message when validation fails
|
|
2193
|
+
* @returns A validator function
|
|
805
2194
|
*
|
|
806
2195
|
* @example
|
|
807
2196
|
* ```typescript
|
|
808
|
-
*
|
|
2197
|
+
* const isPositive = createValidator(
|
|
2198
|
+
* (state) => state.count >= 0,
|
|
2199
|
+
* 'Count must be positive'
|
|
2200
|
+
* );
|
|
809
2201
|
*
|
|
810
|
-
* const
|
|
811
|
-
*
|
|
812
|
-
* draft.users[0].age = 31;
|
|
813
|
-
* });
|
|
2202
|
+
* const store = createStore({ count: 0 })
|
|
2203
|
+
* .use(validate({ schema: isPositive }));
|
|
814
2204
|
* ```
|
|
815
2205
|
*/
|
|
816
|
-
declare function
|
|
2206
|
+
declare function createValidator<T>(predicate: (state: T) => boolean, message: string): (state: T) => ValidationResult;
|
|
817
2207
|
/**
|
|
818
|
-
*
|
|
2208
|
+
* Combine multiple validators into one.
|
|
819
2209
|
*
|
|
820
|
-
* @
|
|
2210
|
+
* @param validators - Array of validator functions
|
|
2211
|
+
* @returns Combined validator function
|
|
821
2212
|
*
|
|
822
2213
|
* @example
|
|
823
2214
|
* ```typescript
|
|
824
|
-
*
|
|
825
|
-
*
|
|
826
|
-
*
|
|
827
|
-
*
|
|
828
|
-
* }).use(immer());
|
|
2215
|
+
* const combinedValidator = combineValidators(
|
|
2216
|
+
* createValidator((s) => s.name.length > 0, 'Name required'),
|
|
2217
|
+
* createValidator((s) => s.age >= 18, 'Must be 18+'),
|
|
2218
|
+
* );
|
|
829
2219
|
*
|
|
830
|
-
*
|
|
831
|
-
*
|
|
832
|
-
* draft.items[0].name = 'Updated Item';
|
|
833
|
-
* draft.items.push({ id: 2, name: 'Item 2' });
|
|
834
|
-
* });
|
|
2220
|
+
* const store = createStore({ name: '', age: 0 })
|
|
2221
|
+
* .use(validate({ schema: combinedValidator }));
|
|
835
2222
|
* ```
|
|
836
2223
|
*/
|
|
837
|
-
declare function
|
|
838
|
-
|
|
2224
|
+
declare function combineValidators<T>(...validators: ValidatorFn<T>[]): (state: T) => ValidationResult;
|
|
839
2225
|
/**
|
|
840
|
-
*
|
|
2226
|
+
* Create a field-level validator.
|
|
841
2227
|
*
|
|
842
|
-
*
|
|
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
|
|
843
2232
|
*
|
|
844
2233
|
* @example
|
|
845
2234
|
* ```typescript
|
|
846
|
-
*
|
|
847
|
-
*
|
|
848
|
-
*
|
|
849
|
-
*
|
|
850
|
-
*
|
|
851
|
-
* })
|
|
852
|
-
* .use(selector({
|
|
853
|
-
* // Computed: filtered items
|
|
854
|
-
* filteredItems: (state) => {
|
|
855
|
-
* if (state.filter === 'all') return state.items;
|
|
856
|
-
* return state.items.filter((item: any) => item.status === state.filter);
|
|
857
|
-
* },
|
|
858
|
-
* // Computed: item count
|
|
859
|
-
* itemCount: (state) => state.items.length,
|
|
860
|
-
* }));
|
|
2235
|
+
* const emailValidator = createFieldValidator(
|
|
2236
|
+
* 'email',
|
|
2237
|
+
* (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email),
|
|
2238
|
+
* 'Invalid email format'
|
|
2239
|
+
* );
|
|
861
2240
|
*
|
|
862
|
-
*
|
|
863
|
-
*
|
|
864
|
-
* console.log(state.filteredItems); // Computed value
|
|
2241
|
+
* const store = createStore({ email: '' })
|
|
2242
|
+
* .use(validate({ schema: emailValidator }));
|
|
865
2243
|
* ```
|
|
866
2244
|
*/
|
|
867
|
-
|
|
2245
|
+
declare function createFieldValidator<T, K extends keyof T>(field: K, predicate: (value: T[K], state: T) => boolean, message: string): (state: T) => ValidationResult;
|
|
868
2246
|
/**
|
|
869
|
-
* Create
|
|
2247
|
+
* Create an async validator (for server-side validation).
|
|
870
2248
|
*
|
|
871
|
-
* @param
|
|
872
|
-
* @returns A
|
|
2249
|
+
* @param validator - Async validation function
|
|
2250
|
+
* @returns A promise that resolves to validation result
|
|
873
2251
|
*
|
|
874
2252
|
* @example
|
|
875
2253
|
* ```typescript
|
|
876
|
-
*
|
|
877
|
-
*
|
|
878
|
-
*
|
|
879
|
-
*
|
|
880
|
-
*
|
|
881
|
-
* })
|
|
882
|
-
* .use(selector({
|
|
883
|
-
* // Computed total
|
|
884
|
-
* total: (state) =>
|
|
885
|
-
* state.items.reduce((sum: number, item: any) => sum + item.price, 0),
|
|
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
|
+
* });
|
|
886
2260
|
*
|
|
887
|
-
*
|
|
888
|
-
*
|
|
889
|
-
* const total = state.items.reduce((sum: number, item: any) => sum + item.price, 0);
|
|
890
|
-
* return total * (1 + state.taxRate);
|
|
891
|
-
* },
|
|
892
|
-
* }));
|
|
2261
|
+
* // Manual validation
|
|
2262
|
+
* const result = await checkUsername(store.getState());
|
|
893
2263
|
* ```
|
|
894
2264
|
*/
|
|
895
|
-
declare function
|
|
2265
|
+
declare function createAsyncValidator<T>(validator: (state: T) => Promise<ValidationError[]>): (state: T) => Promise<ValidationResult>;
|
|
896
2266
|
|
|
897
2267
|
/**
|
|
898
2268
|
* Deep clone a value, creating copies of nested objects and arrays.
|
|
@@ -983,6 +2353,7 @@ declare function shallowEqual(a: unknown, b: unknown): boolean;
|
|
|
983
2353
|
*/
|
|
984
2354
|
|
|
985
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;
|
|
986
2357
|
|
|
987
2358
|
/**
|
|
988
2359
|
* Type guard to check if a value is a function.
|
|
@@ -1058,4 +2429,430 @@ declare function omit<T extends object, K extends keyof T>(obj: T, keys: readonl
|
|
|
1058
2429
|
*/
|
|
1059
2430
|
declare function identity<T>(value: T): T;
|
|
1060
2431
|
|
|
1061
|
-
|
|
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 };
|