@storve/react 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +996 -11
  2. package/package.json +2 -2
package/README.md CHANGED
@@ -1,22 +1,101 @@
1
- # @storve/react
1
+ # ⚡ Storve
2
2
 
3
- > React bindings for Storve — `useStore` and `useDevtools` hooks.
3
+ > **State that thinks for itself.**
4
4
 
5
+ A fast, minimal-boilerplate React state management library with first-class async support, auto-tracking, and built-in caching. Replaces both Zustand and TanStack Query with a single cohesive API.
6
+
7
+ [![npm (scoped)](https://img.shields.io/npm/v/@storve/core.svg)](https://www.npmjs.com/package/@storve/core)
5
8
  [![npm (scoped)](https://img.shields.io/npm/v/@storve/react.svg)](https://www.npmjs.com/package/@storve/react)
6
9
  [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
10
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue)](https://www.typescriptlang.org/)
7
11
  [![React](https://img.shields.io/badge/React-18%2B-61dafb)](https://react.dev/)
12
+ [![Coverage](https://img.shields.io/badge/coverage-99%25-brightgreen)]()
13
+ [![Core size](https://img.shields.io/badge/core-1.4KB-success)]()
14
+ [![Tests](https://img.shields.io/badge/tests-998%20passing-success)]()
15
+
16
+
17
+ ---
18
+
19
+ ## Why Storve?
20
+
21
+ | Problem with existing tools | How Storve solves it |
22
+ |---|---|
23
+ | Redux requires actions, reducers, selectors in separate files | One `createStore` call, zero boilerplate |
24
+ | Zustand has no built-in async — you need TanStack Query too | `createAsync` is first-class — loading, error, caching built in |
25
+ | Manual selector writing to prevent re-renders | Auto-tracking Proxy — only re-renders what actually changed |
26
+ | No built-in caching or stale-while-revalidate | TTL + SWR built into every async key |
27
+ | Optimistic updates require complex middleware | One option: `{ optimistic: { data } }` |
28
+
29
+ ---
8
30
 
9
31
  ## Installation
10
32
 
33
+ **Storve has two packages — install both for React apps:**
34
+
11
35
  ```bash
36
+ # npm
12
37
  npm install @storve/core @storve/react
13
- # or
38
+
39
+ # pnpm
14
40
  pnpm add @storve/core @storve/react
15
- # or
41
+
42
+ # yarn
16
43
  yarn add @storve/core @storve/react
17
44
  ```
18
45
 
19
- **Peer dependencies:** `@storve/core`, `react` (18+)
46
+ **Peer dependencies:** React 18+
47
+
48
+ ---
49
+
50
+ ## Get started in 5 minutes
51
+
52
+ **1. Install**
53
+ ```bash
54
+ npm install @storve/core @storve/react
55
+ ```
56
+
57
+ **2. Create a store**
58
+ ```ts
59
+ import { createStore } from '@storve/core'
60
+
61
+ const counterStore = createStore({ count: 0 })
62
+ ```
63
+
64
+ **3. Use it in a component**
65
+ ```tsx
66
+ import { useStore } from '@storve/react'
67
+
68
+ function Counter() {
69
+ const count = useStore(counterStore, s => s.count)
70
+ return (
71
+ <button onClick={() => counterStore.setState(s => ({ count: s.count + 1 }))}>
72
+ Count: {count}
73
+ </button>
74
+ )
75
+ }
76
+ ```
77
+
78
+ **4. Add async data**
79
+ ```ts
80
+ import { createAsync } from '@storve/core/async'
81
+
82
+ const userStore = createStore({
83
+ user: createAsync(async (id: string) => {
84
+ const res = await fetch(`/api/users/${id}`)
85
+ return res.json()
86
+ })
87
+ })
88
+
89
+ await userStore.fetch('user', 'user-123')
90
+ userStore.getState().user.data // { id: 'user-123', name: 'Alice' }
91
+ userStore.getState().user.status // 'success'
92
+ ```
93
+
94
+ That's it. No actions, reducers, or providers needed.
95
+
96
+ ➡️ *StackBlitz demo coming soon*
97
+
98
+ ---
20
99
 
21
100
  ## Quick Start
22
101
 
@@ -24,8 +103,10 @@ yarn add @storve/core @storve/react
24
103
  import { createStore } from '@storve/core'
25
104
  import { useStore } from '@storve/react'
26
105
 
106
+ // 1. Create a store
27
107
  const counterStore = createStore({ count: 0 })
28
108
 
109
+ // 2. Use it in a component
29
110
  function Counter() {
30
111
  const count = useStore(counterStore, s => s.count)
31
112
  return (
@@ -36,15 +117,919 @@ function Counter() {
36
117
  }
37
118
  ```
38
119
 
39
- ## API
120
+ ---
121
+
122
+ ## Import Patterns (Tree-Shaking)
123
+
124
+ Storve uses subpath imports so you only bundle what you use:
125
+
126
+ | Import | Size (gzipped) | Use when |
127
+ |--------|----------------|----------|
128
+ | `import { createStore, batch } from '@storve/core'` | ~1.4 KB | Core store only |
129
+ | `import { createAsync } from '@storve/core/async'` | +1.1 KB | Async state, fetching, caching |
130
+ | `import { computed } from '@storve/core/computed'` | +0.8 KB | Derived state |
131
+ | `import { withPersist } from '@storve/core/persist'` | +1.2 KB | Persistence, adapters |
132
+ | `import { signal } from '@storve/core/signals'` | +0.4 KB | Fine-grained reactivity |
133
+ | `import { withDevtools } from '@storve/core/devtools'` | +0.8 KB | Time-travel, Undo/Redo |
134
+ | `import { withSync } from '@storve/core/sync'` | +0.6 KB | Cross-tab synchronization |
135
+
136
+ ```ts
137
+ // Core only
138
+ import { createStore } from '@storve/core'
139
+
140
+ // With async
141
+ import { createStore } from '@storve/core'
142
+ import { createAsync } from '@storve/core/async'
143
+
144
+ // With computed
145
+ import { createStore } from '@storve/core'
146
+ import { computed } from '@storve/core/computed'
147
+ ```
148
+
149
+ ---
150
+
151
+ ## Core Concepts
152
+
153
+ Storve has two packages:
154
+
155
+ - **`@storve/core`** — the framework-agnostic core store. Works anywhere: React, Node, tests, vanilla JS.
156
+ - **`@storve/react`** — the React adapter. Provides `useStore` hook built on `useSyncExternalStore`.
157
+
158
+ ---
159
+
160
+ ## API Reference
161
+
162
+ ### `createStore(definition, options?)`
163
+
164
+ Creates a reactive store. Returns a store instance.
165
+
166
+ ```ts
167
+ import { createStore } from '@storve/core'
168
+
169
+ const store = createStore({
170
+ count: 0,
171
+ name: 'Alice',
172
+ theme: 'light' as 'light' | 'dark',
173
+ })
174
+ ```
175
+
176
+ #### Options
177
+
178
+ ```ts
179
+ createStore(definition, {
180
+ immer: true, // enable Immer mutation-style updates (default: false)
181
+ })
182
+ ```
183
+
184
+ ---
185
+
186
+ ### `store.getState()`
187
+
188
+ Returns a shallow copy of the current state. Each call is an independent snapshot — mutations to the returned object do not affect the store.
189
+
190
+ ```ts
191
+ const state = store.getState()
192
+ state.count // 0
193
+ state.name // 'Alice'
194
+
195
+ // Safe — `before` is a snapshot, not a live reference
196
+ const before = store.getState()
197
+ store.setState({ count: 99 })
198
+ before.count // still 0
199
+ store.getState().count // 99
200
+ ```
201
+
202
+ ---
203
+
204
+ ### `store.setState(updater)`
205
+
206
+ Updates state and notifies all subscribers. Accepts a partial object, an updater function, or an Immer draft mutator (when `immer: true`).
207
+
208
+ ```ts
209
+ // 1. Partial object — merged into existing state
210
+ store.setState({ count: 1 })
211
+
212
+ // 2. Updater function — receives current state, returns partial
213
+ store.setState(s => ({ count: s.count + 1 }))
214
+
215
+ // 3. Immer draft mutator (requires immer: true option)
216
+ store.setState(draft => {
217
+ draft.count++
218
+ draft.name = 'Bob'
219
+ })
220
+ ```
221
+
222
+ **Immer example with nested state:**
223
+
224
+ ```ts
225
+ const store = createStore({
226
+ user: { address: { city: 'New York' } }
227
+ }, { immer: true })
228
+
229
+ // Without Immer — verbose
230
+ store.setState(s => ({
231
+ user: { ...s.user, address: { ...s.user.address, city: 'LA' } }
232
+ }))
233
+
234
+ // With Immer — clean
235
+ store.setState(draft => { draft.user.address.city = 'LA' })
236
+ ```
237
+
238
+ ---
239
+
240
+ ### `store.subscribe(listener)`
241
+
242
+ Subscribes to state changes. Returns an unsubscribe function.
243
+
244
+ ```ts
245
+ const unsubscribe = store.subscribe(newState => {
246
+ console.log('state changed:', newState)
247
+ })
248
+
249
+ // Stop listening
250
+ unsubscribe()
251
+ ```
252
+
253
+ Useful outside React — in Node scripts, tests, or to sync with external systems like `localStorage`.
254
+
255
+ ---
256
+
257
+ ### `store.batch(fn)`
258
+
259
+ Runs multiple `setState` calls and fires subscribers **exactly once** at the end, regardless of how many updates happen inside.
260
+
261
+ ```ts
262
+ store.batch(() => {
263
+ store.setState({ count: 1 })
264
+ store.setState({ name: 'Bob' })
265
+ store.setState({ theme: 'dark' })
266
+ })
267
+ // Subscribers notified once — not three times
268
+ ```
269
+
270
+ Use `batch` whenever you need to make several state changes atomically. Prevents intermediate renders.
271
+
272
+ ---
273
+
274
+ ### `actions` — Named operations
275
+
276
+ Define named operations directly inside the store definition. Actions are automatically bound and available directly on the store instance.
277
+
278
+ ```ts
279
+ const counterStore = createStore({
280
+ count: 0,
281
+ actions: {
282
+ increment() { counterStore.setState(s => ({ count: s.count + 1 })) },
283
+ decrement() { counterStore.setState(s => ({ count: s.count - 1 })) },
284
+ reset() { counterStore.setState({ count: 0 }) },
285
+ incrementBy(amount: number) {
286
+ counterStore.setState(s => ({ count: s.count + amount }))
287
+ }
288
+ }
289
+ })
290
+
291
+ // Call actions directly on the store
292
+ counterStore.increment()
293
+ counterStore.incrementBy(5)
294
+ counterStore.reset()
295
+
296
+ // Actions are also grouped under .actions
297
+ counterStore.actions.increment()
298
+ ```
299
+
300
+ Actions keep business logic in one place instead of scattered across components.
301
+
302
+ ---
303
+
304
+ ### `useStore(store, selector?)` *(@storve/react)*
305
+
306
+ React hook to consume a store inside a component. Built on `useSyncExternalStore` — safe in React 18 Concurrent Mode with no tearing.
307
+
308
+ ```tsx
309
+ import { useStore } from '@storve/react'
310
+
311
+ function MyComponent() {
312
+ // Subscribe to the entire store
313
+ const state = useStore(counterStore)
314
+
315
+ // Subscribe to a single value — only re-renders when count changes
316
+ const count = useStore(counterStore, s => s.count)
317
+
318
+ // Subscribe to a derived value — only re-renders when result changes
319
+ const isEven = useStore(counterStore, s => s.count % 2 === 0)
320
+
321
+ return <div>{count} — {isEven ? 'even' : 'odd'}</div>
322
+ }
323
+ ```
324
+
325
+ **The selector is optional.** If your store is small and focused, subscribing to everything is fine. Use a selector when you want to prevent re-renders from unrelated state changes.
326
+
327
+ ---
328
+
329
+ ## Computed values (v0.5)
330
+
331
+ Synchronous derived state with automatic dependency tracking. Use `computed(fn)` in your store definition; the store will run the function against the current state, track which keys were read, and recompute when those dependencies change. Supports chaining (computed can depend on other computeds). Circular dependencies are detected at store creation and throw a clear error.
332
+
333
+ ```ts
334
+ import { createStore } from '@storve/core'
335
+ import { computed } from '@storve/core/computed'
336
+
337
+ const store = createStore({
338
+ a: 1,
339
+ b: 2,
340
+ sum: computed((s) => s.a + s.b),
341
+ })
342
+
343
+ store.getState().sum // 3
344
+ store.setState({ a: 10 })
345
+ store.getState().sum // 12
346
+ ```
347
+
348
+ Computed keys are read-only: you cannot set them via `setState` (TypeScript will flag it; at runtime such keys are ignored).
349
+
350
+ ---
351
+
352
+ ## Async State
353
+
354
+ Async data is a first-class citizen in Storve. No separate library needed.
355
+
356
+ ### `createAsync(fn, options?)`
357
+
358
+ Defines an async value inside a store. Automatically manages `loading`, `error`, `data`, and `status`.
359
+
360
+ ```ts
361
+ import { createStore } from '@storve/core'
362
+ import { createAsync } from '@storve/core/async'
363
+
364
+ const userStore = createStore({
365
+ user: createAsync(async (id: string) => {
366
+ const res = await fetch(`/api/users/${id}`)
367
+ return res.json()
368
+ })
369
+ })
370
+ ```
371
+
372
+ Every async key automatically has this shape:
373
+
374
+ ```ts
375
+ store.getState().user === {
376
+ data: null, // T | null — the result
377
+ loading: false, // boolean — is a fetch in progress?
378
+ error: null, // string | null — error message if failed
379
+ status: 'idle', // 'idle' | 'loading' | 'success' | 'error'
380
+ refetch: () => void // convenience method to re-run the fetch
381
+ }
382
+ ```
383
+
384
+ #### Async Options
385
+
386
+ ```ts
387
+ createAsync(fn, {
388
+ ttl: 60_000, // cache result for 60 seconds (default: 0 = no cache)
389
+ staleWhileRevalidate: true // show stale data while fetching fresh (default: false)
390
+ })
391
+ ```
392
+
393
+ ---
394
+
395
+ ### `store.fetch(key, ...args)`
396
+
397
+ Triggers the async function. Sets `loading: true` synchronously before the first await — safe to check immediately after calling.
398
+
399
+ ```ts
400
+ // Basic fetch
401
+ await store.fetch('user', 'user-123')
402
+
403
+ // Check loading synchronously
404
+ const fetchPromise = store.fetch('user', 'user-123')
405
+ store.getState().user.loading // true — set synchronously
406
+
407
+ await fetchPromise
408
+ store.getState().user.loading // false
409
+ store.getState().user.data // { id: 'user-123', name: 'Alice' }
410
+ store.getState().user.status // 'success'
411
+ ```
412
+
413
+ **Race condition protection built in** — if you call `fetch` multiple times rapidly, only the last response wins. Previous responses are silently discarded.
414
+
415
+ ```ts
416
+ store.fetch('user', 'user-1') // starts
417
+ store.fetch('user', 'user-2') // starts — user-1 response will be ignored
418
+ store.fetch('user', 'user-3') // starts — user-1 and user-2 will be ignored
419
+ // Only user-3's response updates state
420
+ ```
421
+
422
+ ---
423
+
424
+ ### `store.refetch(key)`
425
+
426
+ Re-runs the async function with the last used arguments. Bypasses TTL cache.
427
+
428
+ ```ts
429
+ await store.fetch('user', 'user-123') // fetches user-123
430
+ await store.refetch('user') // re-fetches user-123 automatically
431
+ ```
432
+
433
+ You can also call `refetch` from the state shape itself:
434
+
435
+ ```ts
436
+ await store.getState().user.refetch() // same as store.refetch('user')
437
+ ```
438
+
439
+ ---
440
+
441
+ ### TTL Caching
442
+
443
+ Cache results for a duration. Within the TTL window, `fetch` returns cached data without hitting the network.
444
+
445
+ ```ts
446
+ const store = createStore({
447
+ user: createAsync(fetchUser, { ttl: 60_000 }) // cache for 60 seconds
448
+ })
449
+
450
+ await store.fetch('user', 'user-123') // hits network
451
+ await store.fetch('user', 'user-123') // returns cache — no network call
452
+ // 60 seconds later...
453
+ await store.fetch('user', 'user-123') // hits network again
454
+ ```
455
+
456
+ Different arguments produce independent cache entries:
457
+
458
+ ```ts
459
+ await store.fetch('user', 'user-1') // cached under 'user-1'
460
+ await store.fetch('user', 'user-2') // cached under 'user-2' independently
461
+ await store.fetch('user', 'user-1') // cache hit — no network
462
+ ```
463
+
464
+ ---
465
+
466
+ ### Stale-While-Revalidate (SWR)
467
+
468
+ When the cache expires, instead of showing a loading spinner, Storve immediately returns the stale data and fetches fresh data in the background.
469
+
470
+ ```ts
471
+ const store = createStore({
472
+ user: createAsync(fetchUser, {
473
+ ttl: 60_000,
474
+ staleWhileRevalidate: true
475
+ })
476
+ })
477
+
478
+ await store.fetch('user', 'user-123') // initial fetch
479
+ // 60 seconds later...
480
+
481
+ store.fetch('user', 'user-123')
482
+ // status is still 'success' — not 'loading'
483
+ // data is the old (stale) value — shown immediately
484
+ // fresh data fetches in background, updates quietly when done
485
+ ```
486
+
487
+ Without SWR, an expired cache shows `status: 'loading'` and a blank/spinner state. With SWR, users always see something — the app feels instant.
488
+
489
+ ---
490
+
491
+ ### `store.invalidate(key)`
492
+
493
+ Clears the TTL cache for a specific key. The next `fetch` will go to the network regardless of TTL.
494
+
495
+ ```ts
496
+ store.invalidate('user')
497
+ await store.fetch('user', 'user-123') // hits network even if TTL hasn't expired
498
+ ```
499
+
500
+ ---
501
+
502
+ ### `store.invalidateAll()`
503
+
504
+ Clears cache for every async key in the store.
505
+
506
+ ```ts
507
+ store.invalidateAll()
508
+ ```
509
+
510
+ ---
511
+
512
+ ### Optimistic Updates
513
+
514
+ Apply an immediate state change before the async operation completes. If the operation fails, state automatically rolls back.
515
+
516
+ ```ts
517
+ // Show the new name immediately — roll back if save fails
518
+ await store.fetch('user', { optimistic: { data: { name: 'New Name' }, status: 'success' } })
519
+ ```
520
+
521
+ The UI updates instantly. If the server rejects the change, the previous data is restored automatically.
522
+
523
+ ---
524
+
525
+ ### Error Handling
526
+
527
+ Errors are captured in state — `fetch` never throws to the caller.
528
+
529
+ ```ts
530
+ // fetch does not throw
531
+ await store.fetch('user', 'user-123')
532
+
533
+ // Check error in state
534
+ const { data, error, status } = store.getState().user
535
+ if (status === 'error') {
536
+ console.log(error) // 'Network error' — the error message
537
+ }
538
+ ```
539
+
540
+ ---
541
+
542
+ ### Full Async Example
543
+
544
+ ```tsx
545
+ import { createStore } from '@storve/core'
546
+ import { createAsync } from '@storve/core/async'
547
+ import { useStore } from '@storve/react'
548
+
549
+ const userStore = createStore({
550
+ user: createAsync(
551
+ async (id: string) => {
552
+ const res = await fetch(`/api/users/${id}`)
553
+ if (!res.ok) throw new Error('Failed to fetch user')
554
+ return res.json()
555
+ },
556
+ { ttl: 60_000, staleWhileRevalidate: true }
557
+ )
558
+ })
559
+
560
+ function UserProfile({ id }: { id: string }) {
561
+ const { data, loading, error, status } = useStore(userStore, s => s.user)
562
+
563
+ useEffect(() => {
564
+ userStore.fetch('user', id)
565
+ }, [id])
566
+
567
+ if (status === 'idle' || loading) return <Spinner />
568
+ if (status === 'error') return <ErrorMessage message={error} />
569
+
570
+ return (
571
+ <div>
572
+ <h1>{data.name}</h1>
573
+ <button onClick={() => userStore.refetch('user')}>Refresh</button>
574
+ </div>
575
+ )
576
+ }
577
+ ```
578
+ ---
579
+
580
+ ## Persistence Layer (v0.4)
581
+
582
+ Storve includes a powerful, tree-shakable persistence layer that automatically syncs your store state to external storage.
583
+
584
+ ### `withPersist(store, options)`
585
+
586
+ Enhances a store with persistence capabilities. It handles hydration (loading state on startup) and automatic debounced writes on state changes.
587
+
588
+ ```ts
589
+ import { createStore } from '@storve/core'
590
+ import { withPersist } from '@storve/core/persist'
591
+ import { localStorageAdapter } from '@storve/core/persist/adapters/localStorage'
592
+
593
+ const store = withPersist(
594
+ createStore({ count: 0 }),
595
+ {
596
+ key: 'my-app-store',
597
+ adapter: localStorageAdapter(),
598
+ pick: ['count'], // optional: only persist these keys
599
+ version: 1, // optional: for schema migrations
600
+ debounce: 100, // optional: ms to wait before saving (default: 100)
601
+ }
602
+ )
603
+
604
+ // Wait for hydration if you need to know when data is loaded
605
+ await store.hydrated
606
+ ```
607
+
608
+ ### Adapters
609
+
610
+ Storve comes with several built-in adapters, all SSR-safe:
611
+
612
+ - **`localStorageAdapter()`**: Persist to `window.localStorage`.
613
+ - **`sessionStorageAdapter()`**: Persist to `window.sessionStorage`.
614
+ - **`indexedDBAdapter()`**: Async persistence to IndexedDB for larger datasets.
615
+ - **`memoryAdapter()`**: In-memory storage, useful for testing or SSR environments.
616
+
617
+ ### Composing Enhancers
618
+
619
+ Use `withPersist` as a higher-order function for clean composition:
620
+
621
+ ```ts
622
+ import { createStore } from '@storve/core'
623
+ import { withPersist } from '@storve/core/persist'
624
+ import { localStorageAdapter } from '@storve/core/persist/adapters/localStorage'
625
+
626
+ const store = withPersist({
627
+ key: 'app',
628
+ adapter: localStorageAdapter()
629
+ })(createStore({ count: 0 }))
630
+ ```
631
+
632
+ ---
633
+
634
+ ## Signals (v0.5)
635
+
636
+ Signals provide fine-grained reactivity by allowing you to subscribe to a single key in the store. Unlike `useStore` which re-renders if a selector result changes, Signals are lower-level objects that can be passed around and subscribed to directly.
637
+
638
+ ### `signal(store, key, transform?)`
639
+
640
+ Creates a Signal for a specific store key. Optionally transforms the value.
641
+
642
+ ```ts
643
+ import { createStore } from '@storve/core'
644
+ import { signal } from '@storve/core/signals'
645
+
646
+ const store = createStore({ count: 0, user: { name: 'Alice' } })
647
+
648
+ // 1. Standard Signal
649
+ const countSignal = signal(store, 'count')
650
+
651
+ // 2. Derived Signal (Read-only)
652
+ const doubleSignal = signal(store, 'count', v => v * 2)
653
+ ```
654
+
655
+ ### Signal API
656
+
657
+ - `signal.get()`: Returns current value.
658
+ - `signal.set(value | fn)`: Updates the store (throws if derived).
659
+ - `signal.subscribe(listener)`: Notifies when *this* signal's value changes. Returns unsubscribe.
660
+ - `signal._derived`: Boolean flag.
661
+
662
+ ### React Integration: `useSignal(signal)`
663
+
664
+ The `useSignal` hook (from `@storve/react`) subscribes to a signal and returns its value. The component re-renders **ONLY** when that specific signal changes.
665
+
666
+ ```tsx
667
+ import { signal } from '@storve/core/signals'
668
+ import { useSignal } from '@storve/react'
669
+
670
+ const countSignal = signal(counterStore, 'count')
671
+
672
+ function CounterDisplay() {
673
+ const count = useSignal(countSignal)
674
+ return <div>Count: {count}</div>
675
+ }
676
+ ```
677
+
678
+ Signals are perfect for high-frequency updates or deep component trees where you want to avoid overhead from larger selectors.
679
+
680
+
681
+ ---
682
+
683
+ ## DevTools & Time Travel (v0.6)
684
+
685
+ Storve features a built-in time-travel engine that integrates seamlessly with the Redux DevTools extension. It uses a ring-buffer history to keep memory usage constant while providing powerful undo/redo and snapshot capabilities.
686
+
687
+ ### `withDevtools(store, options)`
688
+
689
+ Enhances a store with history tracking and Redux DevTools integration.
690
+
691
+ ```ts
692
+ import { createStore } from '@storve/core'
693
+ import { withDevtools } from '@storve/core/devtools'
694
+
695
+ const store = withDevtools(
696
+ createStore({ count: 0 }),
697
+ {
698
+ name: 'My Store', // Label in DevTools panel
699
+ maxHistory: 50 // Max entries in ring buffer (default: 50)
700
+ }
701
+ )
702
+ ```
703
+
704
+ ### History API
705
+
706
+ Once enhanced, the store instance provides methods to navigate history:
707
+
708
+ - `store.undo()`: Move back one step in history.
709
+ - `store.redo()`: Move forward one step in history.
710
+ - `store.canUndo`: Boolean flag indicating if undo is possible.
711
+ - `store.canRedo`: Boolean flag indicating if redo is possible.
712
+ - `store.clearHistory()`: Wipes the history buffer.
713
+
714
+ ### Named Snapshots
715
+
716
+ Save and restore specific state checkpoints by name.
717
+
718
+ ```ts
719
+ store.snapshot('before-expensive-op')
720
+ // ... make changes ...
721
+ store.restore('before-expensive-op') // Jumps back instantly
722
+ ```
723
+
724
+ ### React Integration: `useDevtools(store)`
725
+
726
+ The `useDevtools` hook (from `@storve/react`) provides a reactive way to access history state, useful for building your own Undo/Redo UI.
727
+
728
+ ```tsx
729
+ import { useDevtools } from '@storve/react'
730
+
731
+ function Controls() {
732
+ const { canUndo, canRedo, undo, redo } = useDevtools(counterStore)
733
+
734
+ return (
735
+ <div>
736
+ <button onClick={undo} disabled={!canUndo}>Undo</button>
737
+ <button onClick={redo} disabled={!canRedo}>Redo</button>
738
+ </div>
739
+ )
740
+ }
741
+ ```
742
+
743
+ ---
744
+
745
+ ## Cross-Tab Synchronization (v0.7)
746
+
747
+ Storve provides an easy way to synchronize state across multiple browser tabs using the `BroadcastChannel` API. This is useful for keeping user preferences, authentication state, or shared data consistent without manual event handling.
748
+
749
+ ### `withSync(store, options)`
750
+
751
+ Enhances a store with cross-tab synchronization.
752
+
753
+ ```ts
754
+ import { createStore } from '@storve/core'
755
+ import { withSync } from '@storve/core/sync'
756
+
757
+ const store = withSync(
758
+ createStore({ theme: 'light', user: { name: 'Alice' } }),
759
+ {
760
+ channel: 'my-app-sync', // Unique channel name
761
+ keys: ['theme'] // Optional: only sync specific keys
762
+ }
763
+ )
764
+ ```
765
+
766
+ ### Features
767
+
768
+ - **Automatic Rehydration**: New tabs automatically request the current state from existing tabs on startup.
769
+ - **Selective Sync**: Use the `keys` option to only broadcast specific parts of your state, reducing overhead.
770
+ - **Conflict-Free**: Built on a simple last-write-wins protocol via `BroadcastChannel`.
771
+ - **Zero Configuration**: Works out of the box with no complex setup required.
772
+
773
+ ---
774
+
775
+ Stores are plain JavaScript objects. Import and use them freely across stores.
776
+
777
+ ### Read from another store in an action
778
+
779
+ ```ts
780
+ import { userStore } from './userStore'
781
+
782
+ const cartStore = createStore({
783
+ items: [] as CartItem[],
784
+ actions: {
785
+ addItem(item: CartItem) {
786
+ const user = userStore.getState().user.data
787
+ if (!user) throw new Error('Must be logged in')
788
+ cartStore.setState(s => ({ items: [...s.items, item] }))
789
+ }
790
+ }
791
+ })
792
+ ```
793
+
794
+ ### React to another store's changes
795
+
796
+ ```ts
797
+ // Auto-clear cart when user logs out
798
+ userStore.subscribe(state => {
799
+ if (!state.user.data) {
800
+ cartStore.setState({ items: [] })
801
+ }
802
+ })
803
+ ```
804
+
805
+ ### Use multiple stores in one component
806
+
807
+ ```tsx
808
+ function Header() {
809
+ const user = useStore(userStore, s => s.user.data)
810
+ const cartCount = useStore(cartStore, s => s.items.length)
811
+ const theme = useStore(themeStore, s => s.theme)
812
+
813
+ return (
814
+ <header data-theme={theme}>
815
+ <span>Hello, {user?.name}</span>
816
+ <span>Cart ({cartCount})</span>
817
+ </header>
818
+ )
819
+ }
820
+ ```
821
+
822
+ ---
823
+
824
+ ## Performance
825
+
826
+ All benchmarks run on Apple MacBook Air, 100,000 iterations with 1,000 warmup iterations.
827
+
828
+ ### Core Store
829
+
830
+ | Operation | Average Time | Threshold |
831
+ |---|---|---|
832
+ | `createStore()` | 0.00640ms | < 1ms |
833
+ | `getState()` read | 0.00001ms | < 0.1ms |
834
+ | `setState()` + notify (100 subs) | 0.00090ms | < 1ms |
835
+ | Nested read (3 levels deep) | 0.00001ms | < 0.1ms |
836
+ | Subscribe + Unsubscribe cycle | 0.00008ms | < 0.1ms |
837
+
838
+ ### React Adapter
839
+
840
+ | Operation | Average Time | Threshold |
841
+ |---|---|---|
842
+ | `useStore()` subscription setup | 0.00006ms | < 0.5ms |
843
+ | `useStore()` subscription cleanup | 0.00007ms | < 0.5ms |
844
+ | Selector execution (primitive) | 0.00001ms | < 0.1ms |
845
+ | Selector execution (derived) | 0.00000ms | < 0.1ms |
846
+ | `setState()` + notify (10 subs) | 0.00037ms | < 1ms |
847
+
848
+ ### Immer & Batch
849
+
850
+ | Operation | Average Time |
851
+ |---|---|
852
+ | `setState()` Immer primitive | 0.00080ms |
853
+ | `setState()` Immer nested object | 0.00252ms |
854
+ | `setState()` Immer array push | 0.00831ms |
855
+ | `batch()` 3× setState, 1 notify | 0.00120ms |
856
+ | `batch()` 10× setState, 1 notify | 0.00536ms |
857
+
858
+ ### Async & Computed (Week 5)
859
+
860
+ | Operation | Average Time | Threshold |
861
+ |---|---|---|
862
+ | `createAsync()` initialization | 0.00025ms | < 0.1ms |
863
+ | `fetch()` - cache hit (TTL) | 0.00065ms | < 0.1ms |
864
+ | `fetch()` - cache miss (resolved) | 0.00657ms | < 1.0ms |
865
+ | `refetch()` overhead | 0.00655ms | < 0.1ms |
866
+ | `optimistic` - immediate change | 0.00452ms | < 0.2ms |
867
+ | `computed` read | 0.00001ms | < 0.1ms |
868
+ | `computed` recompute (1 dep) | 0.00212ms | < 0.1ms |
869
+ | `computed` 3-level chain | 0.00337ms | < 0.5ms |
870
+
871
+ ---
872
+
873
+ ## TypeScript
874
+
875
+ Storve is written in TypeScript with full inference. No type casting required.
876
+
877
+ ```ts
878
+ // State type is fully inferred
879
+ const store = createStore({
880
+ count: 0,
881
+ name: 'Alice',
882
+ active: true,
883
+ })
884
+
885
+ store.getState().count // inferred as number
886
+ store.getState().name // inferred as string
887
+ store.getState().active // inferred as boolean
888
+
889
+ // setState is type-safe — wrong keys or types are caught at compile time
890
+ store.setState({ count: 'wrong' }) // TS error
891
+ store.setState({ unknown: true }) // TS error
892
+
893
+ // Async state is fully typed
894
+ const userStore = createStore({
895
+ user: createAsync(async () => ({ name: 'Alice', age: 30 }))
896
+ })
897
+
898
+ userStore.getState().user.data?.name // inferred as string | undefined
899
+ userStore.getState().user.status // inferred as 'idle' | 'loading' | 'success' | 'error'
900
+ ```
901
+
902
+ ---
903
+
904
+ ## Test Coverage
905
+
906
+ | File | Statements | Branches | Functions | Lines |
907
+ |---|---|---|---|---|
908
+ | `async.ts` | 98.44% | 95.83% | 100% | 98.44% |
909
+ | `proxy.ts` | 100% | 100% | 100% | 100% |
910
+ | `store.ts` | 98.3% | 95%+ | 100% | 98.3% |
911
+ | `signals/` | 100% | 100% | 100% | 100% |
912
+ | `persist/` | 99.6% | 92%+ | 100% | 99.6% |
913
+ | `sync/` | 100% | 100% | 100% | 100% |
914
+ | **Total** | **99.1%** | **96%+** | **98%+** | **99.1%** |
915
+
916
+ 998 tests across 36 test files. Zero known bugs.
917
+
918
+ ---
919
+
920
+ ## Migrating from pre-1.0 (storve / storve-react)
921
+
922
+ If you used the old unscoped packages before v1.0, update your imports:
923
+
924
+ | Old | New |
925
+ |-----|-----|
926
+ | `storve` | `@storve/core` |
927
+ | `storve-react` | `@storve/react` |
928
+ | `storve/async` | `@storve/core/async` |
929
+ | `storve/computed` | `@storve/core/computed` |
930
+ | `storve/persist` | `@storve/core/persist` |
931
+ | `storve/signals` | `@storve/core/signals` |
932
+ | `storve/devtools` | `@storve/core/devtools` |
933
+ | `storve/sync` | `@storve/core/sync` |
934
+
935
+ ```bash
936
+ pnpm remove storve storve-react
937
+ pnpm add @storve/core @storve/react
938
+ ```
939
+
940
+ ---
941
+
942
+ ## Migrating from Redux
943
+
944
+ **Before (Redux)**
945
+ ```ts
946
+ // actions.ts
947
+ const INCREMENT = 'INCREMENT'
948
+ const increment = () => ({ type: INCREMENT })
949
+
950
+ // reducer.ts
951
+ function counterReducer(state = { count: 0 }, action) {
952
+ switch (action.type) {
953
+ case INCREMENT: return { ...state, count: state.count + 1 }
954
+ default: return state
955
+ }
956
+ }
957
+
958
+ // store.ts
959
+ const store = createStore(counterReducer)
960
+
961
+ // component.tsx
962
+ const count = useSelector(s => s.count)
963
+ const dispatch = useDispatch()
964
+ dispatch(increment())
965
+ ```
966
+
967
+ **After (Storve)**
968
+ ```ts
969
+ // store.ts
970
+ const counterStore = createStore({
971
+ count: 0,
972
+ actions: {
973
+ increment() { counterStore.setState(s => ({ count: s.count + 1 })) }
974
+ }
975
+ })
976
+
977
+ // component.tsx
978
+ const count = useStore(counterStore, s => s.count)
979
+ counterStore.increment()
980
+ ```
981
+
982
+ ## Migrating from Zustand
983
+
984
+ **Before (Zustand)**
985
+ ```ts
986
+ const useStore = create((set) => ({
987
+ count: 0,
988
+ increment: () => set(s => ({ count: s.count + 1 })),
989
+ }))
990
+
991
+ // component
992
+ const count = useStore(s => s.count)
993
+ const increment = useStore(s => s.increment)
994
+ ```
995
+
996
+ **After (Storve)**
997
+ ```ts
998
+ const counterStore = createStore({
999
+ count: 0,
1000
+ actions: {
1001
+ increment() { counterStore.setState(s => ({ count: s.count + 1 })) }
1002
+ }
1003
+ })
1004
+
1005
+ // component
1006
+ const count = useStore(counterStore, s => s.count)
1007
+ counterStore.increment()
1008
+ ```
1009
+
1010
+ **Key differences:**
1011
+ - No provider needed — stores are module-level singletons
1012
+ - Actions defined inside the store, not as part of state
1013
+ - Built-in async support — no need for a separate server state library
1014
+
1015
+ ---
40
1016
 
41
- - **`useStore(store, selector?)`** — Subscribe to a store. Uses `useSyncExternalStore` for React 18 compatibility.
42
- - **`useDevtools(store)`** — Access `canUndo`, `canRedo`, `undo`, `redo` for stores enhanced with `withDevtools`.
1017
+ ## Roadmap
43
1018
 
44
- ## Documentation
1019
+ | Version | Theme | Status |
1020
+ |---|---|---|
1021
+ | v0.1–v0.3 | Core store, React adapter, Immer, Actions | ✅ Shipped |
1022
+ | v0.4 | Async state — createAsync, TTL, SWR, optimistic | ✅ Shipped |
1023
+ | v0.5 | Computed values + Signals | ✅ Shipped |
1024
+ | v0.6 | DevTools — Time-travel, Undo/Redo, Snapshots | ✅ Shipped |
1025
+ | v0.7 | Cross-tab sync via BroadcastChannel | ✅ Shipped |
1026
+ | v1.0 | Stable API, polished README, StackBlitz demo | ✅ Shipped |
1027
+ | v1.1 | Purpose-built DevTools browser extension | 📋 Planned |
1028
+ | v1.2 | Full docs site (Docusaurus) | 📋 Planned |
1029
+ | v1.3 | Middleware system | 📋 Planned |
45
1030
 
46
- Full docs and examples: [GitHub - Nam1001/React-Flux](https://github.com/Nam1001/React-Flux)
1031
+ ---
47
1032
 
48
1033
  ## License
49
1034
 
50
- MIT
1035
+ MIT © 2026 Storve
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "type": "git",
5
5
  "url": "https://github.com/Nam1001/React-Flux.git"
6
6
  },
7
- "version": "1.0.1",
7
+ "version": "1.0.2",
8
8
  "main": "dist/index.cjs",
9
9
  "module": "dist/index.mjs",
10
10
  "types": "dist/index.d.ts",
@@ -24,7 +24,7 @@
24
24
  "lint": "eslint src --ext .ts,.tsx"
25
25
  },
26
26
  "dependencies": {
27
- "@storve/core": "1.0.1"
27
+ "@storve/core": "1.0.2"
28
28
  },
29
29
  "peerDependencies": {
30
30
  "react": ">=18.0.0"