# TypeScript: Extension Subpaths

> API reference for @zwire/core/tx, @zwire/core/collections, @zwire/core/protocol, @zwire/core/store, and @zwire/core/optics.

## 2. `@zwire/core/tx`

Rebaseable overlapping optimistic layers, async `AbortSignal` transactions, and detached Software Transactional Memory (STM) drafts.

| Export | Signature | Description |
| :--- | :--- | :--- |
| `createOptimisticLayer` | `createOptimisticLayer(scope?: ReactiveScope): OptimisticLayer` | Creates a composable optimistic intent layer (`update`, `revert`, `settle`). Concurrent authoritative writes automatically rebase active layers in creation order. If an intent rejects the proposed base, both committed and effective values retain their previous snapshots. |
| `runOptimistic` | `runOptimistic<R>(scope, fn, options?): Promise<R>` / `runOptimistic<R>(fn, options?): Promise<R>` | Runs an async mutation with an `OptimisticTx` (`layer`, `signal`, `update`, `settle`, `revert`). Automatically reverts on rejection or `AbortSignal` abort, and atomically settles on resolve if `options.settle` is provided. |
| `createDraft` | `createDraft(scope?, options?): Draft` / `createDraft(options): Draft` | Creates a detached Copy-on-Write speculative draft (`base: 'committed' \| 'effective'`). Supports `get`, `set`, `run`, `commit({ verifyReads?: boolean })`, and `discard()`. |
| `StmConflictError` | `class StmConflictError extends Error` (`code: 'ERR_STM_CONFLICT'`) | Thrown by `draft.commit({ verifyReads: true })` when any read atom or store version changed since it was read in the draft. |

---

## 3. `@zwire/core/collections`

Generalized 2-level Chunked Sorted Block Index (`BLOCK_TARGET = 128`) with deterministic key tie-breaking and `O(1)` Top-K boundary pruning.

| Export | Signature | Description |
| :--- | :--- | :--- |
| `createCollection` | `createCollection<T, K = number>(options: CollectionOptions<T, K>): Collection<T, K>` | Creates an incrementally maintained filtered + sorted collection (`get`, `has`, `insert`, `insertMany`, `upsert`, `upsertMany`, `update`, `delete`, `clear`, `size`, `indexedSize`). |
| `col.topK` | `col.topK(k: number, options?: TopKOptions<T>): Computed<readonly T[]>` | Returns a first-class reactive `Computed<readonly T[]>` signal updated once per batch (`F_EXTERNAL`-aware, safe inside `computed()` and `createDraft()`). |
| `col.getTopK` / `col.subscribeTopK` | `getTopK(k, opts?)` / `subscribeTopK(k, listener, opts?)` | Imperative snapshot read and direct subscription helper. |
| `createQueryCollection` | `createQueryCollection(options): QueryCollection<T, K>` | Extends the incremental index with reactive `range(offset, limit)`, snapshot `getRange(offset, limit)`, sorted iteration, `sizeSignal`, `indexedSizeSignal`, and `O(1)` per-key `getSignal(id)` and `hasSignal(id)`. |
| `createTransactionalCollection` | `createTransactionalCollection(options): TransactionalCollection<T, K>` | Provides `get`, `size`, `range`, `getRange` and row mutations. Pass an optimistic layer as the last argument of `upsert`, `update` or `delete` to record replayable edits. Ordinary mutations inside `draft.run` stay isolated until commit. |

Queries apply the collection filter and optional per-window filter before counting the offset.
`setFilter(predicate?)` and `setCompare(compare)` on a query collection rebuild its index and refresh live queries.
`values()` and `[Symbol.iterator]()` traverse indexed rows in sorted order. Point lookups also include filtered rows.
Transactional collections copy the row map per write and rebuild their sorted index on demand. Verified drafts detect a concurrent write to any row in that collection.

---

## 4. `@zwire/core/protocol`

Open wire-compatible hydration, push/pull external source bridge, coalesced state sync bridge, and zero-cost DevTools instrumentation (100% parity with `zwire-protocol` and [`spec/protocol.md`](/protocol/specification/)).

| Export | Signature | Description |
| :--- | :--- | :--- |
| `hydratable` | `hydratable<T>(key: string, initial: T, options?): Atom<T>` / `hydratable<S>(signal: S, key: string, options?): S` | Registers a keyed signal in `scope` (`Atom`, `ObjectStore`, `DeepStore`, `focus()`) and immediately consumes any pre-buffered hydrated value for `key`. |
| `dehydrate` | `dehydrate(scope?: ReactiveScope): HydratedState` | Snapshots committed (non-optimistic) base values of all keyed signals in `scope` into a plain JSON-serializable object (`__proto__`-safe). |
| `hydrate` | `hydrate(scope: ReactiveScope, data: HydratedState): void` / `hydrate(data: HydratedState): void` | Applies hydrated values inside a single batch and buffers unregistered keys until lazy routes call `hydratable()` (delete-on-consume). |
| `fromExternalSource` | `fromExternalSource<TView>(source: ExternalSource<TView>, optionsOrScope?): Computed<TView>` | Bridges any push/pull external store (`{ getSnapshot(), subscribe(onUpdate) }`) into a reactive `Computed<TView>`. |
| `createSyncBridge` | `createSyncBridge(scope, adapter, options?): SyncBridgeHandle` / `createSyncBridge(adapter, options?): SyncBridgeHandle` | Coalesces local committed writes per batch into `StatePatch[]` pushed to `adapter.push`, suppresses remote echo loops, applies remote patches (rebasing active optimistic layers), and buffers unregistered keys. |
| `attachInspector` | `attachInspector(scope, inspector: InspectorHook): Unsubscribe` / `attachInspector(inspector): Unsubscribe` | Attaches zero-cost-when-detached tracing callbacks (`onWrite`, `onCompute`, `onFlush`, `onError`). Multiple inspectors compose safely via an internal hub. `onStoreWrite` filters committed store changes. `onOptimisticLayer` reports a scope-local layer ID and its create, update, settle, revert or error phase. |

### Browser transports & WASM bridge

`@zwire/core/protocol/transports` exports `createLocalStorageAdapter`, `createIndexedDbAdapter`, `createBroadcastChannelAdapter`, `createWebSocketAdapter`, and `createEventSourceAdapter`. Pass a configured adapter to `createSyncBridge`. Both network transports provide bounded offline queues, exponential reconnection backoff, and a pending-key conflict hook. The bridge drops recent local echoes and duplicate peer transactions and releases subscriptions on disposal. [Transport options and delivery semantics](/typescript/core/#browser-sync-transports)

`@zwire/core/protocol/wasm` exports `connectWasm(scope, peer)` to connect a TypeScript `ReactiveScope` to a Rust `WireScope` generated by `zwire-wasm` (`bridges/wasm`). [WASM bridge guide](/rust/wasm-bridge/)

---

## 5. `@zwire/core/store`

TypeScript-specific fine-grained object and legacy deep-tree stores (tree-shakeable: importing `createObjectStore` never pulls in `createDeepStore`).

| Export | Signature | Description |
| :--- | :--- | :--- |
| `createObjectStore` | `createObjectStore<T extends Record<string, any>>(initial: T, scope?): ObjectStore<T>` / `createObjectStore(scope, initial): ObjectStore<T>` | Flat lazy-key store with `O(1)` swap-remove pruning and Lazy Copy-on-Write immutable snapshots for React `useSyncExternalStore`. Implements `Atom<T>` plus `setKey`, `deleteKey`, `field(key)` (composable with `OptimisticLayer`/`Draft`), and `subscribeField`. |
| `createDeepStore` | `createDeepStore<T extends Record<string, any>>(initial: T, scope?): DeepStore<T>` / `createDeepStore(scope, initial): DeepStore<T>` | Opt-in deep auto-tracking `PathTrie` proxy store with lazy Copy-on-Write (`_sh`) for migrating deeply nested legacy state trees. Implements `Atom<T>` plus `setKey`, `deleteKey`, `select`, and `subscribeField`. |
| `createSelector` | `createSelector<T>(source: ReadableSignal<T>, scope?): (key: T) => ReadableSignal<boolean>` / `createSelector(scope, source)` | `O(1)` incremental key-equality selector (Solid 2.0 pattern): notifies only the previously matched and newly matched keys on `source` changes, pruning unwatched keys automatically. |
| `createProjection` | `createProjection<T extends Record<string, any>>(fn: (draft: T) => void, initial: T, scope?): ReadableSignal<T> & FieldSubscribable<T>` | Solid 2.0 mutable-draft incremental derived store: runs `fn(draft)` over lazy per-key atoms and notifies only mutated keys in `O(changed)`. |
| `reconcile` | `reconcile<T extends Record<string, any>>(target: ObjectStore<T>, next: T, options?: ReconcileOptions): void` | Applies a minimal diff from an incoming snapshot/payload onto an `ObjectStore`, preserving unchanged nested references and reconciling arrays by `{ key }`. |

---

## 6. `@zwire/core/optics`

`lens(root, { get, set })` returns a subscribable writable projection. Supply pure `get(source)` and `set(source, value)` functions. The setter returns the new source. Lenses compose and preserve the root identity used by drafts, hydration and sync bridges. Optimistic layers reapply updates to the latest underlying atom value.

```ts
const fahrenheit = lens(celsius, {
  get: (value) => value * 9 / 5 + 32,
  set: (_value, next: number) => (next - 32) * 5 / 9,
});
```

TypeScript-specific fine-grained keyed atom maps and type-safe subscribable lenses.

| Export | Signature | Description |
| :--- | :--- | :--- |
| `createAtomMap` | `createAtomMap<K, V>(createInitial, options?): AtomMap<K, V>` / `createAtomMap<K, V>(scope, createInitial, options?): AtomMap<K, V>` | `O(1)` lazy keyed atom collection (`get`, `peek`, `has`, `set`, `delete`, `clear`, `keys`, `size`) with automatic unwatched-key eviction (`eviction: 'unchanged' \| 'unwatched' \| 'none'`, `ttl`, `maxEntries` LRU eviction). |
| `focus` | `focus<T extends object, const P extends DeepPath<T>>(root: WritableSignal<T>, ...path: P): Atom<DeepValue<T, P>>` | Recursive type-safe subscribable lens composable with `OptimisticLayer`, `Draft`, and `SyncBridge`. Handles arrays via immutable `Array.prototype.with`, null-prototype objects, and `__proto__` keys safely. |

---
