# Memorio - LLM Documentation ## Overview **Memorio** is a cross-platform state management library that provides reactive state, persistence, and observation capabilities with zero dependencies. It works in Node.js, Deno, browsers, and edge environments. ``` npm i memorio ``` ## Core Concepts Memorio provides 6 storage modules plus utilities: | Module | Purpose | Persistence | |--------|---------|-------------| | `state` | Reactive, volatile state | In-memory (resets on refresh) | | `store` | localStorage persistence | Survives browser refresh | | `session` | sessionStorage | Dies with browser tab | | `cache` | In-memory cache | Fastest read, no persistence | | `idb` | IndexedDB | Structured, async, persistent (browser-only) | | `observer` | Object watcher | Legacy, deprecated | | `useObserver` | React hook | Auto-discovery of state paths | ## Quick Start ```javascript import 'memorio' // Set reactive state state.user = { name: 'Sara', role: 'admin' } state.counter = 0 // Observe changes (React hook) useObserver( () => { console.log('counter:', state.counter) }, [state.counter] ) ``` ## API Reference ### `state` — Reactive State Global, Proxy-based, reactive state management. ```javascript // Set values state.user = { name: 'Sara', role: 'admin' } state.items = [1, 2, 3] state.counter = 0 // Get values const name = state.user.name // 'Sara' // List all keys console.log(state.list) // ['user', 'items', 'counter'] // Remove one key state.remove('items') // Clear all state.removeAll() // Lock/unlock for frozen objects state.lock() // freeze everything state.unlock() // unfreeze ``` **Features:** - Automatic path tracking via `__path` property - Nested proxy support - Lock/unlock per-key or globally - Auto-dispatches events on changes ### `store` — localStorage Persistence Persistent storage that survives browser refresh. ```javascript // Set store.set('preferences', { theme: 'dark' }) // Get const prefs = store.get('preferences') // { theme: 'dark' } or null // List all keys store.list() // { preferences: { theme: 'dark' } } // Remove store.remove('preferences') // Delete (alias for remove) store.delete('preferences') // Clear all memorio items store.removeAll() // Clear all (alias for removeAll) store.clearAll() // Check size console.log(store.size(), 'chars stored') // Check if persistent (real localStorage vs memory fallback) console.log(store.isPersistent) // true → real localStorage // Estimate quota usage (returns [0, 0] for localStorage) await store.quota() // [usage, quota] in KB ``` ### `session` — sessionStorage Storage that dies when browser tab closes. ```javascript // Set session.set('token', 'user-abc-123') // Get const token = session.get('token') // 'user-abc-123' or null // List all keys session.list() // { token: 'user-abc-123' } // Remove session.remove('token') // Delete (alias for remove) session.delete('token') // Clear all session.removeAll() // Clear all (alias for removeAll) session.clearAll() // Check size console.log(session.size(), 'chars stored') // Check if persistent console.log(session.isPersistent) ``` ### `cache` — In-Memory Cache Fastest possible read, data lost on refresh. ```javascript // Set cache.set('temp', computeExpensiveResult()) // Get const result = cache.get('temp') // undefined or the value // List all keys cache.list() // { temp: } // Remove cache.remove('temp') // Clear all cache.clear() // Remove all (alias for clear) cache.removeAll() // Direct access (also works) cache['myKey'] = value const value = cache['myKey'] delete cache['myKey'] ``` ### `idb` — IndexedDB Structured, persistent, async database (browser-only). ```javascript // Create database await idb.db.create('my-db', 1) // version defaults to 1 // Create table (object store) await idb.table.create('my-db', 'users') // Set data await idb.data.set('my-db', 'users', { id: 1, name: 'Sara' }) // Get data by key const user = await idb.data.get('my-db', 'users', 1) // Delete data await idb.data.delete('my-db', 'users', 1) // List databases const dbs = await idb.db.list() // Check if database exists const exists = await idb.db.exist('my-db') // Delete database await idb.db.delete('my-db') // Get database size const size = await idb.db.size('my-db') // Get table size const tableSize = await idb.table.size('my-db', 'users') // Check support idb.db.support() // true if IndexedDB available // Check quota const [usage, quota] = await idb.db.quota() ``` **Note:** In Node.js/Deno, `idb` is disabled with a warning. Use `store` or `session` instead. ### `observer` — Object Watcher (DEPRECATED) Legacy observer API. Use `useObserver` instead. ```javascript // Listen to state changes observer('state.user', (newVal, oldVal) => { console.log('user changed:', newVal, oldVal) }) // Toggle listening (no callback) observer('state.counter') // Remove observer observer.remove('state.user') // List all observers console.log(observer.list) // Remove all observers observer.removeAll() ``` ### `useObserver` — React Hook Primary way to observe state changes in React components. ```jsx import 'memorio' import { useReducer } from 'react' function Counter() { const [, forceUpdate] = useReducer(x => x + 1, 0) // Auto-discovery mode (no deps) useObserver(() => { console.log('counter:', state.counter) }, state.counter) // Explicit deps mode useObserver( () => { console.log('user:', state.user) }, [state.user] ) return
Count: {state.counter}
} ``` **Features:** - Auto-discovery of state paths during render - Returns cleanup function to stop monitoring - Supports both Proxy objects and string paths ### `devtools` — Inspection Tools Inspect all memorio data in console. ```javascript // Pretty-print state, store, session, cache memorio.devtools.inspect() // Get stats memorio.devtools.stats() // { stateKeys, storeKeys, sessionKeys, ... } // Clear specific module memorio.devtools.clear('state') // Clear all modules memorio.devtools.clearAll() // Export all data as JSON memorio.devtools.exportData() // Import data from JSON memorio.devtools.importData(jsonString) // Show help memorio.devtools.help() // Console shortcuts $state // same as globalThis.state $store // same as globalThis.store $session // same as globalThis.session $cache // same as globalThis.cache ``` ### `logger` — Change Tracking Track every state change with timestamps. ```javascript // Configure logger memorio.logger.configure({ enabled: true, logToConsole: true, modules: ['state', 'store', 'session', 'cache', 'idb'] }) // Get history memorio.logger.getHistory() // [{ timestamp, module, action, path, value }, ...] // Get stats memorio.logger.getStats() // { total, state, store, session, cache, idb, set, get, ... } // Clear history memorio.logger.clearHistory() // Export logs memorio.logger.exportLogs() // JSON string of all history ``` ## Platform Detection Access via `memorio.*` after `import 'memorio'`: ```javascript memorio.isBrowser() // true in Chrome, Firefox, Safari memorio.isNode() // true in Node.js memorio.isDeno() // true in Deno memorio.isEdge() // true in Cloudflare Workers, Vercel Edge const caps = memorio.getCapabilities() // { platform: 'browser', hasLocalStorage: true, hasIndexedDB: true, sessionId: 'uuid', ... } // Create isolated context memorio.createContext('tenant-name') memorio.listContexts() memorio.deleteContext('context-id') memorio.isolate('tenant-name') // alias for createContext ``` ## Cross-Platform Support | Module | Browser | Node.js | Deno | Edge/Workers | |--------|---------|---------|------|--------------| | `state` | ✅ | ✅ | ✅ | ✅ | | `observer` / `useObserver` | ✅ | ✅ | ✅ | ✅ | | `cache` | ✅ | ✅ | ✅ | ✅ | | `store` | ✅ localStorage | ⚠️ memory | ⚠️ memory | ✅ localStorage | | `session` | ✅ sessionStorage | ⚠️ memory | ⚠️ memory | ✅ sessionStorage | | `idb` | ✅ IndexedDB | ❌ | ❌ | ⚠️ | | `devtools` | ✅ | ❌ | ❌ | ⚠️ | **Note:** `store` and `session` fall back to in-memory `Map` in Node.js/Deno. ## Session Isolation Each browser tab and server request gets an isolated namespace automatically via session IDs. ```javascript // Create isolated context memorio.createContext('tenant-name') memorio.listContexts() memorio.deleteContext('context-id') memorio.isolate('tenant-name') // alias for createContext ``` ## Security - Zero production dependencies - NIST & NSA aligned security standards - No `eval`, no obfuscation, no hardcoded secrets - All inputs validated, keys sanitized - Secure random session IDs via `crypto.randomUUID` ## License MIT © Dario Passariello (BigLogic Inc Canada) ## Utilities ### `memorio.dispatch` — Event Dispatch System Internal event system used by state changes. ```javascript // Dispatch a custom event memorio.dispatch.set('custom:event', { detail: { data: 'value' } }) // Listen for an event memorio.dispatch.listen('custom:event', (e) => { console.log('Event triggered:', e.detail) }) // Remove listener memorio.dispatch.remove('custom:event') ```