# Zudux-State API Reference

This reference covers the public package surface. Import core APIs from `zudux-state` and React APIs from `zudux-state/react`.

> **Author signature:** Pradeep Kumar Sheoran (Stack Developer) · BSG Technologies · [+91-8595147850 (WhatsApp)](https://wa.me/918595147850) · [Visit the official website](https://bsgtechnologies.com) to meet, learn, contribute, discuss new topics, or accept a coffee invitation.

## Function selection guide

| If you need to… | Choose |
|---|---|
| Own a complete state boundary | `forgeDomain` |
| Preview command patches before commit | `domain.preview` |
| Cache a costly projection | `deriveView` |
| Compare flat selector objects | `shallowEqual` |
| Persist through a custom backend | `bindPersistence` |
| Use an in-memory persistence backend | `memoryPersistence` |
| Use `localStorage` or `sessionStorage` | `browserPersistence` |
| Synchronize domain instances | `bindRelay` |
| Use a browser channel transport | `broadcastRelay` |
| Connect monitoring callbacks | `telemetryModule` |
| Remove sensitive audit tags | `redactAudit` |
| Add risk-scored command policy | `forgeStateGuard` |
| Enforce command duration/patch/actor rules | `commandSlaModule` |
| Profile mutation cost | `forgeMutationProfiler` |
| Query audit history | `queryAudit` / `stateTimeline` |
| Replay audit history against new rules | `replayPolicy` |
| Isolate per-tenant domains | `forgeTenantHub` |
| Model domain dependency impact | `forgeDomainGraph` |
| Score production readiness | `scoreEnterpriseReadiness` |
| Subscribe from React | `useDomainSlice` |
| Bind a typed command in React | `useCommand` |

## `forgeDomain(options)`

Creates an isolated `Domain`. It has no global registry or implicit singleton.

Important options:

| Option | Purpose |
|---|---|
| `name` | Stable domain identity used by checkpoints and relays |
| `seed` | Initial state value or factory |
| `commands` | Typed business transitions |
| `policy` | Async or sync authorization gate |
| `invariants` | Pre-commit integrity rules |
| `modules` | Command lifecycle integrations |
| `historyLimit` | Maximum rollback snapshots; default `50` |
| `auditLimit` | Maximum audit records; default `500` |
| `clone` | Custom state cloning strategy |
| `freeze` | Deep-freeze published snapshots |
| `clock` / `identify` | Deterministic infrastructure overrides |

### Command context

Every command receives:

- `read()` — reads the command's private working draft.
- `edit(recipe)` — mutates that private draft.
- `signal` — cancellation signal checked by the engine.
- `commandId` — unique operation identity.
- `actor` and `tags` — trace and governance metadata.

Draft mutations are not externally visible. A draft becomes the current state only after the handler completes and all invariants pass.

## Domain methods

### `read()`

Returns the current published snapshot. With `freeze: true`, the snapshot is deeply frozen.

### `revision()`

Returns the monotonically increasing local commit revision.

### `run(name, payload, meta?)`

Queues and executes one typed command. The promise resolves to the handler result after commit. Policy rejection, cancellation, handler failure, and invariant failure reject the promise without publishing the draft.

### `preview(name, payload, meta?)`

Runs the same command path against a private draft and returns a `CommandPreview` with `ok`, `current`, `patches`, `inversePatches`, `result`, or `error`. It does not publish state, notify observers, write audit records, or call lifecycle modules. Use it for what-if screens, approval review, patch-cost inspection, and regulated workflows where a user must see the effect before commit.

### `atomic(label, operation, meta?)`

Provides a private `AtomicScope` with `read`, `edit`, and typed `invoke` methods. The entire operation emits one commit or rolls back.

### `watch(listener)`

Observes every successful commit and returns an unsubscribe function. Observer exceptions cannot invalidate a completed command.

### `watchSlice(select, listener, equality?)`

Runs the listener only when a selected value changes. Equality defaults to `Object.is`.

### `checkpoint()` / `restore(checkpoint, meta?)`

Creates and restores a cloned recovery point. A checkpoint from a differently named domain is rejected.

### `rewind(steps?, meta?)`

Restores a retained historical snapshot. Default is one step. Rewind depth cannot exceed `historyLimit` retention.

### `replace(next, label?, meta?)`

Replaces the state through invariants and the normal observer boundary. Intended for hydration, synchronization, and controlled recovery—not ordinary business commands.

### `audit()`

Returns defensive copies of bounded audit entries. Entries include revision, command, command ID, actor, tags, timestamps, duration, status, and rejection message.

### `dispose()`

Clears listeners/history and permanently rejects future domain use.

## Derived values

### `deriveView(projector, equality?)`

Returns `{ read(state), clear() }`. It avoids recomputing for the same state reference and preserves the prior derived reference when custom equality reports equivalence.

### `shallowEqual(left, right)`

Compares own keys using `Object.is`; useful for flat selector results.

## Persistence

### `bindPersistence(domain, port, options)`

Hydrates once, then saves versioned state after commits. Returns:

- `ready` — hydration completion promise.
- `flush()` — immediately writes pending state.
- `clear()` — removes persisted state.
- `stop()` — detaches persistence.

Options include `key`, `version`, `debounceMs`, `select`, `codec`, `migrate`, and `onFault`. Custom codecs enable encryption/compression without adding a mandatory dependency.

### Persistence ports

`memoryPersistence()` provides an isolated test/in-memory port. `browserPersistence(storage)` adapts Web Storage. Implement `PersistencePort` to connect databases, secure native storage, or remote caches.

## Relay

### `bindRelay(domain, port, options?)`

Publishes checkpoints and applies newer remote checkpoints while preventing feedback loops. Options provide `source`, a custom `accept` conflict rule, and `onFault`. A source string is also accepted as a shorthand. Use a custom `RelayPort` for workers, native bridges, WebSockets, or server transports.

### `broadcastRelay(channelName)`

Creates a browser `BroadcastChannel` relay port.

## Modules and audit

### `telemetryModule(sink)`

Maps command lifecycle events to `command`, `commit`, and `reject` callbacks. The sink may be asynchronous.

### `redactAudit(entry, hiddenTags?)`

Creates a copy without the named tag keys before export to logs or analytics.

## React entry point

### `useDomainSlice(domain, select, equality?)`

Subscribes with `useSyncExternalStore`, caches by published state identity, and preserves equal selected references.

### `useDomainRevision(domain)`

Subscribes to the numeric domain revision.

### `useCommand(domain, name, meta?)`

Returns a memoized, type-safe function that calls `domain.run(name, payload, meta)`.

## Error types

- `ZuduxStateFault` — base error with stable `code` and optional `cause`.
- `PolicyDeniedFault` — `POLICY_DENIED`.
- `InvariantFault` — `INVARIANT_REJECTED`.
- `DomainDisposedFault` — `DOMAIN_DISPOSED`.

`ZudFault` and `ZuduxFault` remain as deprecated compatibility aliases for `ZuduxStateFault`. New applications should import `ZuduxStateFault` from `zudux-state`.

## V2 domain capabilities

### Copy-on-write patches

Every successful command event contains `patches`. The runtime clones only changed branches and revokes the command draft after completion. `beginDraft()` and `applyStatePatches()` expose the same original patch engine for advanced integrations.

### `domain.speculate(label, recipe, effect, meta?)`

Publishes an optimistic recipe, executes the external effect without blocking the domain queue, and applies inverse patches if the effect rejects.

### `domain.addModule(module)` / `domain.injectCommand(name, handler)`

Adds runtime capabilities for lazy-loaded applications. Each method returns a removal function. Existing command names cannot be overwritten accidentally.

### `domain.inspect()`

Returns revision, queue depth, active commands, listeners, history, audit, and module counts.

### Run metadata

`RunMeta` supports actor, tags, abort signal, notification priority, queue deadline, and idempotency key.

## Advanced selectors

### `forgeSelector(inputs, calculate, options?)`

Creates a multi-input selector with configurable LRU capacity, result equality, slow-computation reporting, cache clearing, and hit/miss statistics.

### `trackView(calculate, equality?)`

Tracks accessed object paths and reuses the prior result while those paths remain referentially equal.

## Entity registry

### `forgeRegistry(options)`

Creates normalized entity operations with IDs, sorting, secondary indexes, bulk CRUD, selectors, and structural consistency auditing. Operations mutate a command draft and therefore participate in normal domain patches and transactions.

## Lightweight and transient state

### `forgeSignal(seed)`

Provides `read`, `change`, and `watch` on top of an isolated domain for small models.

### `forgeTransientChannel(initial, schedule?)`

Provides frame-coalesced mutable values for animation, pointer, sensor, and canvas workloads that should not enter durable business history.

## Resource hub

### `forgeResourceHub(endpoints)`

Creates a remote-state cache with typed endpoint arguments/data, request deduplication, cancellation, retry/backoff, stale/retention windows, tag invalidation, optimistic rollback, stream lifecycles, endpoint injection, and dehydrate/hydrate.

### `bindBrowserResourceRefresh(hub, targets)`

Refetches selected endpoints when connectivity returns or the document becomes visible.

## Workflows and scheduling

### `forgeWorkflow(operation, options?)`

Creates cancellable async work in `parallel`, `serial`, `latest`, `leading`, or `drop` mode. Context methods provide abort-aware delay, retry, and child-task fork.

### `waitForDomain(domain, predicate, options?)`

Waits for a future matching domain state with timeout and cancellation.

### `forgeScheduler(options?)`

Schedules tasks with priority, concurrency, maximum queue, deadlines, backpressure, drain, and close controls.

### `forgeCircuitBreaker(options?)`

Protects repeatedly failing async dependencies with closed/open/half-open states.

## Governance and schemas

### `forgePolicyEngine(rules, options?)`

Evaluates role/attribute rules with deny precedence, default effect, reason strings, an `AccessPolicy` adapter, and bulk simulation.

### `forgeSchema(version, shape)`

Creates a zero-dependency runtime object schema with `check`, `issues`, and `assert`.

### Diagnostics

`inspectSerializable`, `integrityModule`, `notificationLanes`, and `verifyAuditChain` provide runtime integrity checks, scheduling, and SHA-256 audit-chain validation.

## Enterprise intelligence

### `forgeStateGuard(rules, options?)`

Creates a risk-scored guard with `assess(input)`, `policy(base?)`, and `module(sink?)`. Use it when sensitive commands need score-based approval, denial, or audit tagging before they mutate state.

### `commandSlaModule(rules, onViolation)`

Adds command-level service rules for maximum duration, maximum patch count, required actor, allowed actors, and required tags. Violations are reported after commits or rejections without corrupting the command result.

### `forgeMutationProfiler()`

Returns a lifecycle module plus `report()` and `reset()`. The report groups command runs, rejection count, total/max duration, and total/max patch count so teams can find expensive or noisy mutations.

### `queryAudit(entries, query)` and `stateTimeline(entries)`

Filters audit entries by command, actor, status, tags, revision, duration, or patch count. `stateTimeline()` provides convenience views such as `byActor`, `byCommand`, `rejected`, `slow`, and `patchHeavy`.

### `replayPolicy(entries, policy, state, payloads?)`

Re-evaluates historical audit entries against a new policy. This helps answer "what would this rule have denied?" before deploying a governance change.

### `forgeTenantHub(factory)`

Creates and caches isolated domain instances per tenant ID. Use it for SaaS tenants, SSR requests, tests, and multi-account workspaces where accidental state sharing is unacceptable.

### `forgeRedactionProfiles(profiles)`

Creates named redaction profiles for audit entries. Each profile can replace selected tag values for developer, support, compliance, or public export views.

### `forgeDomainGraph()`

Builds a small dependency graph for domain impact analysis. Register links such as `account -> invoice` and ask which domains are affected when a source domain changes.

### `scoreEnterpriseReadiness(input)`

Scores a domain or application configuration across policy, invariants, audit, persistence, checksums, actor tags, rollback, tests, inspector, and schema validation. Returns a numeric score, grade, and missing controls.

### `replicaConflictStrategies`

Provides reusable replica resolution strategies: `applyPatches`, `serverAuthoritative`, and `lastWriteWins`.

## Inspector

`bindInspector` connects a domain to a transport-neutral inspector port. `memoryInspector` supports tests and `browserInspector` connects the included Manifest V3 DevTools panel.

## Event sourcing

### `forgeEventDomain(seed, events, options?)`

Creates a versioned event domain with typed payloads, event IDs, actor metadata, SHA-256 chain, deterministic replay, migration hook, subscriptions, and snapshot compaction.

## Coordination and replication

### `coordinateDomains(domains, operation, meta?)`

Stages recipes across enlisted domains, commits them in order, and restores prior checkpoints if a later domain rejects. This is saga-style atomic compensation rather than a database isolation guarantee.

### `bindReplica(domain, transport, options?)`

Builds an offline patch outbox with duplicate suppression, per-source vector progress, validation, custom resolution, missing-counter conflict hooks, and explicit flush.

## Test kit and code generation

- `deterministicRuntime()` supplies controllable time and IDs.
- `faultingPersistence()` injects storage failures/corruption.
- `replicaTestBus()` simulates delivery, drops, and reordering.
- `generateResourceTypes()` emits a typed resource-hub source scaffold from an OpenAPI-like document.
- `generateStateContract()` emits a TypeScript state contract and can include command payload/result contracts, policy names, invariant names, persistence metadata, and audit tags.

## React V2 entry point

- `createDomainScope(factory?)` creates a Provider, scoped domain hook, and scoped selector hook.
- `useResource(hub, name, argument, options?)` subscribes to a resource and begins loading through React's external-store contract.
