memorio 4.6.6 → 4.6.8

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.
@@ -1,362 +0,0 @@
1
- /**
2
- * Memorio React App Example
3
- *
4
- * This example shows how to use Memorio state in a React application.
5
- *
6
- * Run: npx ts-node --esm examples/react-app.tsx
7
- * Or copy to your React project
8
- */
9
-
10
- import React, { useState, useEffect } from 'react'
11
- import 'memorio'
12
-
13
- // ============================================
14
- // 1. SETUP - Import once at app start
15
- // ============================================
16
-
17
- // In your main App.tsx or index.js:
18
- // import 'memorio'
19
-
20
- // ============================================
21
- // 2. DEFINE YOUR STATE SHAPE
22
- // ============================================
23
-
24
- interface AppState {
25
- user: {
26
- name: string
27
- email: string
28
- avatar?: string
29
- } | null
30
- theme: 'light' | 'dark'
31
- notifications: Notification[]
32
- cart: CartItem[]
33
- isLoading: boolean
34
- }
35
-
36
- interface Notification {
37
- id: string
38
- message: string
39
- read: boolean
40
- }
41
-
42
- interface CartItem {
43
- id: number
44
- name: string
45
- price: number
46
- quantity: number
47
- }
48
-
49
- // ============================================
50
- // 3. USE STATE IN COMPONENTS
51
- // ============================================
52
-
53
- // ------------------------------
54
- // Header Component
55
- // ------------------------------
56
- function Header() {
57
- // Using useObserver to react to state changes
58
- const [theme, setTheme] = useState(state.theme)
59
-
60
- useObserver(() => {
61
- setTheme(state.theme)
62
- }, [state.theme])
63
-
64
- return (
65
- <header className={`header header--${theme}`}>
66
- <h1>My App</h1>
67
- <button onClick={() => {
68
- state.theme = state.theme === 'light' ? 'dark' : 'light'
69
- }}>
70
- Toggle Theme
71
- </button>
72
- </header>
73
- )
74
- }
75
-
76
- // ------------------------------
77
- // User Profile Component
78
- // ------------------------------
79
- function UserProfile() {
80
- const [user, setUser] = useState(state.user)
81
-
82
- // Auto-discover all state changes
83
- useObserver(() => {
84
- setUser(state.user)
85
- })
86
-
87
- if (!user) {
88
- return <div>Please log in</div>
89
- }
90
-
91
- return (
92
- <div className="profile">
93
- <img src={user.avatar} alt={user.name} />
94
- <h2>{user.name}</h2>
95
- <p>{user.email}</p>
96
- </div>
97
- )
98
- }
99
-
100
- // ------------------------------
101
- // Login Form Component
102
- // ------------------------------
103
- function LoginForm() {
104
- const [name, setName] = useState('')
105
- const [email, setEmail] = useState('')
106
-
107
- const handleSubmit = (e: React.FormEvent) => {
108
- e.preventDefault()
109
-
110
- // Set user state
111
- state.user = {
112
- name,
113
- email,
114
- avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${name}`
115
- }
116
-
117
- // Also persist to store
118
- store.set('lastUser', name)
119
- }
120
-
121
- return (
122
- <form onSubmit={handleSubmit}>
123
- <input
124
- value={name}
125
- onChange={e => setName(e.target.value)}
126
- placeholder="Name"
127
- />
128
- <input
129
- value={email}
130
- onChange={e => setEmail(e.target.value)}
131
- placeholder="Email"
132
- />
133
- <button type="submit">Login</button>
134
- </form>
135
- )
136
- }
137
-
138
- // ------------------------------
139
- // Shopping Cart Component
140
- // ------------------------------
141
- function Cart() {
142
- const [items, setItems] = useState<CartItem[]>([])
143
-
144
- useObserver(() => {
145
- setItems(state.cart || [])
146
- }, [state.cart])
147
-
148
- const total = items.reduce((sum, item) => sum + item.price * item.quantity, 0)
149
-
150
- return (
151
- <div className="cart">
152
- <h2>Cart ({items.length})</h2>
153
- {items.map(item => (
154
- <div key={item.id}>
155
- {item.name} - ${item.price} x {item.quantity}
156
- </div>
157
- ))}
158
- <strong>Total: ${total}</strong>
159
- <div style={{ marginTop: '1rem' }}>
160
- <AddToCartButton
161
- product={{ id: 1, name: 'Sample Product', price: 9.99 }}
162
- />
163
- </div>
164
- </div>
165
- )
166
- }
167
-
168
- // ------------------------------
169
- // Add to Cart Button
170
- // ------------------------------
171
- function AddToCartButton({ product }: { product: { id: number, name: string, price: number } }) {
172
- return (
173
- <button onClick={() => {
174
- // Initialize cart if not exists
175
- if (!state.cart) {
176
- state.cart = []
177
- }
178
-
179
- // Add item or increment quantity
180
- const existing = state.cart.find(item => item.id === product.id)
181
- if (existing) {
182
- existing.quantity++
183
- } else {
184
- state.cart.push({
185
- id: product.id,
186
- name: product.name,
187
- price: product.price,
188
- quantity: 1
189
- })
190
- }
191
- }}>
192
- Add to Cart
193
- </button>
194
- )
195
- }
196
-
197
- // ------------------------------
198
- // Notifications Component
199
- // ------------------------------
200
- function Notifications() {
201
- const [notifications, setNotifications] = useState<Notification[]>([])
202
-
203
- useObserver(() => {
204
- setNotifications(state.notifications || [])
205
- }, [state.notifications])
206
-
207
- const unread = notifications.filter(n => !n.read).length
208
-
209
- return (
210
- <div className="notifications">
211
- <span>🔔 {unread} unread</span>
212
- {notifications.map(n => (
213
- <div key={n.id} className={n.read ? 'read' : 'unread'}>
214
- {n.message}
215
- </div>
216
- ))}
217
- </div>
218
- )
219
- }
220
-
221
- // ------------------------------
222
- // Settings Component
223
- // ------------------------------
224
- function Settings() {
225
- const [theme] = useState(state.theme)
226
- const [savedSettings, setSavedSettings] = useState<any>(null)
227
-
228
- // Load saved settings from store
229
- useEffect(() => {
230
- const settings = store.get('appSettings')
231
- if (settings) {
232
- setSavedSettings(settings)
233
- }
234
- }, [])
235
-
236
- const saveSettings = () => {
237
- store.set('appSettings', { theme: state.theme })
238
- alert('Settings saved!')
239
- }
240
-
241
- return (
242
- <div className="settings">
243
- <h2>Settings</h2>
244
-
245
- <label>
246
- Theme:
247
- <select
248
- value={theme}
249
- onChange={e => state.theme = e.target.value as 'light' | 'dark'}
250
- >
251
- <option value="light">Light</option>
252
- <option value="dark">Dark</option>
253
- </select>
254
- </label>
255
-
256
- <button onClick={saveSettings}>Save Settings</button>
257
-
258
- {savedSettings && (
259
- <p>Saved: {savedSettings.theme}</p>
260
- )}
261
- </div>
262
- )
263
- }
264
-
265
- // ============================================
266
- // 4. MAIN APP COMPONENT
267
- // ============================================
268
-
269
- function App() {
270
- // Initialize default state
271
- useEffect(() => {
272
- // Load theme from store
273
- const savedTheme = store.get('appSettings')?.theme
274
- if (savedTheme) {
275
- state.theme = savedTheme
276
- } else {
277
- state.theme = 'light'
278
- }
279
-
280
- // Initialize notifications
281
- state.notifications = [
282
- { id: '1', message: 'Welcome to Memorio!', read: false },
283
- { id: '2', message: 'Check out our new features', read: false }
284
- ]
285
-
286
- // Check for returning user
287
- const lastUser = store.get('lastUser')
288
- if (lastUser) {
289
- console.debug('Welcome back,', lastUser)
290
- }
291
- }, [])
292
-
293
- return (
294
- <div className={`app app--${state.theme}`}>
295
- <Header />
296
- <main>
297
- {state.user ? (
298
- <>
299
- <UserProfile />
300
- <Cart />
301
- <Notifications />
302
- <Settings />
303
-
304
- <button onClick={() => {
305
- // Logout - clear user but keep settings
306
- state.user = null
307
- }}>
308
- Logout
309
- </button>
310
- </>
311
- ) : (
312
- <LoginForm />
313
- )}
314
- </main>
315
- </div>
316
- )
317
- }
318
-
319
- export default App
320
-
321
- // ============================================
322
- // 5. USAGE SUMMARY
323
- // ============================================
324
-
325
- /*
326
- MEMORIO REACT USAGE GUIDE:
327
-
328
- 1. IMPORT ONCE (index.js or App.tsx):
329
- import 'memorio'
330
-
331
- 2. SET STATE:
332
- state.user = { name: 'Mario', email: 'mario@example.com' }
333
- state.theme = 'dark'
334
- state.cart = []
335
-
336
- 3. READ STATE:
337
- const value = state.user.name
338
- const theme = state.theme
339
-
340
- 4. REACT TO CHANGES:
341
- useObserver(() => {
342
- console.debug('State changed!')
343
- }, [state.user])
344
-
345
- 5. AUTO-DISCOVERY (watch all):
346
- useObserver(() => {
347
- console.debug(state.user, state.theme)
348
- })
349
-
350
- 6. PERSIST DATA:
351
- store.set('settings', { theme: 'dark' })
352
- const settings = store.get('settings')
353
-
354
- 7. SESSION DATA (cleared on tab close):
355
- session.set('token', 'abc123')
356
- const token = session.get('token')
357
-
358
- 8. CLEAR DATA:
359
- state.removeAll() // Clear all state
360
- store.removeAll() // Clear all persisted
361
- session.removeAll() // Clear all session
362
- */
@@ -1,91 +0,0 @@
1
- /**
2
- * Memorio Session Advanced Example
3
- *
4
- * This example shows advanced session (sessionStorage) operations.
5
- * Session data is cleared when the browser tab closes.
6
- *
7
- * Run: npx ts-node examples/session-advanced.ts
8
- */
9
-
10
- import 'memorio'
11
-
12
- // ============================================
13
- // CHECK PERSISTENCE
14
- // ============================================
15
-
16
- console.debug('=== Session Persistence Check ===')
17
- console.debug('Is persistent (survives tab close):', session.isPersistent)
18
- // In browser: true (sessionStorage)
19
- // In Node.js/Deno: false (memory fallback)
20
-
21
- if (!session.isPersistent) {
22
- console.debug('⚠️ Warning: Using in-memory storage. Data will be lost on process restart!')
23
- }
24
-
25
- // ============================================
26
- // AUTHENTICATION
27
- // ============================================
28
-
29
- // Store auth token (temporary - cleared when tab closes)
30
- session.set('authToken', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...')
31
- session.set('userId', 12345)
32
-
33
- // Check if user is logged in
34
- const token = session.get('authToken')
35
- if (token) {
36
- console.debug('User is logged in, token:', token.substring(0, 20) + '...')
37
- }
38
-
39
- // ============================================
40
- // FORM PROGRESS
41
- // ============================================
42
-
43
- // Save form draft
44
- session.set('formDraft', {
45
- name: 'Mario',
46
- email: 'mario@example.com',
47
- message: 'Hello world!'
48
- })
49
-
50
- // Restore on page refresh
51
- const draft = session.get('formDraft')
52
- if (draft) {
53
- console.debug('Restored draft:', draft)
54
- }
55
-
56
- // ============================================
57
- // SHOPPING CART
58
- // ============================================
59
-
60
- // Store cart items (temporary)
61
- session.set('cart', [
62
- { id: 1, name: 'Super Mushroom', price: 99, qty: 2 },
63
- { id: 2, name: 'Fire Flower', price: 199, qty: 1 }
64
- ])
65
-
66
- // Calculate total
67
- const cart = session.get('cart') || []
68
- const total = cart.reduce((sum, item) => sum + (item.price * item.qty), 0)
69
- console.debug('Cart total:', total)
70
-
71
- // ============================================
72
- // SESSION SIZE
73
- // ============================================
74
-
75
- // Get session storage size
76
- console.debug('Session size:', session.size(), 'bytes')
77
-
78
- // ============================================
79
- // CLEANUP
80
- // ============================================
81
-
82
- // Remove specific item
83
- session.remove('formDraft')
84
-
85
- // Clear all session data (logout)
86
- // session.removeAll()
87
-
88
- // Or use alias
89
- // session.clearAll()
90
-
91
- console.debug('Session advanced example complete!')
@@ -1,89 +0,0 @@
1
- /**
2
- * Memorio State Advanced Example
3
- *
4
- * This example shows advanced state features: locking, path tracking, and nesting.
5
- *
6
- * Run: npx ts-node examples/state-advanced.ts
7
- */
8
-
9
- import 'memorio'
10
-
11
- // ============================================
12
- // NESTED OBJECTS
13
- // ============================================
14
-
15
- // Create nested state
16
- state.user = {
17
- name: 'Mario',
18
- profile: {
19
- email: 'mario@example.com',
20
- settings: {
21
- theme: 'dark',
22
- notifications: true
23
- }
24
- }
25
- }
26
-
27
- // Access nested values
28
- console.debug('User name:', state.user.name)
29
- console.debug('Email:', state.user.profile.email)
30
- console.debug('Theme:', state.user.profile.settings.theme)
31
-
32
- // ============================================
33
- // ARRAYS
34
- // ============================================
35
-
36
- // State arrays work like regular arrays
37
- state.items = [1, 2, 3]
38
- state.items.push(4)
39
- console.debug('Items:', state.items) // [1, 2, 3, 4]
40
-
41
- state.users = [
42
- { name: 'Mario', id: 1 },
43
- { name: 'Luigi', id: 2 }
44
- ]
45
- state.users.push({ name: 'Peach', id: 3 })
46
- console.debug('Users:', state.users)
47
-
48
- // ============================================
49
- // LOCKING STATE
50
- // ============================================
51
-
52
- // Lock a value to prevent modifications
53
- state.config = { maxUsers: 100, timeout: 30 }
54
- state.config.lock()
55
-
56
- // This will fail:
57
- // state.config.maxUsers = 200 // Error: state 'config' is locked
58
-
59
- console.debug('Config locked:', state.config)
60
-
61
- // ============================================
62
- // PATH TRACKING
63
- // ============================================
64
-
65
- // Get path information
66
- console.debug('Path:', state.user.__path) // "state.user"
67
-
68
- // Use path tracker for debugging
69
- const path = state.user.profile
70
- console.debug('Profile path:', path.email.toString()) // "state.user.profile.email"
71
-
72
- // ============================================
73
- // LIST ALL STATES
74
- // ============================================
75
-
76
- // Get all current state keys
77
- console.debug('All states:', state.list)
78
-
79
- // ============================================
80
- // REMOVE STATE
81
- // ============================================
82
-
83
- // Remove specific state
84
- state.remove('items')
85
-
86
- // Remove all states
87
- // state.removeAll()
88
-
89
- console.debug('State advanced example complete!')
@@ -1,117 +0,0 @@
1
- /**
2
- * Memorio Store Advanced Example
3
- *
4
- * This example shows advanced store (localStorage) operations.
5
- *
6
- * Run: npx ts-node examples/store-advanced.ts
7
- */
8
-
9
- import 'memorio'
10
-
11
- // ============================================
12
- // CHECK PERSISTENCE
13
- // ============================================
14
-
15
- console.debug('=== Store Persistence Check ===')
16
- console.debug('Is persistent (survives restart):', store.isPersistent)
17
- // In browser: true (localStorage)
18
- // In Node.js/Deno: false (memory fallback)
19
-
20
- if (!store.isPersistent) {
21
- console.debug('⚠️ Warning: Using in-memory storage. Data will be lost on restart!')
22
- }
23
-
24
- // ============================================
25
- // PERSIST USER PREFERENCES
26
- // ============================================
27
-
28
- // Save user preferences
29
- store.set('preferences', {
30
- theme: 'dark',
31
- language: 'en',
32
- notifications: true,
33
- fontSize: 16
34
- })
35
-
36
- // ============================================
37
- // CHECK AND LOAD PREFERENCES
38
- // ============================================
39
-
40
- const savedPrefs = store.get('preferences')
41
- if (savedPrefs) {
42
- console.debug('Loaded preferences:', savedPrefs)
43
- } else {
44
- console.debug('No preferences found, using defaults')
45
- store.set('preferences', { theme: 'light', language: 'en' })
46
- }
47
-
48
- // ============================================
49
- // STORAGE QUOTA
50
- // ============================================
51
-
52
- // Get storage size
53
- const currentSize = store.size()
54
- console.debug('Current storage size:', currentSize, 'bytes')
55
-
56
- // ============================================
57
- // ALIAS METHODS
58
- // ============================================
59
-
60
- // store.delete() is alias for store.remove()
61
- store.set('temp', 'value')
62
- store.delete('temp')
63
-
64
- // store.clearAll() is alias for store.removeAll()
65
- // store.clearAll()
66
-
67
- // ============================================
68
- // ERROR HANDLING
69
- // ============================================
70
-
71
- // Try-catch for large data
72
- try {
73
- // Store large data
74
- const largeData = {
75
- items: Array(1000).fill(null).map((_, i) => ({ id: i, data: 'x'.repeat(100) }))
76
- }
77
- store.set('largeData', largeData)
78
- console.debug('Large data stored successfully')
79
- } catch (error) {
80
- console.error('Storage full:', error)
81
- }
82
-
83
- // ============================================
84
- // DATA SERIALIZATION
85
- // ============================================
86
-
87
- // Store supports all JSON-serializable types
88
- store.set('string', 'hello')
89
- store.set('number', 42)
90
- store.set('boolean', true)
91
- store.set('array', [1, 2, 3])
92
- store.set('object', { nested: { value: 'deep' } })
93
- store.set('null', null)
94
-
95
- // Functions are not supported (logged as error)
96
- store.set('function', () => { }) // logs: "It's not secure to store functions."
97
-
98
- // ============================================
99
- // PRACTICAL EXAMPLE: APP STATE
100
- // ============================================
101
-
102
- // Save app state
103
- const appState = {
104
- lastPage: '/dashboard',
105
- sidebarOpen: true,
106
- recentFiles: ['file1.txt', 'file2.pdf'],
107
- lastSaved: Date.now()
108
- }
109
- store.set('appState', appState)
110
-
111
- // Load on next visit
112
- const restored = store.get('appState')
113
- if (restored) {
114
- console.debug('Restored app state:', restored.lastPage)
115
- }
116
-
117
- console.debug('Store advanced example complete!')