# Platform & Context Isolation - Memorio

> ℹ️ **New in v2.7.0, expanded in v3.0.2**: Context isolation system for multi-tenant server-side applications

Memorio automatically detects the runtime environment and adapts its behavior accordingly. This document explains platform compatibility, session isolation, and the new context system.

---

## Quick Reference: Client vs Server

### Which Module to Use?

| Scenario | Recommended Module | Persistence |
|----------|-------------------|-------------|
| UI State (React/components) | `state` | Memory |
| Temporary computed data | `cache` | Memory |
| User preferences | `store` | Browser localStorage |
| Auth tokens | `session` | Browser sessionStorage |
| Large offline data | `idb` | IndexedDB |
| Server request isolation | `memorio.createContext()` | Memory |

### Module Availability

| Module | Browser | Node.js | Deno | Edge |
|--------|--------|---------|------|------|
| `state` | ✅ | ✅ | ✅ | ✅ |
| `cache` | ✅ | ✅ | ✅ | ✅ |
| `store` | ✅ (localStorage) | ⚠️ (memory) | ⚠️ (memory) | ✅ |
| `session` | ✅ (sessionStorage) | ⚠️ (memory) | ⚠️ (memory) | ✅ |
| `idb` | ✅ | ❌ | ❌ | ⚠️ |
| `useObserver` | ✅ | ⚠️ | ⚠️ | ✅ |
| `devtools` | ✅ | ❌ | ❌ | ❌ |

---

## Platform Detection

Memorio automatically detects the environment on import:

```javascript
import 'memorio';

// Check current platform
console.debug(memorio.platform);   // 'browser' | 'node' | 'deno' | 'edge'
console.debug(memorio.isPersistent); // true if using real storage
```

### Available Platform APIs

```javascript
// Check platform
memorio.isBrowser()    // true in browser
memorio.isNode()      // true in Node.js
memorio.isDeno()      // true in Deno
memorio.isEdge()      // true in Edge Workers

// Get capabilities
const caps = memorio.getCapabilities();
// caps.platform, caps.hasSessionStorage, caps.hasLocalStorage, etc.
```

---

## Platform Compatibility Matrix

| Feature | Browser | Node.js | Deno | Edge Workers |
|---------|---------|---------|------|--------------|
| `state` | ✅ | ✅ | ✅ | ✅ |
| `observer` | ✅ | ✅ | ✅ | ✅ |
| `useObserver` | ✅ | ⚠️ React only | ⚠️ React only | ✅ |
| `cache` | ✅ | ✅ | ✅ | ✅ |
| `store` | ✅ (localStorage) | ⚠️ (memory) | ⚠️ (memory) | ✅ (localStorage) |
| `session` | ✅ (sessionStorage) | ⚠️ (memory) | ⚠️ (memory) | ✅ (sessionStorage) |
| `idb` | ✅ | ❌ | ❌ | ⚠️ |

- ✅ Full support
- ⚠️ Partial support (fallback to in-memory)
- ❌ Not available

---

## Client vs Server Usage

### 🖥️ Client-Side (Browser)

All features work with real browser storage:

```javascript
// Store - persistent localStorage
store.set('preferences', { theme: 'dark' });
store.isPersistent; // true

// Session - temporary sessionStorage
session.set('token', 'jwt-token');
session.isPersistent; // true (survives refresh)

// IDB - large data storage
idb.db.create('myApp');
```

### 🖥️ Server-Side (Node.js/Deno)

Use `state` and `cache` for in-memory data. Store/session fall back to memory:

```javascript
// State - in-memory global state
state.user = { name: 'Server User' };

// Cache - in-memory temporary cache
cache.set('apiResponse', data);

// Store - in-memory fallback (not persistent)
store.set('temp', data);
store.isPersistent; // false - data lost on restart

// Session - in-memory fallback
session.set('requestData', data);
session.isPersistent; // false - data lost on restart
```

---

## Session Isolation

Each instance/session gets unique storage keys to prevent conflicts:

```javascript
// Without context: "memorio_store_[sessionId]_key"
// With context: "[contextName]-key"
```

This ensures:
- Multiple browser tabs don't share session data
- Server-side requests are isolated

---

## Context Isolation (Server-Side Multi-Tenancy)

> ⚠️ **Server-Side Only**: This feature is designed for multi-tenant server environments (Node.js, Deno). Not needed for client-side applications.

For server-side applications handling multiple tenants (e.g., different users/requests), use **contexts** to isolate data:

### Creating a Context

```javascript
// Create isolated context for a user/session
const ctx = memorio.isolate('user-123');

// Keys in store/session are prefixed with context name
// store: "user-123-key"
// session: "user-123-key"

// Use context's isolated storage
ctx.state.user = { name: 'Isolated User' };
ctx.store.set('settings', { theme: 'dark' });
ctx.session.set('token', 'abc123');
ctx.cache.set('temp', data);

// Context is completely isolated from global state
console.debug(state.user); // undefined - global state is separate
```

### Managing Contexts

```javascript
// List all contexts
const contexts = memorio.listContexts();
console.debug(contexts); // ['user-123', 'user-456', ...]

// Delete a context (cleanup)
memorio.deleteContext('user-123');
```

> **Note**: `memorio.isolate('name')` is a shorthand alias for creating isolated contexts.

### Context Use Cases

#### 1. Per-Request Isolation (Express/Fastify)

```javascript
// Middleware to isolate each request
app.use((req, res, next) => {
  const ctx = memorio.createContext(`req-${req.id}`);
  req.memorioContext = ctx;
  next();
});

// In route handler
app.get('/user', (req, res) => {
  const ctx = req.memorioContext;
  ctx.state.user = getUserData();
  // Each request has isolated state
});
```

#### 2. Multi-Tenant SaaS

```javascript
// Each tenant gets isolated storage
function handleTenant(tenantId) {
  const ctx = memorio.createContext(tenantId);

  ctx.state.config = getTenantConfig(tenantId);
  ctx.store.set('data', tenantData);

  return ctx;
}
```

---

## Best Practices

### Client-Side (Browser)

1. Use `store` for persistent data (preferences, user settings)
2. Use `session` for temporary data (auth tokens)
3. Use `cache` for computed values
4. Use `state` for reactive UI state

### Server-Side (Node.js/Deno)

1. Use `memorio.createContext()` for each request/tenant
2. Don't use global `state`/`store`/`session` across requests
3. Use `cache` for request-scoped caching
4. Check `store.isPersistent` / `session.isPersistent` if persistence matters

### Edge Workers

Same as browser - localStorage and sessionStorage are available.

---

## API Reference

### Global Functions

| Function | Returns | Description |
|----------|---------|-------------|
| `memorio.isBrowser()` | `boolean` | Check if running in browser |
| `memorio.isNode()` | `boolean` | Check if running in Node.js |
| `memorio.isDeno()` | `boolean` | Check if running in Deno |
| `memorio.isEdge()` | `boolean` | Check if running in Edge |
| `memorio.getCapabilities()` | `object` | Get platform capabilities |

### Context Management

| Function | Returns | Description |
|----------|---------|-------------|
| `memorio.isolate(name?)` | `Context` | Create isolated context |
| `memorio.listContexts()` | `string[]` | List all context IDs |
| `memorio.deleteContext(id)` | `boolean` | Delete a context |

### Properties

| Property | Type | Description |
|----------|------|-------------|
| `memorio.version` | `string` | Memorio version |
| `memorio.platform` | `string` | Current platform |
| `memorio._sessionId` | `string` | Unique session identifier |
