<div align="center">

# Zudux-State

### Advanced State Management Library for Future-Ready Enterprise Systems

**Zudux-State is an advanced, zero-runtime-dependency state management library built for future-demand enterprise applications where every transition must be intentional, observable, reversible, and governed.**

**Version 2 adds an original copy-on-write runtime, resource cache, workflow scheduler, indexed entity engine, event sourcing, offline replication, tamper-evident audit, and a dedicated Inspector—without adopting another state library.**

[![npm version](https://img.shields.io/npm/v/zudux-state?style=for-the-badge&color=dc2626)](https://www.npmjs.com/package/zudux-state)
[![TypeScript](https://img.shields.io/badge/TypeScript-strict-2563eb?style=for-the-badge)](https://www.typescriptlang.org/)
[![runtime dependencies](https://img.shields.io/badge/runtime_dependencies-0-16a34a?style=for-the-badge)](./package.json)
[![license](https://img.shields.io/badge/license-MIT-111827?style=for-the-badge)](./LICENSE)
[![Learn Here](https://img.shields.io/badge/Learn_Here-beginner_course-f59e0b?style=for-the-badge)](#-learn-here--beginner-lessons-for-every-public-function)
[![BSG Technologies](https://img.shields.io/badge/BSG-Technologies-7c3aed?style=for-the-badge)](https://bsgtechnologies.com)

### Created by Pradeep Kumar Sheoran (Stack Developer)

**BSG Technologies** · **WhatsApp/Contact:** [+91-8595147850](https://wa.me/918595147850)

### 🌐 [Visit the official BSG Technologies website](https://bsgtechnologies.com)

*Meet, learn, contribute, discuss new topics with us, or accept a coffee invitation.*

</div>

---

> ## 📦 Learn Here
>
> **New to state management? Start here.** Every public Zudux-State function is explained in easy language with syntax, parameters, return values, examples, output, errors, and practical use cases.
>
> [🚀 Quickstart](#your-first-domain) · [🧭 Lessons](#-learn-here--beginner-lessons-for-every-public-function) · [📋 Functions list](#-separate-functions-list) · [❓ Questions and answers](#-what-was-missing-and-what-can-you-do-now) · [📚 API reference](./API_REFERENCE.md) · [🌐 BSG Technologies](https://bsgtechnologies.com)

---

Most state tools answer one question: **“How do I update a value?”**

Zudux-State starts where that question ends. It treats state as a controlled operational domain—commands enter through one boundary, policies decide who may act, invariants decide what may exist, atomic commits prevent partial truth, and an audit trail explains what happened afterward.

It is designed for the next wave of application demand: AI-assisted products, financial workflows, regulated dashboards, collaborative tools, offline-first operations, multi-team platforms, and high-scale React applications where state must behave like accountable infrastructure, not scattered UI memory.

No borrowed state engine. No compatibility wrapper. No hidden runtime framework. Zudux-State has its own command pipeline, transaction coordinator, selector system, persistence protocol, history engine, policy boundary, relay protocol, and React adapter.

> Zudux-State is an independent implementation. It does not import, wrap, copy, or require Redux or Zustand. Those projects are not runtime dependencies and their APIs are not used by this package.

## Copyright and policy position

Zudux-State is built as an original library with its own architecture, runtime behavior, public API, documentation, and examples. The project is intended for legitimate enterprise use under the terms of its license, with respect for copyright, trademarks, and third-party project identities.

- Zudux-State does not copy Redux, Zustand, or any other state library source code.
- Zudux-State does not expose a disguised clone API or depend on another state engine at runtime.
- Redux and Zustand are mentioned only for transparent positioning and compatibility context.
- Enterprise teams should review the included `LICENSE`, security guidance, and internal compliance requirements before production adoption.

## Why serious applications choose an operational state layer

| Requirement | Zudux-State answer |
|---|---|
| Predictable updates | Named commands are serialized through one commit pipeline |
| Multi-step consistency | `atomic()` commits every operation together or rolls everything back |
| Least-privilege control | A domain-level policy can approve or deny every command |
| Invalid-state prevention | Invariants execute before state becomes visible |
| Production diagnosis | Bounded audit records include actor, timing, tags, outcome, and command ID |
| Safe recovery | Checkpoints, restore, and bounded rewind are first-class APIs |
| Efficient rendering | Slice subscriptions and memoized derived views avoid unrelated work |
| Durable state | Versioned persistence supports migrations and custom codecs |
| Multiple contexts | Relay bindings synchronize isolated domain instances |
| SSR and tests | Every `forgeDomain()` call creates an isolated instance; there is no global singleton |

## The V2 operational platform

Zudux-State now covers four distinct state workloads through one custom-owned platform:

| Workload | API |
|---|---|
| Governed business state | `forgeDomain()` |
| Minimal local state | `forgeSignal()` |
| High-frequency ephemeral values | `forgeTransientChannel()` |
| Remote/server state | `forgeResourceHub()` |

The domain engine uses revocable copy-on-write drafts. Updating one nested field preserves every untouched branch by reference and produces forward/inverse patches for inspection, rewind, optimistic rollback, synchronization, and compact history.

```ts
const before = account.read();
await account.run('credit', 500, { idempotencyKey: 'payment_932' });
const after = account.read();

// Unchanged branches retain identity; changed paths become patches.
```

### Beyond basic state updates

- `forgeSelector()` provides multi-input LRU memoization and profiling.
- `trackView()` automatically tracks accessed state paths.
- `forgeRegistry()` provides normalized entities, sorting, secondary indexes, bulk CRUD, and integrity audits.
- `forgeWorkflow()` provides serial/parallel/latest/leading/drop execution, cancellation, child tasks, retry, debounce, and throttle.
- `forgeScheduler()` adds priorities, deadlines, concurrency limits, backpressure, and drain control.
- `forgeResourceHub()` provides request deduplication, freshness, retention, invalidation, retries, optimistic updates, streams, code splitting, and SSR hydration.
- `forgeEventDomain()` provides versioned events, idempotent replay, snapshots, and hash-chain verification.
- `bindReplica()` provides an offline outbox, vector progress, patch exchange, validation, and conflict hooks.
- `forgePolicyEngine()` provides ordered deny/allow rules for role and attribute policies.
- `forgeSchema()` validates runtime state, persistence, and integration boundaries.
- `domain.preview()` runs a command as a dry run and returns proposed patches, result, or rejection without publishing state.
- `forgeStateGuard()` adds risk-scored policy checks for sensitive commands.
- `forgeMutationProfiler()`, `commandSlaModule()`, `queryAudit()`, and `stateTimeline()` turn audit records into operational intelligence.
- `forgeTenantHub()` creates isolated per-tenant domain instances for SaaS and SSR boundaries.
- `coordinateDomains()` coordinates business changes across enlisted domains with automatic compensation.
- `bindInspector()` and the included browser Inspector expose commands, patches, state, timing, and audit records.

## Complete feature map

| Area | What Zudux-State gives you |
|---|---|
| Original runtime | Revocable copy-on-write drafts, structural sharing, frozen published snapshots, forward/inverse patches, and patch replay |
| Typed commands | Named command catalog, inferred payload/result types, cancellation, deadlines, idempotency keys, actor/tags metadata, serialized execution, and pre-commit dry-run preview |
| Transactions | `atomic()` for one visible commit, automatic rollback on failure, speculative commits, checkpoint/restore, and bounded rewind |
| Derived data | `deriveView()`, `forgeSelector()`, `trackView()`, `shallowEqual()`, selector stats, cache clearing, and slow-computation reporting |
| Subscriptions | Full-domain events, slice watchers, custom equality, notification priorities, and React external-store hooks |
| Entities | Normalized IDs/records, add/put/update/remove, bulk writes, stable sorting, secondary indexes, multi-value indexes, and registry audits |
| Server state | Resource cache, request dedupe, abort support, retry/backoff, stale/retain windows, tag invalidation, optimistic rollback, streaming, polling, SSR hydration, and endpoint injection |
| Workflows | Parallel, serial, latest, leading, and drop modes; debounce, throttle, child tasks, retry, abort-aware delay, and condition waiting |
| Scheduling | Priority queues, concurrency limits, queue caps, deadlines, overload backpressure, graceful drain/close, and circuit breaker protection |
| Persistence | Pluggable storage ports, versioned envelopes, migrations, SHA-256 checksums, partial persistence, merge hooks, validation, codecs, manual hydration, debounced writes, flush, clear, and status |
| Governance | Domain policy, rule-based policy engine, deny precedence, role/attribute checks, simulation, risk-scored state guard, invariants, runtime schemas, and approval gates |
| Security | Tamper-evident audit hashes, HMAC-sealed checkpoints, sealed checkpoint verification, redaction profiles, audit redaction, and multi-approver gates |
| Event sourcing | Versioned event definitions, idempotent event IDs, event migration, deterministic replay, hash-chain validation, snapshots, and compaction |
| Distribution | Relay ports, browser broadcast relay, MessagePort/worker relay, offline patch replicas, outbox flushing, vector progress, validation, and conflict hooks |
| CRDT helpers | Counter merge and observed-set merge primitives for eventually consistent values |
| Inspector | Transport-neutral inspector protocol, in-memory inspector, browser bridge, and included Manifest V3 DevTools panel |
| Test kit | Deterministic clock/IDs, faulting persistence, replica packet bus, corruption/drop/reorder scenarios, and integration-friendly helpers |
| Code generation | OpenAPI-like resource source generation and TypeScript state-contract generation |
| Enterprise intelligence | Command preview, policy replay, mutation profiling, command SLAs, audit timeline queries, tenant isolation, dependency graph, conflict strategies, and readiness scoring |
| Platform | Zero core runtime dependencies, strict TypeScript, ESM output, isolated instances, SSR-friendly domains, optional React entry point, and Node/browser/native-safe adapters |

## Install

```bash
npm install zudux-state
```

The core has **zero runtime dependencies**. React is an optional peer dependency only when importing `zudux-state/react`.

## Your first domain

```ts
import { forgeDomain } from 'zudux-state';

const account = forgeDomain({
  name: 'account',
  seed: { balance: 0, status: 'active' as 'active' | 'locked' },

  commands: {
    credit(context, amount: number) {
      context.edit((draft) => {
        draft.balance += amount;
      });
      return context.read().balance;
    },

    lock(context, reason: string) {
      context.edit((draft) => {
        draft.status = 'locked';
      });
      return reason;
    },
  },

  policy: ({ actor, command }) => command !== 'lock' || actor === 'security-admin',
  invariants: [
    (state) => {
      if (state.balance < 0) throw new Error('Balance cannot be negative');
    },
  ],
  freeze: true,
  historyLimit: 100,
});

const newBalance = await account.run('credit', 500, {
  actor: 'billing-service',
  tags: { traceId: 'tr_71d9' },
});

console.log(newBalance);       // 500
console.log(account.read());  // { balance: 500, status: 'active' }
```

Command names, payloads, and results are inferred from the command catalog. A misspelled command or incorrect payload fails at compile time.

## One commit for an entire business operation

```ts
await account.atomic('settlement', async (flow) => {
  await flow.invoke('credit', 200, { actor: 'settlement-worker' });
  flow.edit((draft) => {
    draft.status = 'active';
  });
});
```

Observers see exactly one commit. If any command, policy, abort signal, or invariant fails, observers see none of it.

## React with render precision

```tsx
import { useCommand, useDomainSlice } from 'zudux-state/react';
import { account } from './account-domain';

export function BalanceCard() {
  const balance = useDomainSlice(account, (state) => state.balance);
  const credit = useCommand(account, 'credit', { actor: 'account-ui' });

  return (
    <button onClick={() => void credit(25)}>
      Balance: {balance}
    </button>
  );
}
```

`useDomainSlice` uses React's external-store contract and only exposes a new snapshot when the selected value changes. It is compatible with React 18 and newer.

## Persistence with schema evolution

```ts
import { bindPersistence, browserPersistence } from 'zudux-state';

const persistence = bindPersistence(account, browserPersistence(localStorage), {
  key: 'account-state',
  version: 2,
  migrate(stored, fromVersion) {
    if (fromVersion === 1) {
      return { ...(stored as object), status: 'active' } as {
        balance: number;
        status: 'active' | 'locked';
      };
    }
    throw new Error(`Unsupported stored version: ${fromVersion}`);
  },
});

await persistence.ready;
```

Bring an encrypted or compressed representation by supplying a custom `PersistenceCodec`; Zudux-State does not force a storage vendor or encryption package into your runtime.

## Observability without vendor lock-in

```ts
import { telemetryModule } from 'zudux-state';

const metrics = telemetryModule({
  commit(entry) {
    console.info(entry.command, entry.durationMs, entry.actor);
  },
  reject(entry, error) {
    console.error(entry.commandId, error);
  },
});
```

Add the module to `forgeDomain({ modules: [metrics] })`. Connect it to your own logger, OpenTelemetry bridge, analytics stream, or compliance pipeline.

## Which function should I use?

| Goal | Use |
|---|---|
| Create an isolated state boundary | `forgeDomain()` |
| Execute a typed business transition | `domain.run()` |
| Preview a command before commit | `domain.preview()` |
| Commit several transitions together | `domain.atomic()` |
| Read current state without subscribing | `domain.read()` |
| Observe every successful commit | `domain.watch()` |
| Observe one selected value | `domain.watchSlice()` |
| Build a memoized computation | `deriveView()` |
| Save a recovery point | `domain.checkpoint()` |
| Recover a prior point | `domain.restore()` or `domain.rewind()` |
| Persist and migrate state | `bindPersistence()` |
| Synchronize browser contexts | `bindRelay()` + `broadcastRelay()` |
| Feed monitoring infrastructure | `telemetryModule()` |
| Enforce command SLA rules | `commandSlaModule()` |
| Profile mutation cost | `forgeMutationProfiler()` |
| Query audit history | `queryAudit()` or `stateTimeline()` |
| Replay old audit entries against a new policy | `replayPolicy()` |
| Add risk-scored command governance | `forgeStateGuard()` |
| Isolate SaaS tenants or SSR requests | `forgeTenantHub()` |
| Model domain dependencies | `forgeDomainGraph()` |
| Score enterprise readiness | `scoreEnterpriseReadiness()` |
| Select state in React | `useDomainSlice()` from `zudux-state/react` |
| Trigger a command in React | `useCommand()` from `zudux-state/react` |
| Create a scoped React Provider | `createDomainScope()` from `zudux-state/react` |
| Read remote state in React | `useResource()` from `zudux-state/react` |
| Normalize and index records | `forgeRegistry()` |
| Deduplicate and cache API data | `forgeResourceHub()` |
| Run cancellable workflows | `forgeWorkflow()` |
| Synchronize offline replicas | `bindReplica()` |
| Build an event-sourced model | `forgeEventDomain()` |
| Inspect commands and patches | `bindInspector()` |
| Generate resource source from an API document | `generateResourceTypes()` |

## Enterprise boundaries by design

- **Governance:** actor-aware access policies execute before mutation.
- **Integrity:** proposed state must pass every invariant before publication.
- **Resilience:** failed and aborted operations discard their private drafts.
- **Concurrency:** async commands are serialized, preventing lost-update races.
- **Accountability:** command IDs, actors, tags, duration, and outcomes remain inspectable.
- **Recovery:** bounded history avoids unbounded memory while preserving rollback controls.
- **Isolation:** no module-level state means safe per-request SSR and deterministic tests.
- **Portability:** storage, telemetry, relay transport, clocks, IDs, and cloning are replaceable ports.

## 📦 Learn Here — beginner lessons for every public function

> **Easy reading rule:** `value` means the data you give a function; `options?` means the setting is optional; `Promise<T>` means use `await`; and `Stop` means a cleanup function that you should call when finished.
>
> These lessons live directly in this npm README so a fresher can learn on the package page. The longer authoring source is kept outside the published package payload.

### 🧭 Lesson navigation

[Core state](#1-core-state-and-selection) · [Data and async](#2-data-async-and-durability) · [Security and enterprise](#3-security-distribution-and-enterprise) · [Testing and React](#4-testing-code-generation-and-react) · [Functions list](#-separate-functions-list) · [Q&A](#-what-was-missing-and-what-can-you-do-now)

Each row is one mini lesson. The **Parameters** column is the parameter table for that function; the last column shows a tiny example, its expected output, common error behavior, and when to use it.

### 1. Core state and selection

| Function and description | Syntax | Parameters | Return value | Example → output · errors · use case |
|---|---|---|---|---|
| `forgeDomain` — creates a safe business-state container. | `forgeDomain(options)` | `options`: name, seed, commands; policy/invariants optional. | A typed `Domain`. | `forgeDomain({ name:'cart', seed:{n:0}, commands })` → domain object. Invalid options/failed invariants throw. Use for app business state. |
| `deriveView` — remembers a calculated value. | `deriveView(projector, equality?)` | `projector`: calculation; `equality?`: result comparison. | `{ read, clear }`. | `deriveView(s => s.items.length).read(state)` → `2`. Projector errors pass through. Use for derived totals. |
| `shallowEqual` — compares two flat objects. | `shallowEqual(left, right)` | `left`, `right`: flat records. | `boolean`. | `shallowEqual({a:1},{a:1})` → `true`. Nested values compare by reference. Use for selector results. |
| `beginDraft` — starts a copy-on-write edit session. | `beginDraft(base)` | `base`: original state. | `DraftSession`. | `const d=beginDraft({n:1}); d.draft.n=2; d.finish()` → patches for `n`. A finished/revoked draft rejects edits. Use for custom tooling. |
| `applyStatePatches` — replays patches on state. | `applyStatePatches(state, patches)` | `state`: base value; `patches`: patch array. | New state. | `applyStatePatches({n:1}, [{op:'set',path:['n'],value:2}])` → `{n:2}`. Bad paths throw. Use for replay/sync. |
| `forgeSelector` — caches a multi-input calculation. | `forgeSelector(inputs, calculate, options?)` | `inputs`: selector array; `calculate`: combiner; `options?`: cache/profiling. | `SmartSelector`. | `selector.read(state)` → cached total. Calculation errors pass through. Use for expensive projections. |
| `trackView` — tracks only state paths a calculation reads. | `trackView(calculate, equality?)` | `calculate`: view builder; `equality?`: comparator. | `TrackedView`. | `trackView(s => s.user.name).read(state)` → `'Asha'`. Non-object state is invalid. Use for fine-grained views. |
| `forgeRegistry` — manages normalized records and indexes. | `forgeRegistry(options)` | `options`: ID selector, sort/index settings. | `EntityRegistry`. | `users.add(draft,{id:1,name:'A'})` → ID `1` stored. Duplicate/invalid IDs can fail. Use for user/product lists. |
| `forgeSignal` — creates very small isolated state. | `forgeSignal(seed)` | `seed`: object or factory. | `StateSignal`. | `signal.change(d => { d.count++ })` → `read().count === 1`. Disposed signal rejects use. Use for compact local models. |
| `forgeTransientChannel` — stores fast, non-durable values. | `forgeTransientChannel(initial, schedule?)` | `initial`: value; `schedule?`: notification scheduler. | `TransientChannel`. | `pointer.write({x:10,y:5})` → next `read()` returns coordinates. Scheduler errors surface. Use for pointer/canvas data. |

### 2. Data, async, and durability

| Function and description | Syntax | Parameters | Return value | Example → output · errors · use case |
|---|---|---|---|---|
| `forgeResourceHub` — caches API/server data. | `forgeResourceHub(endpoints)` | `endpoints`: named request definitions. | `ResourceHub`. | `await hub.fetch('user',1)` → user data and cached snapshot. Fetch errors appear in snapshot/reject. Use for remote data. |
| `bindBrowserResourceRefresh` — refreshes data after focus/reconnect. | `bindBrowserResourceRefresh(hub, targets)` | `hub`: resource hub; `targets`: function returning resources. | `Stop`. | `const stop=bindBrowserResourceRefresh(hub, targets)` → cleanup function. Browser globals are required. Use in web apps. |
| `pollResource` — repeatedly refreshes one resource. | `pollResource(hub, name, argument, intervalMs, options?)` | Hub, endpoint name, argument, interval, optional force. | `Stop`. | `pollResource(hub,'rates',{},5000)` → polling starts. Fetch faults remain in hub state. Use for live dashboards. |
| `forgeWorkflow` — runs cancellable async jobs. | `forgeWorkflow(operation, options?)` | `operation`: async task; `options?`: mode/debounce/throttle. | `Workflow`. | `await flow.start(4)` → operation result. Abort/failure rejects task. Use for search, save, upload flows. |
| `waitForDomain` — waits until state matches a rule. | `waitForDomain(domain, predicate, options?)` | Domain, predicate, timeout/signal options. | `Promise<state>`. | `await waitForDomain(d,s=>s.ready)` → matching state. Timeout/abort rejects. Use for orchestration. |
| `forgeScheduler` — runs queued jobs with limits. | `forgeScheduler(options?)` | Optional concurrency and max queue. | `TaskScheduler`. | `await scheduler.run(() => 7)` → `7`. Closed/full/deadline queue rejects. Use for controlled background work. |
| `forgeCircuitBreaker` — pauses calls after repeated failures. | `forgeCircuitBreaker(options?)` | Failure threshold and reset delay. | `CircuitBreaker`. | `await breaker.run(apiCall)` → API result. Open breaker rejects fast. Use around unstable services. |
| `bindPersistence` — hydrates and saves a domain. | `bindPersistence(domain, port, options)` | Domain, storage port, key/version/migration settings. | `PersistenceBinding`. | `await binding.ready` → saved state loaded. Corrupt/read/write errors reach `onFault`. Use for reload survival. |
| `memoryPersistence` — creates temporary storage. | `memoryPersistence()` | None. | `PersistencePort`. | `await port.write('x','1'); await port.read('x')` → `'1'`. No durable storage. Use in tests. |
| `browserPersistence` — adapts Web Storage. | `browserPersistence(storage)` | `storage`: `localStorage` or `sessionStorage`. | `PersistencePort`. | `browserPersistence(localStorage)` → usable port. Quota/security errors reject. Use in browsers. |
| `nativePersistence` — adapts async mobile storage. | `nativePersistence(storage)` | Async object with get/set/remove methods. | `PersistencePort`. | `nativePersistence(deviceStore)` → usable port. Adapter errors reject. Use in React Native/mobile shells. |
| `bindRelay` — synchronizes domain checkpoints. | `bindRelay(domain, port, options?)` | Domain, relay port, optional source/conflict rule. | `RelayBinding`. | `bindRelay(cart,port)` → active binding. Transport/apply faults call `onFault`. Use across app contexts. |
| `broadcastRelay` — creates a browser-channel relay. | `broadcastRelay(channelName)` | `channelName`: shared channel string. | `RelayPort`. | `broadcastRelay('cart')` → port. Throws where `BroadcastChannel` is unavailable. Use across tabs. |
| `messageRelay` — adapts MessagePort-style endpoints. | `messageRelay(endpoint)` | Endpoint with post/listen methods. | `RelayPort`. | `messageRelay(workerPort)` → port. Endpoint faults surface. Use with workers/native bridges. |
| `bindReplica` — synchronizes offline patches. | `bindReplica(domain, transport, options?)` | Domain, replica transport, conflict/validation options. | `ReplicaBinding`. | `await replica.flush()` → queued patches sent. Transport/conflict errors are reported. Use offline-first apps. |
| `forgeEventDomain` — creates event-sourced state. | `forgeEventDomain(seed, events, options?)` | Initial state, event reducers, version/replay options. | `EventDomain`. | `events.emit('credited',50)` → state/event log updated. Unknown/invalid events reject. Use for deterministic history. |
| `coordinateDomains` — stages work across domains. | `coordinateDomains(domains, operation, meta?)` | Domain list, coordinated operation, optional metadata. | `Promise<Result>`. | `await coordinateDomains([a,b], flow)` → result after all commits. Later failure restores earlier checkpoints. Use for sagas. |

### 3. Security, distribution, and enterprise

| Function and description | Syntax | Parameters | Return value | Example → output · errors · use case |
|---|---|---|---|---|
| `forgePolicyEngine` — evaluates allow/deny rules. | `forgePolicyEngine(rules, options?)` | Rules plus optional default effect. | `PolicyEngine`. | `await engine.decide(input)` → `{allowed, reason}`. Rule errors reject. Use for roles/attributes. |
| `forgeSchema` — validates plain runtime objects. | `forgeSchema(version, shape)` | Schema version and field shape. | `StateSchema`. | `schema.check({age:20})` → `true`. `assert` throws on mismatch. Use at persistence/API boundaries. |
| `inspectSerializable` — finds unsafe state values. | `inspectSerializable(value)` | Any value to inspect. | `DiagnosticIssue[]`. | `inspectSerializable({fn(){}})` → issue for `fn`. It reports instead of throwing. Use before persistence. |
| `integrityModule` — checks committed state serializability. | `integrityModule(onIssue)` | Callback receiving diagnostic issues. | `DomainModule`. | `integrityModule(console.log)` → module. Callback errors are lifecycle faults. Use during development. |
| `notificationLanes` — schedules updates by priority. | `notificationLanes()` | None; returned function takes notify + priority. | Notification scheduler. | `lanes()(() => render(),'background')` → render queued. Callback errors occur when run. Use for UI priority. |
| `verifyAuditChain` — checks audit hashes. | `verifyAuditChain(entries)` | Audit entries in original order. | `boolean`. | `verifyAuditChain(domain.audit())` → `true`. Returns `false` for tampering. Use for audit integrity. |
| `sealCheckpoint` — signs a checkpoint. | `sealCheckpoint(checkpoint, secret)` | Checkpoint and signing secret. | `Promise<SealedCheckpoint>`. | `await sealCheckpoint(cp,'secret')` → checkpoint + signature. Crypto/serialization failures reject. Use before storage/transfer. |
| `verifySealedCheckpoint` — verifies a signed checkpoint. | `verifySealedCheckpoint(sealed, secret)` | Sealed checkpoint and same secret. | `Promise<boolean>`. | `await verifySealedCheckpoint(sealed,'secret')` → `true`. Wrong secret returns `false`. Use before restore. |
| `redactPaths` — hides selected data paths. | `redactPaths(value, paths, replacement?)` | Value, dot paths, optional replacement. | Redacted copy. | `redactPaths(user,['password'])` → password becomes `[REDACTED]`. Invalid paths are safely skipped. Use before logging. |
| `forgeApprovalGate` — requires several approvals. | `forgeApprovalGate(options?)` | Required approval count and TTL. | `ApprovalGate`. | `gate.approve(id,'lead')` → approval status. Expired/duplicate approvals do not unlock early. Use for sensitive changes. |
| `forgeCounterCrdt` — merges distributed counters. | `forgeCounterCrdt(source)` | Unique replica/source ID. | Mergeable counter. | `counter.add(2); counter.value()` → `2`. Reusing source IDs causes incorrect semantics. Use distributed counts. |
| `forgeObservedSet` — merges distributed sets. | `forgeObservedSet(identify)` | Function returning stable item IDs. | Mergeable observed set. | `set.add(user); set.value()` → `[user]`. Unstable IDs break merging. Use distributed membership. |
| `bindInspector` — sends domain activity to an inspector. | `bindInspector(domain, port)` | Domain and inspector port. | `Stop`. | `const stop=bindInspector(d,port)` → inspector receives events. Port faults may surface. Use for DevTools. |
| `memoryInspector` — records inspector messages in memory. | `memoryInspector()` | None. | Inspector port with `messages()`. | `port.messages()` → recorded array. No browser UI. Use in tests. |
| `browserInspector` — connects to the browser inspector channel. | `browserInspector(channel?)` | Optional channel name. | `InspectorPort`. | `browserInspector()` → bridge port. Requires browser channel support. Use with included DevTools panel. |
| `telemetryModule` — forwards command lifecycle events. | `telemetryModule(sink)` | Sink with command/commit/reject callbacks. | `DomainModule`. | `telemetryModule({commit:e=>log(e)})` → module. Sink failures are isolated/reported. Use observability. |
| `redactAudit` — removes selected audit tags. | `redactAudit(entry, hiddenTags?)` | Audit entry and tag names to hide. | Redacted `AuditEntry`. | `redactAudit(entry,['token'])` → safe copy. Original is unchanged. Use before export. |
| `forgeStateGuard` — scores command risk. | `forgeStateGuard(rules, options?)` | Risk rules and threshold options. | `StateGuard`. | `await guard.assess(input)` → score/decision report. Rule failures reject. Use for governed commands. |
| `commandSlaModule` — checks command service rules. | `commandSlaModule(rules, onViolation)` | SLA rules and violation callback. | `DomainModule`. | Slow command → callback receives violation. Callback runs after outcome. Use for operational policy. |
| `forgeMutationProfiler` — measures command cost. | `forgeMutationProfiler()` | None. | `MutationProfiler`. | `profiler.report()` → command timing/patch stats. Empty usage returns empty report. Use performance audits. |
| `queryAudit` — filters audit records. | `queryAudit(entries, query)` | Audit list and filters. | Matching entries. | `queryAudit(log,{command:'pay'})` → only pay records. Invalid ranges simply match none. Use investigations. |
| `replayPolicy` — tests old events against a new policy. | `replayPolicy(entries, policy, state, payloads?)` | Audit list, policy, state, optional payload map. | `Promise<PolicyReplayResult[]>`. | `await replayPolicy(...)` → allowed/denied per entry. Policy errors reject. Use rule simulations. |
| `forgeTenantHub` — owns one domain per tenant. | `forgeTenantHub(factory)` | Factory receiving tenant ID. | `TenantHub`. | `hub.get('acme')` → isolated Acme domain. Factory errors pass through. Use SaaS/SSR isolation. |
| `forgeRedactionProfiles` — creates named redaction views. | `forgeRedactionProfiles(profiles)` | Array of named redaction profiles. | Profile helper object. | `profiles.apply('support',entry)` → safe entry. Unknown profile throws. Use audience-specific logs. |
| `forgeDomainGraph` — maps domain dependencies. | `forgeDomainGraph()` | None. | `DomainDependencyGraph`. | `graph.link('account','invoice')` → dependency stored. Cycles are handled as graph data. Use impact analysis. |
| `bindDomainGraph` — connects a live domain to the graph. | `bindDomainGraph(graph, domain, dependencies)` | Graph, domain, dependency names. | `Stop`. | `bindDomainGraph(g,orders,['stock'])` → live registration. Call cleanup on disposal. Use architecture maps. |
| `scoreEnterpriseReadiness` — grades production controls. | `scoreEnterpriseReadiness(input)` | Boolean/control readiness facts. | Score, grade, missing list. | `scoreEnterpriseReadiness(input)` → e.g. `{score:80,grade:'B'}`. Missing values lower score. Use release reviews. |
| `stateTimeline` — creates audit convenience views. | `stateTimeline(entries)` | Audit entries. | Query helper object. | `stateTimeline(log).rejected()` → rejected records. Empty input returns empty views. Use support/debugging. |
| `electBrowserLeader` — chooses one leader tab. | `electBrowserLeader(name, options?)` | Election name, heartbeat/timeout/ID options. | `LeaderElection`. | `election.isLeader()` → `true` in one active tab. Requires browser storage/events. Use single-tab jobs. |

### 4. Testing, code generation, and React

| Function and description | Syntax | Parameters | Return value | Example → output · errors · use case |
|---|---|---|---|---|
| `deterministicRuntime` — controls test time and IDs. | `deterministicRuntime(startAt?)` | Optional starting timestamp. | `DeterministicRuntime`. | `runtime.now()` → chosen time; advance then read new time. Use repeatable tests. |
| `faultingPersistence` — simulates storage failures. | `faultingPersistence(options?)` | Read/write/corruption fault settings. | `PersistencePort`. | Configured write → rejected promise. This is intentional. Use resilience tests. |
| `replicaTestBus` — simulates replica delivery. | `replicaTestBus(options?)` | Optional drop/reorder behavior. | Test bus with transports/control. | Connect two replicas → packets delivered/dropped as configured. Use offline-sync tests. |
| `generateResourceTypes` — generates resource TypeScript. | `generateResourceTypes(document, importFrom?)` | OpenAPI-like document and optional import path. | Source-code string. | `generateResourceTypes(doc)` → TypeScript text. Invalid shapes may produce limited output. Use scaffolding. |
| `generateStateContract` — generates a typed state contract. | `generateStateContract(name, shape, options?)` | Type name, field map, optional contracts. | Source-code string. | `generateStateContract('Cart',{total:'number'})` → TS interface text. Invalid identifiers create unusable TS. Use scaffolding. |
| `useDomainSlice` — subscribes React to one state slice. | `useDomainSlice(domain, select, equality?)` | Domain, selector, optional comparator. | Selected slice. | `useDomainSlice(cart,s=>s.total)` → `250`; rerenders only when total changes. Selector errors reach React boundary. |
| `useDomainRevision` — subscribes React to revision number. | `useDomainRevision(domain)` | Domain. | `number`. | First render → `0`; after commit → `1`. Disposed domain use can fail. Use debug/status UI. |
| `useCommand` — creates a typed React command callback. | `useCommand(domain, name, meta?)` | Domain, command name, optional run metadata. | Async payload function. | `await credit(50)` → command result. Policy/invariant/handler errors reject. Use buttons/forms. |
| `createDomainScope` — creates a scoped React Provider. | `createDomainScope(factory?)` | Optional domain factory. | Provider + hooks. | `<Scope.Provider>` → descendants access domain. Missing provider/factory throws. Use SSR/component isolation. |
| `useResource` — subscribes React to cached remote data. | `useResource(hub, name, argument, options?)` | Hub, endpoint, argument, enabled/force options. | `ResourceSnapshot`. | Hook returns `{status:'loading'}` then data. Fetch error appears in snapshot. Use normal loading UIs. |
| `useResourceSuspense` — reads resource data with Suspense. | `useResourceSuspense(hub, name, argument)` | Hub, endpoint name, argument. | Endpoint data. | Returns user after load; throws promise while loading or error on failure. Use React Suspense boundaries. |

> **Important non-function exports:** `ZuduxStateFault`, `PolicyDeniedFault`, `InvariantFault`, and `DomainDisposedFault` are error classes for `catch` checks. `replicaConflictStrategies` is a ready-made strategy object, not a function. Deprecated `ZudFault` and `ZuduxFault` aliases remain temporarily available so existing users can migrate safely.

## 📋 Separate functions list

**Core (61):** `forgeDomain`, `deriveView`, `shallowEqual`, `beginDraft`, `applyStatePatches`, `forgeSelector`, `trackView`, `forgeRegistry`, `forgeSignal`, `forgeTransientChannel`, `forgeResourceHub`, `bindBrowserResourceRefresh`, `pollResource`, `forgeWorkflow`, `waitForDomain`, `forgeScheduler`, `forgeCircuitBreaker`, `bindPersistence`, `memoryPersistence`, `browserPersistence`, `nativePersistence`, `bindRelay`, `broadcastRelay`, `messageRelay`, `bindReplica`, `forgeEventDomain`, `coordinateDomains`, `forgePolicyEngine`, `forgeSchema`, `inspectSerializable`, `integrityModule`, `notificationLanes`, `verifyAuditChain`, `sealCheckpoint`, `verifySealedCheckpoint`, `redactPaths`, `forgeApprovalGate`, `forgeCounterCrdt`, `forgeObservedSet`, `bindInspector`, `memoryInspector`, `browserInspector`, `telemetryModule`, `redactAudit`, `forgeStateGuard`, `commandSlaModule`, `forgeMutationProfiler`, `queryAudit`, `replayPolicy`, `forgeTenantHub`, `forgeRedactionProfiles`, `forgeDomainGraph`, `bindDomainGraph`, `scoreEnterpriseReadiness`, `stateTimeline`, `electBrowserLeader`, `deterministicRuntime`, `faultingPersistence`, `replicaTestBus`, `generateResourceTypes`, `generateStateContract`.

**React (6, import from `zudux-state/react`):** `useDomainSlice`, `useDomainRevision`, `useCommand`, `createDomainScope`, `useResource`, `useResourceSuspense`.

## ❓ What was missing and what can you do now?

| Fresher question | Before | Now | Easy answer |
|---|---|---|---|
| “Which function starts my app state?” | The large API could feel difficult to enter. | A function-selection guide and per-function lessons exist. | Start with `forgeDomain`; add advanced tools only when needed. |
| “How do I know the syntax and return value?” | Information was spread across reference sections. | Every public function has syntax, parameters, returns, output, errors, and use case in one row. | Find the function in Learn Here and read left to right. |
| “Can I learn without another tutorial website?” | The separate lesson file was packaged into `node_modules`. | The beginner course is directly on the npm package README. | Open the Zudux-State npm page and use the lesson navigation. |
| “Can I use Zudux-State without React?” | React examples could make the boundary unclear. | Core and React functions are separately listed. | Import core from `zudux-state`; only React users import `zudux-state/react`. |
| “Can I safely store state?” | Basic state alone did not explain migration and integrity. | Persistence, schema, checksum, sealing, redaction, and audit tools are documented. | Begin with `bindPersistence`, then add `forgeSchema` for boundary checks. |
| “Can I handle API data?” | Business state and server state could be mixed. | Resource hub, polling, refresh, and React resource hooks are explained. | Use `forgeResourceHub` for API/server data. |
| “Can I test failures?” | Happy-path examples were easier to find than failure tools. | Deterministic runtime, faulting storage, and replica bus lessons are included. | Use the test-kit functions before production release. |
| “What should I build next?” | Advanced capability discovery required reading many files. | The feature map, selection guide, lessons, and Q&A connect the path. | Domain → selector → persistence/resources → workflow → governance. |

### Quick self-check questionnaire

1. **Do you need ordinary business state?** Use `forgeDomain`.
2. **Do you need API caching?** Use `forgeResourceHub`, not extra fields in every domain.
3. **Do you need a React rerender for only one value?** Use `useDomainSlice`.
4. **Do you need reload survival?** Use `bindPersistence` with a storage port.
5. **Do you need an async task where older work should cancel?** Use `forgeWorkflow` in `latest` mode.
6. **Do you need security approval before a sensitive change?** Combine policy/guard rules with `forgeApprovalGate`.
7. **Do you need to reproduce hard failures in tests?** Use `deterministicRuntime`, `faultingPersistence`, and `replicaTestBus`.

## More documentation

- [API Reference](./API_REFERENCE.md) — every public function and selection guidance
- [Feature Inventory](./FEATURES.md) — complete capability map
- [Architecture](./ARCHITECTURE.md) — commit pipeline, trust boundaries, and scaling model
- [Security](./SECURITY.md) — threat model and safe integration guidance
- [Examples](./examples) — runnable core and React patterns
- [Changelog](./CHANGELOG.md) — release history
- [Enterprise V2 Guide](./ENTERPRISE_GUIDE.md) — advanced subsystems and deployment guidance
- [V2 Migration](./MIGRATION_V2.md) — behavior changes and upgrade checklist

## Compatibility and independence

- ESM package; Node.js 18+.
- Modern browsers with `structuredClone`, `AbortController`, and optional `BroadcastChannel` for relay support.
- React is optional and isolated to the `zudux-state/react` entry point.
- Core runtime dependencies: **none**.
- TypeScript is used only to build the package; it is not shipped as a runtime dependency.

## Philosophy

Tiny applications need convenient updates. Large applications need controlled truth. Zudux-State is built for the moment state stops being local convenience and starts carrying money, permissions, workflows, customer intent, and operational risk.

**Own the transition. Prove the outcome. Recover with confidence.**

## License

MIT © Zudux-State contributors. See [LICENSE](./LICENSE).

---

<div align="center">

**Created and maintained by Pradeep Kumar Sheoran (Stack Developer)**  
**BSG Technologies** · [Official Website](https://bsgtechnologies.com) · [WhatsApp +91-8595147850](https://wa.me/918595147850)

*Meet · Learn · Contribute · Discuss new topics · Accept a coffee invitation*

</div>
