npm package: @litforge/state
Description: Core state management library for LitForge projects. Provides a flexible event-sourcing system with persistence, snapshots, and Redux DevTools integration.
Latest version: 0.1.22

# @litforge/state

Core state management library for LitForge projects. Provides a flexible event-sourcing system with persistence, snapshots, and Redux DevTools integration.

## Overview

`@litforge/state` is a framework-agnostic state management library that uses an event-sourcing pattern. It tracks all state changes as events, supports snapshots for performance, and provides persistence mechanisms for browser and Node.js environments.

## Key Features

- **Event Sourcing**: All state changes are tracked as immutable events
- **Persistence**: Built-in support for browser (IndexedDB/localStorage) and Node.js (file system)
- **Snapshots**: Create state snapshots for efficient replay
- **Redux DevTools**: Full integration with Redux DevTools extension
- **TypeScript**: Fully typed with TypeScript support
- **Framework Agnostic**: Works with any framework or vanilla JavaScript

## Installation

```bash
npm install @litforge/state
# or
pnpm add @litforge/state
# or
yarn add @litforge/state
```

## Basic Usage

### Creating a State System

```typescript
import { createStateSystem, BrowserPersistor } from '@litforge/state';

const stateSystem = createStateSystem({
  persistor: new BrowserPersistor(), // Optional: defaults to BrowserPersistor
});

// Load persisted state
await stateSystem.loadFromPersistor();
```

### Pushing Events

```typescript
// Push an event
const event = stateSystem.push({
  type: 'USER_LOGIN',
  payload: { userId: '123', username: 'john' },
  meta: { source: 'login-form' }
});
```

### Creating Snapshots

```typescript
const currentState = { user: { id: '123' }, todos: [] };
const snapshot = stateSystem.snapshot(currentState);
```

### Subscribing to Events

```typescript
const unsubscribe = stateSystem.subscribe((event) => {
  console.log('New event:', event);
});

// Later, unsubscribe
unsubscribe();
```

### Replaying Events

```typescript
await stateSystem.replay(
  targetIndex,
  (event, index) => {
    // Apply event to your state
    applyEventToState(event);
  },
  (snapshot) => {
    // Restore from snapshot (optional)
    restoreState(snapshot.state);
  }
);
```

### Export/Import

```typescript
// Export state
const json = stateSystem.export();

// Import state
await stateSystem.import(json);
```

## Singleton Pattern

For convenience, you can use the singleton pattern:

```typescript
import { initStateSystem, getStateSystem } from '@litforge/state';

// Initialize (typically in your app setup)
await initStateSystem({
  connectDevtools: true,
  getState: () => yourCurrentState,
  restoreState: (state) => { /* restore state */ },
  name: 'MyApp'
});

// Get the instance anywhere
const stateSystem = getStateSystem();
```

## Persistors

### BrowserPersistor

Uses IndexedDB with localStorage fallback:

```typescript
import { BrowserPersistor } from '@litforge/state';

const persistor = new BrowserPersistor();
```

### NodeFilePersistor

For Node.js environments:

```typescript
import { NodeFilePersistor } from '@litforge/state';

const persistor = new NodeFilePersistor('./state_store.json');
```

### Custom Persistor

Implement the `Persistor` interface:

```typescript
import type { Persistor, Persisted } from '@litforge/state';

class MyCustomPersistor implements Persistor {
  async save(data: Persisted): Promise<void> {
    // Your save logic
  }
  
  async load(): Promise<Persisted | null> {
    // Your load logic
  }
}
```

## Redux DevTools Integration

```typescript
import { connectReduxDevtools } from '@litforge/state';

const cleanup = connectReduxDevtools(
  stateSystem,
  () => yourCurrentState,
  {
    restoreState: (state) => { /* restore */ },
    name: 'MyApp'
  }
);
```

## Types

```typescript
import type {
  Event,
  Snapshot,
  Persistor,
  Subscriber,
  Persisted
} from '@litforge/state';
```

## API Reference

### ActionLog

Main class for managing events and snapshots.

- `push(event)`: Add a new event
- `snapshot(state)`: Create a state snapshot
- `getEvents(from, to)`: Get events in a range
- `subscribe(fn)`: Subscribe to new events
- `replay(index, applyEvent, restoreSnapshot)`: Replay events
- `export()`: Export state as JSON
- `import(json)`: Import state from JSON
- `loadFromPersistor()`: Load persisted state

## License

Part of the LitForge component library.