# @zwire/core

> Zero-dependency, tree-shakeable TypeScript reactive core and opt-in ESM subpaths (/tx, /collections, /protocol, /store, /optics, /resource, /devtools).

**Zero-global scoped reactive core** with **forward-only GC-safe unwatched computeds**, **rebaseable optimistic layers + STM drafts**, **incremental Top-K collections**, **open wire protocols & hydration**, **fine-grained stores & optics**, and first-party **React 19, Vue 3, Solid 2, and Svelte 5 adapters**.

Pure erasable TypeScript with zero runtime dependencies — publishes ES2023 ESM for Node.js 20+, Bun, and modern browsers, with 100% JSON wire parity with the native Rust [`zwire`](/rust/overview/) workspace.

---

## Install

```bash
npm install @zwire/core
```

For UI framework bindings, install the matching companion package alongside `@zwire/core`:

- React 18 / 19: `npm install @zwire/react`
- Vue 3.5+: `npm install @zwire/vue`
- Solid 2+: `npm install @zwire/solid`
- Svelte 5.7+: `npm install @zwire/svelte`

Each adapter mirrors the subpaths below (`@zwire/<fw>/tx`, `/collections`, `/resource`, `/protocol`) with hooks for optimistic mutations, lists, async resources and hydration. Define state once with `scoped((scope) => ...)` and read the instance for the active scope with the adapter's `useScoped()`.

---

## Tree-shakeable ESM subpaths

| Subpath | Rust Parity | Exports |
| :--- | :--- | :--- |
| `@zwire/core` | `zwire-core` | `atom`, `computed`, `effect`, `subscribe`, `batch`, `untracked`, `createScope`, `createChildScope`, `defaultScope`, `scoped`, `onWatched`, `onUnwatched` |
| `@zwire/core/tx` | `zwire-tx` | `createOptimisticLayer`, `runOptimistic`, `createDraft`, `StmConflictError` |
| `@zwire/core/collections` | `zwire-collections` | `createCollection` (2-level Chunked B-Tree + reactive `topK(k)`) |
| `@zwire/core/protocol` | `zwire-protocol` | `hydratable`, `dehydrate`, `hydrate`, `fromExternalSource`, `createSyncBridge`, `attachInspector` |
| `@zwire/core/store` | TS-only | `createObjectStore` (lazy CoW immutable snapshots), `createDeepStore` (PathTrie proxy) |
| `@zwire/core/optics` | TS-only | `createAtomMap` (`O(1)` keyed atoms w/ eviction), `focus` (type-safe subscribable `DeepPath` lens), `lens` (custom bidirectional projection) |
| `@zwire/core/resource` | TS-only | `resource` (dependency-tracked async reads, cancellation and Suspense) |
| `@zwire/core/devtools` | TS-only | `createInspectableScope` (weak node registry and graph snapshots) |

All subpaths declare `"sideEffects": false` and compose with `@zwire/core` through 5 lazy zero-cost extension slots — zero unused subpath bytes ever ship in your bundle.

---

## Quick Start

### Core Primitives (`@zwire/core`)

```ts
import { atom, batch, computed, effect } from '@zwire/core';

const count = atom(1);
const doubled = computed(() => count.get() * 2);

const stop = effect(() => {
  console.log('doubled:', doubled.get());
});

batch(() => {
  count.set(2);
  count.set((n) => n + 1);
}); // logs once: doubled: 6

stop();
```

### Rebaseable Optimistic Layers & STM Drafts (`@zwire/core/tx`)

```ts
import { atom } from '@zwire/core';
import { createDraft, createOptimisticLayer, runOptimistic } from '@zwire/core/tx';

const likes = atom(10);

const l1 = createOptimisticLayer();
l1.update(likes, (n) => n + 1); // UI: 11

const l2 = createOptimisticLayer();
l2.update(likes, (n) => n + 1); // UI: 12

// Concurrent WebSocket push updates committed base -> active intents auto-rebase!
likes.set(15); // UI: 17 (zero lost updates)

l1.revert(); // surgical rollback preserves l2 -> UI: 16
l2.settle(() => likes.set(16)); // zero-flicker atomic settle

// Async helper with AbortSignal cleanup & automatic revert on rejection
const controller = new AbortController();
await runOptimistic(
  async (tx) => {
    tx.update(likes, (n) => n + 1);
    const res = await fetch('/api/like', { method: 'POST', signal: tx.signal });
    const { total } = (await res.json()) as { total: number };
    return total;
  },
  { signal: controller.signal, settle: (total) => likes.set(total) },
);

// Detached speculative draft with STM read-set conflict verification
const draft = createDraft();
const cur = draft.get(likes);
draft.set(likes, cur + 5);
draft.commit({ verifyReads: true }); // throws StmConflictError if `likes` changed since read
```

### Scoped Hydration, External Sources, Sync Bridges & Inspector (`@zwire/core/protocol`)

```ts
import { computed, createScope } from '@zwire/core';
import {
  attachInspector,
  createSyncBridge,
  dehydrate,
  fromExternalSource,
  hydratable,
  hydrate,
} from '@zwire/core/protocol';

// Server (per-request isolated scope; watchers are no-ops)
const ssr = createScope({ mode: 'ssr' });
const serverUser = hydratable('user', { name: 'Ada' }, { scope: ssr });
const payload = dehydrate(ssr);

// Client (supports hydrate() before lazy routes register signals)
const client = createScope();
hydrate(client, payload);
const user = hydratable('user', { name: '' }, { scope: client });
user.get(); // { name: 'Ada' }

// Coalesced batch sync bridge (suppresses remote echo loops & rebases active optimistic layers)
const bridge = createSyncBridge(client, mySyncAdapter, {
  filter: (key) => !key.startsWith('local.'),
});

// Zero-cost instrumentation when detached
const stopInspector = attachInspector(client, {
  onWrite: (ev) => console.debug('write', ev.key, ev.prevValue, '->', ev.nextValue),
});
```

### Incremental Top-K Collections (`@zwire/core/collections`)

```ts
import { computed } from '@zwire/core';
import { createCollection } from '@zwire/core/collections';

const leaderboard = createCollection({
  getId: (r: { id: number; score: number; active: boolean }) => r.id,
  filter: (r) => r.active && r.score >= 700,
  compare: (a, b) => b.score - a.score,
});
const top50 = leaderboard.topK(50);
const leader = computed(() => top50.get()[0]?.id);
```

### Fine-Grained Stores & Type-Safe Optics (`@zwire/core/store`, `@zwire/core/optics`)

```ts
import { atom } from '@zwire/core';
import { createAtomMap, focus } from '@zwire/core/optics';
import { createDeepStore, createObjectStore } from '@zwire/core/store';
import { createOptimisticLayer } from '@zwire/core/tx';

// Lazy key atoms + Copy-on-Write immutable snapshots (ideal for flat forms & React)
const form = createObjectStore({ name: 'Ada', email: 'ada@example.com', count: 0 });
form.setKey('email', 'grace@example.com');
const countField = form.field('count');
createOptimisticLayer().update(countField, (n) => n + 1);

// Opt-in PathTrie proxy store for migrating deeply nested legacy state trees
const legacy = createDeepStore({ user: { profile: { theme: 'dark' } }, flags: { beta: false } });
const theme = legacy.select((s) => s.user.profile.theme);

// O(1) keyed atom map & recursive DeepPath subscribable lens
const fields = createAtomMap<string, string>(() => '');
const root = atom({ user: { profile: { name: 'Ada' } } });
const nameLens = focus(root, 'user', 'profile', 'name');
nameLens.set('Grace');
```

---

## Verified Cross-Engine Benchmarks (V8 & JSC)

Measured on Apple M1 (`darwin/arm64`) across 15 process-isolated runs against `@tanstack/store@0.11.3` ([full report](/architecture/benchmarks/)):

- **15/15 Correctness & GC Gates PASS** on both Node v26 (V8) and Bun 1.3 (JSC)
- **Single R/W:** `42.0 ns` (V8) / `28.7 ns` (JSC) — `1.15x–2.34x` faster
- **1k-field `setKey()` rotation:** `305.8 ns` (V8) / `113.9 ns` (JSC) — `549x–1,367x` faster
- **50k-row Top-K update:** `0.45 µs` (V8) / `0.21 µs` (JSC) — `4,511x–8,891x` faster
- **Optimistic Rebase cycle:** `0.32 µs` (V8) / `0.25 µs` (JSC) — `3.15M–4.03M cycles/s`
- **Heap per `atom + subscriber`:** `370 B` (V8) / `400 B` (JSC) — `2.8x–4.3x` less memory

See the [repository README](https://github.com/kjmin-dev/zwire#readme) and [API reference](https://github.com/kjmin-dev/zwire/blob/main/docs/API.md) for full documentation.

### Browser sync transports

Import factories from `@zwire/core/protocol/transports` and pass their result to `createSyncBridge(scope, adapter)`. Each network or channel adapter instance owns one active bridge subscription. Disposing the bridge closes its connection and cancels outstanding retries.

| Factory | Connection and persistence behavior |
| --- | --- |
| `createLocalStorageAdapter({ key, version, onError })` | Loads a snapshot synchronously and merges committed writes by key. |
| `createIndexedDbAdapter({ database, key, version, onError })` | Atomically merges writes in read/write transactions. Local writes during the initial read take precedence for their keys. |
| `createBroadcastChannelAdapter({ name })` | Exchanges JSON patch batches between tabs and suppresses recent transaction echoes and replays. |
| `createWebSocketAdapter({ url })` | Receives JSON text frames. A push succeeds when the socket accepts the frame. |
| `createEventSourceAdapter({ url, pushUrl })` | Receives JSON via SSE message events and POSTs batches as JSON to `pushUrl`. Success requires an HTTP 2xx response. Reconnects send the latest SSE event ID as a `lastEventId` query parameter. Configure `resumeUrl` for servers using another cursor convention. |

Both persistent adapters store an application schema version (default 1). An incompatible snapshot is preserved and reported to `onError`; use a new key or migrate the stored snapshot before reconnecting. Local storage uses a synchronous read/merge/write. IndexedDB transactions also serialize simultaneous writers from different tabs.

The network adapters keep up to `maxPending` unsent batches (256 by default) in memory and reconnect with exponential backoff from `initialDelayMs` to `maxDelayMs`. They resend in FIFO order with the original transaction IDs after connection or transient POST failures. Permanent HTTP 4xx errors (apart from 408 and 429), queue overflow, and cancellation reject the pending push and reach the bridge's `onPushError`. Reloading the page clears the in-memory queue. A `resolveConflict(local, remote)` callback can return `'local'` to ignore an inbound change to a pending key, or `'remote'` to apply it. Outbound commands already queued retain their original payload. Configure your server's own conflict and acknowledgement policy as appropriate.
