npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@kyneta/exchange

v5.0.0

Published

Substrate-agnostic state exchange — sync for any @kyneta/schema substrate

Readme

@kyneta/exchange

Define your data's shape. Get sync, persistence, and presence — across any number of peers, over any transport, with any CRDT or none.

import { Exchange, whenSettled } from "@kyneta/exchange"
import { loro } from "@kyneta/loro-schema"
import { batch, Schema } from "@kyneta/schema"
import { createWebsocketClient } from "@kyneta/websocket-transport/browser"

const TodoDoc = loro.bind(
  Schema.struct({
    title: Schema.text(),
    items: Schema.list(
      Schema.struct.json({
        text: Schema.string(),
        done: Schema.boolean(),
      }),
    ),
  }),
)

const exchange = new Exchange({
  principal: "alice",
  transports: [
    createWebsocketClient({ url: "ws://localhost:3000/ws", WebSocket }),
  ],
})

const doc = exchange.get("my-todos", TodoDoc)

batch(doc, d => {
  d.title.insert(0, "My Todos")
  d.items.push({ text: "Learn Exchange", done: false })
})

doc.title() // "My Todos"

await whenSettled(doc) // ✓ every truth source has reported

That's a collaborative CRDT document, syncing over WebSocket, with full TypeScript types. Every connected peer running this code converges automatically — concurrent edits merge, no data-level conflicts, no manual resolution.

The same schema works with Loro CRDTs, Yjs CRDTs, plain JS objects, or ephemeral presence state — in the same exchange, over the same connections.

314 tests · 4 transport protocols · WebSocket, SSE, WebRTC, Unix socket


The Same App, Three Perspectives

The exchange's key insight is that different participants in a sync network need different levels of involvement with the same data. A client reads and writes. A relay forwards without understanding. A server reads selectively.

One protocol handles all three. The difference is a single line of configuration.

The Client — full interpretation. Typed reads, writes, changefeed, the works.

const exchange = new Exchange({
  principal: "alice",
  transports: [createWebsocketClient({ url: "ws://localhost:3000/ws", WebSocket })],
})

const doc = exchange.get("shared-doc", TodoDoc)
doc.title()  // typed read
batch(doc, d => d.title.insert(0, "Hello"))  // typed write
subscribe(doc, changeset => { /* reactive */ })

The Relay — headless replication. No schemas, no application types. Just "hold state and forward it."

import { loro } from "@kyneta/loro-schema"

const relay = new Exchange({
  principal: "relay",
  type: "service",
  transports: [
    createWebsocketClient({ url: "ws://upstream:3000/ws", WebSocket }),
    createWebsocketClient({ url: "ws://downstream:3001/ws", WebSocket }),
  ],
  replicas: [loro.replica()],
  resolve: () => Replicate(),
})

Plain and ephemeral replicas are built-in — replicas is only needed when relaying CRDT documents (Loro, Yjs).

The Application Server — selective interpretation. Understand some documents, ignore others.

const server = new Exchange({
  principal: "game-server",
  transports: [serverTransport],
  resolve: (docId, peer) => {
    if (docId.startsWith("input:")) return Interpret(PlayerInputDoc)
    return Reject()
  },
})

These three peers join the same network. The exchange negotiates the right sync behavior for each — the client gets full CRDT merge, the relay gets opaque binary forwarding, the server gets typed access to just the documents it cares about.


Growing Without Rewriting

Most distributed state systems unintentionally punish exploration. A common story:

  • You start with plain JSON messages over WebSocket.
  • Then you need durable delivery, offline support, and need to rewrite for persistence.
  • Then you need multi-device or multi-player, and conflict resolution, and need to rewrite for CRDTs.
  • Then you need a more complex topology for production, perhaps with relay nodes or fan-out, and you need to backtrack to duplicate your types on the server.
  • Then you need presence, so it's natural to bolt on a second protocol.

But every step invalidates the previous work done, in order to accommodate the new problem space you're exploring.

The exchange is designed so that each capability is additive. You engage the next level when you need it, without rewriting what came before.

Without an exchange — @kyneta/schema on its own

import { createDoc, Schema } from "@kyneta/schema/basic"

const doc = createDoc(Schema.struct({ theme: Schema.string() }))
doc.theme.set("dark")
doc.theme()  // "dark"

The /basic entry is the batteries-included one: its createDoc(schema) binds the schema to the plain substrate for you. Everywhere else in this README the binding is explicit — json.bind(schema), loro.bind(schema) — because once an exchange is involved, which substrate you picked is the whole point.

When you need that document to sync across peers, the exchange wraps the same schema. Your reads and writes don't change.

Two peers, one writer — the simplest distributed case

const ConfigDoc = json.bind(Schema.struct({ theme: Schema.string() }))

// Peer A — creates the document and writes
const exchangeA = new Exchange({
  principal: "alice",
  transports: [createWebsocketClient({ url: "ws://localhost:3000/ws", WebSocket })],
})
const docA = exchangeA.get("config", ConfigDoc)
docA.theme.set("dark")

// Peer B — opens the same document and waits for data to arrive
const exchangeB = new Exchange({
  principal: "bob",
  transports: [createWebsocketClient({ url: "ws://localhost:3000/ws", WebSocket })],
})
const docB = exchangeB.get("config", ConfigDoc)
await whenSettled(docB)
docB.theme()  // "dark"

Switch to multi-writer — change the bind, not the reads/writes

// Before: plain JS with sequential sync
const ConfigDoc = json.bind(Schema.struct({ theme: Schema.string() }))

// After: Loro CRDT with concurrent merge — concurrent edits converge
const ConfigDoc = loro.bind(Schema.struct({ theme: Schema.string() }))

// Everything else is unchanged:
const doc = exchange.get("config", ConfigDoc)
doc.theme.set("dark")
doc.theme()  // same API, now backed by a CRDT

Add persistence — one line

const exchange = new Exchange({
  principal: "server",
  transports: [serverTransport],
  store: await createLevelDBStore("./data/exchange-db"),  // ← new
})
// Durable documents auto-hydrate on restart, auto-persist on mutation.
// Ephemeral ones deliberately do neither — see Storage, below.

Add presence alongside your documents — same exchange

const PresenceDoc = ephemeral.bind(Schema.struct({
  cursor: Schema.struct({
    x: Schema.number(),
    y: Schema.number()
  }),
  name: Schema.string(),
}))

// Same exchange, same transport connections, different sync mode
const doc = exchange.get("shared-doc", TodoDoc)          // Loro CRDT, concurrent merge
const presence = exchange.get("my-presence", PresenceDoc) // ephemeral broadcast

Add access control — one predicate

const exchange = new Exchange({
  principal: "server",
  transports: [serverTransport],
  canShare: (docId, peer) => {  // ← new: outbound flow control
    if (docId.startsWith("input:")) return peer.peerId === docId.slice(6)
    return undefined
  },
  canWrite: (docId, peer) => {  // ← new: who may write; clients register it too
    if (docId === "game-state") return peer.principal === "server"
    return undefined
  },
})

Add a relay — no client changes

// The relay has zero knowledge of your schemas.
// Plain and ephemeral replicas are built-in; add CRDT replicas if relaying Loro/Yjs docs.
const relay = new Exchange({
  principal: "relay",
  type: "service",
  transports: [
    createWebsocketClient({ url: "ws://upstream:3000/ws", WebSocket }),
    createWebsocketClient({ url: "ws://downstream:3001/ws", WebSocket }),
  ],
  replicas: [loro.replica()],
  resolve: () => Replicate(),
})

Each step is one or two lines that don't invalidate the previous step. Your reads, writes, subscriptions, and tests survive every transition.


Why This Works

One declaration, three decisions

A BoundSchema captures the three choices that define a document type:

  1. Schema — what shape is the data?
  2. Factory — how is the data stored and versioned?
  3. SyncMode — how does the exchange sync it?
import { Schema, json, ephemeral } from "@kyneta/schema"
import { loro } from "@kyneta/loro-schema"
import { yjs } from "@kyneta/yjs-schema"

// Collaborative document — Loro CRDT with concurrent merge
const TodoDoc = loro.bind(Schema.struct({
  title: Schema.text(),
  items: Schema.list(Schema.struct.json({ name: Schema.string() })),
}))

// Collaborative text — Yjs CRDT with concurrent merge
const NoteDoc = yjs.bind(Schema.struct({
  body: Schema.text(),
}))

// Config data — plain substrate with sequential sync
const ConfigDoc = json.bind(Schema.struct({ theme: Schema.string() }))

// Ephemeral presence — deltas, merged per field on each leaf's timestamp
const PresenceDoc = ephemeral.bind(Schema.struct({
  cursor: Schema.struct({ x: Schema.number(), y: Schema.number() }),
  name: Schema.string(),
}))

BoundSchemas are static declarations, defined at module scope. They can be shared across multiple exchange instances — each exchange calls the factory builder independently, producing a fresh factory with the correct peer identity.

For custom substrates, use bind() directly as the general primitive, and createBindingTarget to build custom binding target objects:

import { bind, createBindingTarget, SYNC_COLLABORATIVE } from "@kyneta/schema"

// bind() is the general primitive — explicit schema, factory builder, syncMode
const CustomDoc = bind({
  schema: Schema.struct({ data: Schema.string() }),
  factory: (ctx) => createMyFactory(ctx.peerId),
  syncMode: SYNC_COLLABORATIVE,
})

// createBindingTarget builds a binding target like json/ephemeral/loro/yjs
const mySubstrate = createBindingTarget({
  factory: (ctx) => createMyFactory(ctx.peerId),
  replicaFactory: myReplicaFactory,
  syncMode: {
    writerModel: "concurrent",
    durability: "persistent",
  }
})

const AnotherDoc = mySubstrate.bind(Schema.struct({ data: Schema.string() }))
const replica = mySubstrate.replica()

Three sync modes, one wire format

Each BoundSchema carries a SyncMode — a structured record with two orthogonal axes (writerModel, durability) — that determines how the exchange syncs documents of that type. These are genuinely different sync algorithms, not transport optimizations:

| SyncMode constant | Axes | Protocol | Version Order | Use Case | |-----------------------|------|----------|---------------|----------| | SYNC_COLLABORATIVE | concurrent + persistent | Bidirectional exchange | Partial (concurrent possible) | Loro / Yjs CRDTs | | SYNC_AUTHORITATIVE | serialized + persistent | Request/response | Total (no concurrency) | Plain substrates | | SYNC_EPHEMERAL | concurrent + transient | Bidirectional exchange | Unordered (digest decides equality) | Ephemeral/presence |

All three run over the same seven-message sync protocol:

  • present — "I have these documents." Carries docId, replicaType, syncMode, and schemaHash so the receiver can validate compatibility before any data exchange.
  • interest — "I want document X. Here's my version." Carries reciprocate for collaborative bidirectional exchange.
  • offer — "Here is state for document X." Carries an opaque SubstratePayload — the exchange never inspects the bytes.
  • accept — "I now hold your version of document X." Lets a writer compact its history down to what every reader holds.
  • refuse — "I will not take your operations on document X." Answers an offer the receiver's policy vetoes; see When a peer refuses your writes.
  • dismiss — "I'm leaving document X."
  • vacant — "You asked for document X, and I won't serve it."

Two lifecycle messages (establish, depart) handle the channel handshake and departure. The sync mode's field values determine when and how these messages are sent, not their shape. Peers must speak the same protocol major; this release is protocol 2.1, a 1.x peer is reported as a protocol-mismatch diagnostic, and a 2.0 peer as a protocol-skew warning (it drops refuse, and is not told its offers are refused).

The exchange never inspects your data

This is the architectural decision that makes substrate agnosticism real. The exchange dispatches on SyncMode fields (writerModel, durability) to decide protocol behavior, but actual document payloads are opaque SubstratePayload values. The exchange moves bytes; the substrate interprets them. This means:

  • A Loro document, a Yjs document, a plain JS object, and an ephemeral value all flow through the same protocol.
  • A relay can forward documents without knowing what CRDT library produced them.
  • You can implement a new substrate by satisfying the Substrate<V> interface — no exchange changes needed.

Four dispositions

When a peer announces a document, your exchange decides how to participate:

| Disposition | What happens | Created by | |-------------|-------------|------------| | Interpret | Full schema-driven interpretation — Ref<S>, changefeed, reads, writes | exchange.get(docId, bound) | | Replicate | Headless replication — version tracking, export/import, no schema | exchange.replicate(docId) or resolve: () => Replicate() | | Defer | Track for routing but don't replicate yet — promotable later | resolve: () => Defer() | | Reject | Refuse to track the document at all | resolve: () => Reject() |

The two-tiered default (when no resolve callback matches): documents whose replica type is supported get deferred (promotable via a later exchange.get() or registerSchema()), while documents with unsupported replica types are silently rejected.


Core Concepts

The Exchange

The Exchange class is the central orchestrator. It manages document lifecycle, coordinates transports and a store, and runs sync algorithms on behalf of passive substrates.

const exchange = new Exchange({
  principal: "alice",
  type: "user",
  transports: [networkTransport],
  store: createInMemoryStore(),
  canShare: (docId, peer) => {
    if (docId.startsWith("input:")) return peer.peerId === docId.slice(6)
    return undefined
  },
  canAccept: (docId, peer) => {
    if (docId === "game-state") return false
    return undefined
  },
})

exchange.get(docId, bound) gives a document, creating it if this exchange has never seen it. exchange.open(docId, bound) gives it only if this exchange holds it (open, or in its store), and resolves undefined otherwise: it never creates one.

Peer identity: you name a principal, who this exchange speaks for: a user, a service. Several exchanges may share one. The exchange issues its own peerId, its seat, which is the address its operations are written under. A store makes the seat stable across restarts: the store issues it, and a reload over the same storage gets it back, while two tabs or processes open at once hold different seats. Without a store, each session is a new peer. Key policies on principal when you mean who, and on peerId when you mean which replica. Input documents above are keyed by seat, one per tab.

Done with a document: suspend, unload, destroy

| | leaves the sync graph | leaves memory | leaves the store | comes back with | |---|---|---|---|---| | exchange.suspend(docId) | yes | no | no | resume(docId) | | exchange.unload(docId) | yes | yes | no | get or open | | exchange.destroy(docId) | yes | yes | yes | — (a get creates a new one) |

unload is for a document you will want again, such as a card the user closed: it releases the document's memory and keeps it stored, and opening it loads it back, with every write you made, in the tier it had and suspended if it was. It needs a store, and throws for a transient (ephemeral) document, which no store would hold.

const card = exchange.get("card-7", MyDoc)
batch(card, d => d.title.insert(0, "Groceries"))

exchange.unload("card-7")       // its memory goes once the store holds it
// …later
const again = await exchange.open("card-7", MyDoc)  // loads it from the store
  • Peers receive every write made before the unload. The document stays in memory, still sending what peers are owed, until the store holds all of it; it takes nothing new in meanwhile.
  • A ref held across the unload reads its last value. Its writes throw DocumentClosedError (reason "unloaded") from the moment you call unload, and writeRefusal(doc) returns that error.
  • Opening it while it unloads cancels the unload if the store does not yet hold everything, and returns the same ref, writable again. After that, it loads the document again as a new ref.
  • While unloaded, exchange.documents shows it as { mode: "unloaded" } and exchange.has is true; peers are not told of it, and an index built with @kyneta/index drops its rows until it is opened. On a server (authority: "self"), a client asking for an unloaded document loads it again, and the first such request logs an unloaded-doc-reloaded warning: a server unloading a document still in use pays a load for it.

destroy releases memory the same way: its native document (a LoroDoc, a Y.Doc) is freed, and once you let go of its refs, they are collected too. A ref you still hold reads the document's last value, but its writes, unwrap, and the sync functions throw DocumentClosedError, and writeRefusal(doc) returns that error. reset() and shutdown() close every document the same way.

Heterogeneous Documents

A single exchange hosts documents backed by different substrate types simultaneously:

const doc = exchange.get("collab-doc", TodoDoc)       // Loro CRDT, concurrent merge
const config = exchange.get("settings", ConfigDoc)     // Plain JSON, sequential sync
const presence = exchange.get("presence", PresenceDoc) // ephemeral broadcast

Each document's substrate and sync mode are determined by its BoundSchema. No configuration needed at the exchange level.

Governance Predicates

Five predicates control information flow. All use three-valued logic (true / false / undefined) for composable policy stacking — false short-circuits, undefined defers to other policies, and the default when all policies abstain is true.

  • canShare(docId, peer) → boolean | undefined — Outbound. Gates all four ways a document can reach a peer: the present that announces it, the push on a local change, the relay of an imported change, and the offer answering a peer that asks for it by id. A denied request is answered vacant — "I will not serve you this" — which is deliberately the same reply the peer would get for a document that does not exist, so a denial reveals nothing about which ids are real. Also gates resolve: if canShare returns false for the announcing peer, the callback never fires.

  • canAccept(docId, peer) → boolean | undefined — Inbound. Gates offer imports. A rejected offer is not imported, and its sender is told with refuse: it stops sending you that document, and if you are its authority, it stops writing it (When a peer refuses your writes). Its operations stay with it, so to keep a peer from writing a document at all, use canWrite.

  • canWrite(docId, peer) → boolean | undefined — Authorship. May peer author operations in this document? Judged twice: against this exchange's own identity for every local write, which throws NotAWriterError when rejected, and against the sender of every offer, which is dropped as a canAccept veto is. See A document only one peer writes.

  • canReset(docId, peer) → boolean | undefined — Epoch boundary. Fires when a peer sends an entirety payload for a document that already has local state — meaning the remote peer has compacted history past our known version. Accepting discards local state and adopts the entirety; rejecting keeps local state and diverges from compacted peers.

  • canConnect(peer) → boolean | undefined — Connection. Gates the establish handshake. When rejected, the peer's channel is dropped and its connection closed: no documents are exchanged, and a server never sends a refused peer its own establish. A refused client backs off and retries toward its maxAttempts. Unlike the other predicates, this takes only a peer (no docId).

When a policy changes

Registering a policy, disposing of one, or replacing a named one takes effect for peers that are already connected, not only for what happens next:

  • canShare granted: the peer is sent the documents it may now see. Revoked: it is told the document is gone (dismiss), and is sent nothing more of it. It keeps what it already received.
  • canAccept or canWrite loosened: a writer you refused is told it may write again, its lock lifts, and its refused writes arrive.
  • canConnect revoked: the peer is disconnected.
  • resolve: documents you deferred are classified again. A Reject stays rejected.

A predicate that reads state of your own, such as a membership list, must say when that state changes, since the exchange cannot see inside it. Give the policy a subscribe:

const members = new Set<string>(["alice"])
const listeners = new Set<() => void>()

exchange.register({
  canShare: (docId, peer) =>
    docId === "room" ? members.has(peer.principal) : undefined,
  subscribe: onChange => {
    listeners.add(onChange)
    return () => listeners.delete(onChange)
  },
})

function addMember(principal: string) {
  members.add(principal)
  for (const notify of listeners) notify()
}

A change re-checks only what the changed policy's gates decide: a policy with only canAccept never re-checks who may see what. A canShare change re-checks each connected peer against each document, so keep subscribe to real changes.

Return undefined for documents your policy does not govern. This is what the three-valued logic is for, and with canShare it now matters in practice: a false blocks every path for that document, including a direct request. Features that own documents of their own — Line, most visibly, which fetches the remote peer's outbox by id — depend on unrelated policies abstaining rather than vetoing. Both examples above follow this pattern: each governs one id prefix and returns undefined for the rest.

A document only one peer writes

Some documents have one writer by design: a host keeps the authoritative layout, and clients change it by asking the host. Say so once, with one predicate, and register it unchanged on every peer:

import type { PeerIdentityDetails } from "@kyneta/exchange"

const isHost = (p: PeerIdentityDetails) => p.principal === "host"
exchange.register({
  canWrite: (docId, p) => (docId === "places" ? isHost(p) : undefined),
})
  • Every peer evaluates it the same way, because it is keyed by principal, which each peer announces, rather than by "self". On the host it permits the host's own writes; on a client it rejects the client's own writes, and on every peer it rejects an offer of "places" from anyone but the host.
  • On a client, "places" is read-only. Every write to it throws NotAWriterError before anything is applied, so no operation exists for the host to drop. writeRefusal(doc) returns the same error, writeRefusalFeed(doc) notifies when a policy change flips it, and @kyneta/react's useText keeps its fields read-only. The client still receives every write the host makes.
  • A client changes it by asking the host, for example over a Line, and the host writes.
  • A refused write cannot spread. Even a client that bypasses its own gate is refused by the host and by every other client, since each judges an offer's sender by the same predicate.
  • The rule is read when it is needed, at each write and each offer, so a policy registered or disposed later takes effect at once (When a policy changes).
  • The host must pass its own predicate. A host whose principal the predicate rejects is read-only too, and finds out at its first write.

A read-only document hands out no native handle: unwrap throws NotAWriterError too (see Escape Hatches). Render a read-only view through Kyneta refs (useText and its siblings), not through a native editor binding in read-only mode.

When a peer refuses your writes

Where canWrite is not declared on both sides (the host vetoes with canAccept alone, the two run different policy builds, or a client bypasses its gate), a write can still reach a peer that will not take it. That peer answers with refuse, and the writer:

  • reports an offer-refused diagnostic (a warning, on the console and the observation bus) naming the peer and the document;
  • sends that peer no more of the document's content until the peer reconnects or its policy changes to accept the writer;
  • if that peer is the document's authority (by Policy.authority: a predicate that matches it, or "any"; never under "self"), goes read-only: every write throws OfferRefusedError, which writeRefusal(doc) returns and useText honours.

The lock follows the authority's current refusal. It survives a disconnection until the authority departs (departureTimeout); a reconnect clears it until the authority refuses again, at the reconnect's first offer; a policy change on the authority that accepts the writer lifts it and takes the refused writes in; and a policy change on the writer that makes the refusing peer no longer the authority lifts it.

A refused writer is forked from its authority: its document, and its store, hold operations the authority does not take, and the authority's later writes may not reach it. It rejoins when the authority's policy changes to accept it. Otherwise, to rejoin, destroy the document locally and get it again, which loads the authority's state. An unload does not recover: loading again brings the refused operations back from the store, and the next offer is refused again. Nothing rejoins automatically, because discarding local operations is your application's decision.

Dynamic Document Creation

resolve fires when a peer announces a document your exchange doesn't know about. Return a disposition:

import { Interpret, Replicate, Defer, Reject } from "@kyneta/schema"

const gameExchange = new Exchange({
  principal: "game-server",
  transports: [serverTransport],
  resolve: (docId, peer, replicaType, syncMode, schemaHash) => {
    if (docId.startsWith("input:")) return Interpret(PlayerInputDoc)
    if (docId.startsWith("ephemeral:")) return Defer()
    return Reject()
  },
})

The callback receives the full metadata from the peer's present message — so the receiver can make an informed decision without compile-time schema knowledge.

schemas enables auto-resolve without a callback. Register schemas upfront and the exchange auto-interprets matching documents:

const exchange = new Exchange({
  principal: "alice",
  schemas: [TodoDoc, ConfigDoc],  // auto-interpret when peers announce these
})

onDocCreated fires for every document creation — local get(), remote auto-resolve, resolve, or deferred promotion:

const exchange = new Exchange({
  principal: "server",
  schemas: [PlayerInputDoc],
})

// `documents` is a reactive collection, so registration is a subscription
// rather than a constructor callback — the same channel reports suspension,
// promotion and removal.
exchange.documents.subscribe(changeset => {
  for (const change of changeset.changes) {
    if (change.type !== "doc-created") continue
    if (!change.docId.startsWith("input:")) continue
    registerPlayer(change.docId.slice("input:".length))
  }
})

Use resolve to decide what to do. Use onDocCreated to observe what happened.

Storage

A store is a constructor parameter, separate from transports. Durable documents auto-persist on mutation and auto-hydrate on restart:

import { createLevelDBStore } from "@kyneta/leveldb-store"

const exchange = new Exchange({
  principal: "server",
  store: await createLevelDBStore("./data/exchange-db"),
  transports: [networkTransport],
})

const doc = exchange.get("my-doc", TodoDoc)
// Mutations are automatically persisted. On restart, documents hydrate from storage.

With a store, a local write reaches peers once it is stored. The exchange holds a document's offers back while the store has not confirmed its own writes, so a crash can never leave peers holding writes this peer's next session does not know it made. That costs one store write of latency. persisted(doc) and await whenPersisted(doc) tell you when a document's writes are confirmed, and persistenceError(doc) why not. A failed store write is retried on its own, 250 ms after the failure and doubling to 30 s. Without a store, writes are sent at once.

If another writer takes this exchange's seat, its store rejects every write with SeatLostError: onStoreError fires once, and persistenceError(doc) reports it for every stored document, including ones opened afterwards. Nothing more is written or sent. It happens when a browser released a page's Web Lock while the page was still running, or a Postgres server ended the store's connection. Recover by opening a new store: in a browser, reload.

A json document has one writer. If two peers author one (or a writer restarts without its store and writes before it has synced), each mints its own lineage. When the lineages meet, every peer converges on the one minted later, the other's writes are gone, and both sides report a lineage-collision diagnostic (an error, on the console and the observation bus).

Write to a stored plain document after it has loaded. A json.bind document with a store refuses writes until loading completes, and throws DocumentLoadingError if you try: its history is a sequence, and a write made before that history is known would be overwritten by it. await whenHydrated(doc) (storage only) or await whenSettled(doc) (storage and the authority) first, or seed defaults with initialize. Loro and Yjs documents accept writes while loading and merge them.

Ephemeral documents are never stored. Anything bound through ephemeral declares durability: "transient", and the exchange keeps it out of the store in both directions — no hydrate on open, no write on mutation, no delete on destroy. That is the point of the tier: presence, cursors and live input describe who is here now, and a restarted server resurrecting yesterday's cursor positions would be worse than having none. Configuring a store does not change this, and there is no way to opt a transient document into persistence — use a durable binding target instead.

Several instances may open one storage — tabs over one IndexedDB database, processes over one Postgres schema. Their writes interleave safely, and a compaction by one never deletes what another wrote without having read it.

Two tabs of one app over one store can both read a json document, but only one of them writes it. The store records the seat whose write first carried its own changes, and refuses every other seat's: a tab that loads a document another tab writes throws on its first write, and writeRefusal(doc) says why (writeRefusalFeed(doc) to disable editing; @kyneta/react's useText keeps its field read-only by itself, and useWriteRefusal serves other editors). If two tabs wrote before either had claimed it, the loser's write is rolled back before anything of it is sent. The writer tab keeps its seat across reloads, so it stays the writer; a reader stays a reader for its session. Loro and Yjs documents are unaffected: every tab writes them. Prisma stores record nothing, so route a json document's writes to one process there.

Store format gate. On open, every persistent backend stamps a { major, minor } on-disk format version into a dedicated store-metadata namespace (a kyneta_store_meta table, an IndexedDB store_meta object store, or a store-meta\x00 key prefix — separate from the per-document doc_meta namespace). On a later open it refuses — throwing StoreFormatVersionError — a store whose stamped major is incompatible with the running build, or an unversioned store that already holds documents. The gate is a compatibility check only; it performs no automatic migration. Separately, a document whose stored records were written in a replica format the running build cannot read (a different replicaType major) fails to load: whenHydrated rejects rather than presenting an empty document.

For testing, use createInMemoryStore() with shared state to simulate persist → restart → hydrate flows. createInMemoryStoreData() builds the shared storage, and recordsOf(sharedData, docId) reads what it holds:

const sharedData = createInMemoryStoreData()

const exchange1 = new Exchange({
  principal: "server",
  store: createInMemoryStore({ sharedData }),
})
const doc = exchange1.get("my-doc", TodoDoc)
await whenHydrated(doc) // a stored plain document refuses writes until it has loaded
doc.title.set("Saved")
await exchange1.shutdown()

const exchange2 = new Exchange({
  principal: "server",
  store: createInMemoryStore({ sharedData }),
  resolve: () => Interpret(TodoDoc),
})
// "my-doc" is restored from storage automatically

Sync Status

import { sync } from "@kyneta/exchange"

const doc = exchange.get("doc-id", MyDoc)

sync(doc).peerId        // your seat
sync(doc).docId         // document ID
sync(doc).peerStates    // raw per-peer sync state (volatile)
sync(doc).ready         // monotonic readiness latch (the 90% gate)
sync(doc).connectivity  // "online" | "connecting" | "offline"

await whenSettled(doc)

// Stop waiting for the authority after 3s and carry on with local evidence.
// Resolves { via: "peer" | "local" | "offline" } — "offline" means we gave up.
await whenSettled(doc, { offlineAfter: 3000 })

sync(doc).onPeerSyncChange(states => {
  console.log("Per-peer sync state:", states)
})

Peer Lifecycle

exchange.peers is a reactive feed of the peers this exchange is connected to — callable as a function, subscribable for changes:

const peers = exchange.peers()  // ReadonlyMap<PeerId, PeerIdentityDetails>

exchange.peers.subscribe(changeset => {
  for (const change of changeset.changes) {
    switch (change.type) {
      case "peer-established":  // first channel completed the handshake
        console.log(`${change.peer.principal} connected`)
        break
      case "peer-disconnected": // all channels lost — may still reconnect
        console.log(`${change.peer.principal} dropped`)
        break
      case "peer-reconnected":  // re-established before the departure timer
        console.log(`${change.peer.principal} reconnected`)
        break
      case "peer-departed":     // definitively gone
        console.log(`${change.peer.principal} left`)
        break
    }
  }
})

Connection is not presence. Losing the last channel to a peer does not remove it immediately. The peer first goes peer-disconnected and is held for departureTimeout (default 30_000 ms); reconnect within that window yields peer-reconnected, otherwise the timer expires into peer-departed. A graceful shutdown() — or a received depart message, or departureTimeout: 0 — skips the grace period and departs at once. Set a short departureTimeout when dropped peers should disappear quickly (e.g. a live game roster); keep the default so brief network blips don't churn presence.

Multi-transport deduplication: when a peer is connected through multiple transports (e.g. both WebSocket and SSE), peer-established fires once on the first channel, and the disconnect/departure transitions fire only when all channels are gone. On shutdown() or reset(), synthetic peer-departed events are emitted for all connected peers.

Reliable messaging — Line

A Line is a reliable, ordered message stream between two peers, built from two json documents, one outbox per direction. It is addressed by the remote peer's seat, never its principal: each outbox has one writer, and a user's two tabs are two seats writing two outboxes. Find a seat by principal with whenPeer.

import { Line, whenPeer } from "@kyneta/exchange"

const Chat = Line.protocol({
  topic: "chat",
  schema: Schema.struct({ text: Schema.string() }),
})

// Client: find the server's seat, then address the Line by it.
const server = await whenPeer(exchange, p => p.principal === "server")
const sender = Chat.sender(exchange, server.peerId)
sender.send({ text: "hello" })

// Server: accept a Line from every client that opens one.
Chat.listen(exchange).onReceive((reply, receiver) => {
  void (async () => {
    for await (const msg of receiver) reply.send({ text: `echo: ${msg.text}` })
  })()
})
  • A Line to a stored server survives its restart. The server returns with the same seat and resumes from its store, and the client's Line carries on, with nothing lost or delivered twice. A server without a store (or with Prisma, whose every open is a new seat) is a new seat after a restart: clients find it with whenPeer and open new Lines, and anything in flight to the old seat is lost.
  • Line documents to a seat that never returns stay stored on its peer, and every store-less session is a new seat. Nothing removes them yet.

Undo

createUndoStack undoes this peer's own writes, as they now stand among everyone's: text a collaborator typed inside yours survives your undo, and a value someone changed since is left alone. One step is one gesture, across as many documents as it wrote.

import { createUndoStack } from "@kyneta/exchange"

const stack = await createUndoStack({
  exchange,
  docId: `undo:${tabId}`,             // the document the stack lives in
  key: "cards",                       // which stack in it
  scope: docId => docId.startsWith("card:") || docId === "places",
})

stack.gesture(() => {
  card.text.insert(0, "hello")        // one step, over two documents
  places.place.set("column")
})
await stack.undo()                    // both undone: { kind: "undone", step, stale, dropped }
await stack.redo()

An undo says what it did. { kind: "undone", step } names the step, stale its parts that did not stand whole (a peer changed them since, and they were undone as far as they stood), and dropped the steps nothing of which stood, removed on the way to it. { kind: "none", dropped } means no step was left.

To undo a step entirely or not at all, ask for whole:

const result = await stack.undo({ whole: true })
if (result.kind === "refused") {
  // A collaborator moved one of the cards since: nothing was undone, the
  // step is gone, and `result.stale` names the parts that blocked it.
  showWhyNot(result.step, result.stale)
}

A refused step is dropped, so the next undo takes the step below it. The result's type follows from the call: whole is true or absent.

A peer sees an undo as the state going back, with nothing to say why. To record it, keep what happened as data in an unrecorded log, a root field of the document that undo never records, and give the stack an annotate hook: what it writes goes into each reverted document with the revert, is stored and sent with it, and is never undone.

const Card = Schema.struct({
  title: Schema.text(),
  // A root field: undo never records a write to it.
  intents: Schema.list.unrecorded(
    Schema.struct.json({ kind: Schema.string(), step: Schema.string() }),
  ),
})

const stack = await createUndoStack({
  exchange,
  docId: `undo:${tabId}`,
  key: "cards",
  scope: docId => docId.startsWith("card:"),
  annotate: (reverting, draft: any) => {
    // A copy of the card as it is now, limited to its unrecorded logs.
    draft.intents.push({ kind: reverting.direction, step: reverting.step.id })
  },
})

One rule. Write intents anywhere, in a gesture too: undo never reverts them, and they never end or split a step. annotate may write only the unrecorded logs; a write elsewhere throws at that write, the undo rejects with UndoAnnotationError (its cause names the path), and nothing is written.

  • Typing goes through stack.typing(fn), which joins a keystroke to the step before it while the user keeps typing in one place (useText(ref, { undo: stack }) does this). Direct writes by an editor binding are grouped the same way with stack.follow(docId).
  • The stack is a document. With a Store it survives a reload, and a crash in the middle of an undo is finished on the next load without applying anything twice. Without one it lasts the session. The document is serialized, so one runtime writes it: give each tab its own id for per-tab undo, or share one over a device's Store.
  • Undo by document. stack.undo({ docs: [cardId] }) undoes the newest step that wrote that card, even under steps in other cards, and redo({ docs }) likewise. So one stack per tab serves every card: each editor passes its own card. Steps conflict by what they write: a document, down to its record keys. A step is never taken from under a newer one it conflicts with, so undo({ docs }) can be none while that card has steps, and top agrees. A new step clears the redo steps it conflicts with, and those made on them.
  • What there is to undo is stack.top("undo", [cardId]): the step an undo would try first, or undefined. It is a tracked read, so useSelector(() => stack.top("undo", [cardId]) !== undefined) re-renders when it changes.
  • A destroyed document's steps are skipped, and the result names them. An undo opens a step's documents with exchange.open, so it never creates a document; a part whose document is gone does not stand. It is in stale when the rest of its step is undone, and a step with nothing else is in dropped, as the undo goes on to the step below; with whole, its step is refused. An unloaded document is opened again, and opening one still unloading cancels its unload.
  • Plain, Loro and Yjs documents are undoable; ephemeral ones are not.

Escape Hatches

Reach the native document or container behind a ref when you need to, for instance to attach an editor binding (y-prosemirror, y-codemirror, loro-prosemirror):

import { unwrap } from "@kyneta/schema"

const ydoc = unwrap(doc)          // the Y.Doc, for a yjs.bind document
const text = unwrap(doc.title)    // the Y.Text, LoroText, … behind a field
text.insert(0, "hello")

A write made this way is a local write like any other: the exchange pushes it to peers and persists it, and subscribers receive it with replay: false.

A native handle writes past every check the exchange makes, so a document that refuses this peer's writes hands none out: unwrap throws whatever writeRefusal(doc) returns. That includes DocumentLoadingError on a stored json document still loading, so after get, await whenHydrated(doc) before unwrap. It also means a read-only document (canWrite, or another seat's json document) cannot drive a native editor binding, not even one in read-only mode; render it through Kyneta refs instead.


Document Initialization

A document that has just been created is empty. So is a document whose stored data is still loading, and one whose server has not answered yet. Telling those apart is the entire problem: writing defaults into the first is correct, and writing them into the other two destroys data.

initialize waits for every source that could have something to say, and only then decides:

import { initialize } from "@kyneta/exchange"

await initialize(doc, d => d.set({ title: "Untitled", posts: [] }))
// → "created" if it wrote the defaults, "loaded" if data was already there

The rule it encodes, in one line: whoever is authoritative seeds when the document is empty; everyone else waits and reads.

The four topologies, one verb

// Standalone — nothing to wait for
const doc = createDoc(BlogSchema)
await initialize(doc, seedDefaults)

// Local-only, with storage — waits for the load, never for a network
const exchange = new Exchange({ principal: "app", store })
await initialize(exchange.get("blog", BlogDoc), seedDefaults)

// Server — authoritative. Declared once, at construction. It has a transport
// (it serves clients), but `authority: "self"` means its own storage is the
// last word, so it seeds as soon as the disk read is done rather than waiting
// for a client that has nothing to tell it.
const server = new Exchange({
  principal: "server",
  store,
  transports: [wsServer],
  authority: "self",
})
await initialize(server.get("blog", BlogDoc), seedDefaults)

// Client — waits for the server's answer, and gives up after 3s if it never
// comes (offline-first).
const client = new Exchange({
  principal: "client",
  transports: [ws],
  authority: p => p.principal === "server",
})
await initialize(client.get("blog", BlogDoc), seedDefaults, { offlineAfter: 3000 })

Identify the authority by principal, not by role

PeerIdentityDetails.type is one of "user" | "bot" | "service", so the tempting client-side check is p => p.type === "service". That is too loose for anything that gates a write: your server is a service, but so is any other service peer on the network — including the devtools inspector, which is itself an Exchange peer. A client using the role check could accept the inspector's reply as the server's verdict.

authority: p => p.principal === "my-server"   // recommended

Not by peerId either: that is the server's seat. A server without a store gets a new one on every restart, and several server processes over one store hold one each.

Reading the status directly

import { docStatus } from "@kyneta/exchange"

docStatus(doc)  // "pending" | "empty" | "populated"

"pending" means some source has yet to report. "empty" means everything has reported and there is nothing there — the only state from which writing defaults is safe. The three states exist so that "we do not know yet" cannot be mistaken for "there is nothing here".

This works at every layer and never throws, including on a plain createDoc document with no Exchange behind it.

Writing a concurrency-safe seed

Whether two peers seeding at once causes a problem depends only on which merge law the seed's writes touch — and every schema constructor already declares its law:

| Constructor | Law | Two peers seeding the same thing | | --- | --- | --- | | product / field .set() | lww-per-key | converge — safe | | map (deterministic key) | lww-per-key | converge — safe | | set | add-wins-per-key | converge (value-addressed) — safe | | sum | lww-tag-replaced | converge — safe | | sequence / movableList | positional-ot | duplicate | | counter | additive | double-count | | text | positional-ot | duplicate |

A seed made of scalars, struct fields, deterministically-keyed map entries, or set members is safe on any number of peers with no configuration at all:

await initialize(doc, d => {
  d.title.set("Untitled")                 // lww-per-key
  d.settings.theme.set("dark")            // lww-per-key
  d.tags.add("inbox")                     // add-wins, value-addressed
  d.sections.set("intro", { order: 0 })   // lww-per-key, deterministic key
})

The unsafe shape is the reflex one — d.items.push({ id: crypto.randomUUID() }) — and the fix is usually a one-line reshape to a map keyed by a stable id, which is often the better model anyway.

If a seed genuinely must be positional, declare an authority so only one peer writes it. TECHNICAL.md covers the remaining options.

What initialize does not do

The seed is an ordinary local write. It broadcasts, it persists, and it passes the same governance gates as any other mutation — so a restrictive canShare or canAccept policy applies to it too. A large default payload therefore produces a full changeset broadcast.

It also refuses one thing outright: seeding a writerModel: "serialized" document (anything bound with json.bind) from a peer that is not the authority. Concurrent seeds cannot merge on that document type, so rather than lose the race at runtime, it throws with the fix in the message.

And a document that refuses this peer's writes (a canWrite policy, another seat's json document) cannot be seeded by it: once the document has loaded, initialize rejects with that refusal itself (NotAWriterError, WriterRefusedError), without waiting for peers, unless the document already holds data.


Complexity Gradient

| Level | What you write | What you get | |-------|----------------|--------------| | Trivial | exchange.get("doc", MyDoc) | Typed, syncable, observable document | | Standard | Add transports, store | Network sync + persistence | | Intermediate | Add canShare, canAccept, canWrite, resolve | Information flow control, read-only documents, dynamic doc creation | | Advanced | register() scopes, Line, custom transports | Composable rules, reliable messaging, custom protocols | | Expert | Custom Substrate<V> implementation | New CRDT runtimes, new state models |

You only engage the next level when you need it. Each level is additive — it doesn't rewrite the previous one.


API Reference

Exchange

| Method / Option | Description | |----------------|-------------| | get(docId, boundSchema) | Get or create a document in interpret mode. Returns Ref<S>. Auto-registers the schema in the capabilities registry. | | replicate(docId) | Promote a deferred document — factory resolved from the capabilities registry. | | replicate(docId, replicaFactory, syncMode, schemaHash) | Register a document for headless replication with explicit arguments. | | has(docId) | Check if a document exists (interpret, replicate, deferred or unloaded). | | deferred | ReadonlySet<DocId> — deferred document IDs. Participate in routing but have no local representation. | | destroy(docId) | Remove a document for good: broadcasts dismiss, deletes it from the store, and releases its memory. A ref you still hold reads its last value, and its writes throw DocumentClosedError. | | suspend(docId) / resume(docId) | Leave / re-enter the sync graph, keeping the document and its local state. | | unload(docId) | Release a stored document's memory and keep it in the store: get or open loads it again. Peers receive every write made before it; a ref you still hold reads its last value, and its writes throw DocumentClosedError. | | peers | CallableChangefeed<ReadonlyMap<PeerId, PeerIdentityDetails>, PeerChange> — reactive peer connection lifecycle (established / disconnected / reconnected / departed). | | flush() | Await all pending storage operations. | | shutdown() | Flush the store, disconnect transports, close handles and every document. The recommended graceful teardown. | | reset() | Disconnect transports and close every document (synchronous). Does NOT flush pending storage. | | addTransport(transport) | Add a transport at runtime. | | removeTransport(transportId) | Remove a transport at runtime. | | hasTransport(transportId) | Check if a transport exists by ID. | | getTransport(transportId) | Get a transport by ID. | | register(scope) | Register a composable scope for dynamic rule composition. Returns a dispose function. | | registerSchema(bound) | Register a BoundSchema at runtime. Auto-promotes matching deferred docs. |

Constructor options:

| Option | Description | |--------|-------------| | principal | string — who this exchange speaks for. Required, non-empty. Several exchanges may share one. The exchange issues its own peerId: its store's seat, or a fresh one without a store. | | type | "user" \| "bot" \| "service" — the peer's role. Default "user". | | transports | AnyTransport[] — network connectivity: transport instances, e.g. createWebsocketClient(...). | | store | Store — the persistent storage backend. It issues the exchange's seat, which a restart over the same storage keeps. | | schemas | BoundSchema[] — upfront schema registration for auto-resolution. | | replicas | BoundReplica[] — replication modes for headless participation. E.g. [loro.replica()]. | | canShare | (docId, peer) → boolean \| undefined — outbound flow control. Default: allow. | | canAccept | (docId, peer) → boolean \| undefined — inbound flow control. Default: allow. | | canWrite | (docId, peer) → boolean \| undefined — who may author operations: judged against this exchange's own identity for its writes, and against the sender of every offer. Default: allow. | | canReset | (docId, peer) → boolean \| undefined — epoch boundary policy. Default: allow. | | canConnect | (peer) → boolean \| undefined — connection-level gate. Default: allow. | | resolve | (docId, peer, replicaType, syncMode, schemaHash) → Disposition — policy gate for unknown docs. | | departureTimeout | number — ms before a disconnected peer is declared departed. Default: 30_000. | | establishTimeout | number — ms a channel may stay unestablished before it is dropped and its connection closed, on every transport and both sides. Default: DEFAULT_HANDSHAKE_TIMEOUT_MS (10_000). This bounds one connection's handshake; limiting how many connections, and how fast, is the application's job. |

sync()

| Property/Method | Description | |----------------|-------------| | peerId | This exchange's seat. | | docId | The document ID. | | peerStates | PeerSyncState[] — raw per-peer sync state. Each entry is { docId, peer, state } where state is "pending" \| "synced" \| "vacant". Volatile — can regress on reconnect. | | ready | boolean — monotonic readiness latch: true once the doc reconciles with ≥1 peer (data or vacant); never regresses. The 90% gate. | | readyFor(pred) | boolean — latch restricted to reconciled peers matching pred (authority / quorum). | | connectivity | "online" \| "connecting" \| "offline". | | onPeerSyncChange(cb) | Subscribe to per-peer sync state changes. Returns unsubscribe function. |

Readiness

Standalone functions, not members of sync(doc). They divide by three questions: has everything reported? (settled, whenSettled), what does the document hold? (docStatus), and has the store confirmed this peer's writes? (persisted).

| Function | Description | |----------|-------------| | whenSettled(doc, opts?) | Resolve once every truth source has reported — stored data loaded and the authority answered. Options: { authority?, offlineAfter? }. Resolves { via: "peer" \| "local" \| "offline" }: "local" when nothing upstream had to answer (no transports, or authority: "self"), "peer" when the authority answered, "offline" when offlineAfter elapsed first. Rejects if the store read failed, or with DocumentClosedError if the document closes before its peers answer. | | docStatus(doc, opts?) | "pending" \| "empty" \| "populated" — total, never throws. Options: { authority? }. | | docStatusFeed(doc, opts?) | Observable form of docStatus, carrying [CHANGEFEED]. | | initialize(doc, seed, opts?) | Write defaults exactly once, only if the document is genuinely empty. Options: { authority?, offlineAfter? }. Returns "created" or "loaded". Rejects with the document's writeRefusal if, once loaded, it refuses this peer's writes and holds no data. | | settled(doc) | boolean — has every truth source reported? The synchronous form of whenSettled; not a promise. | | settledFeed(doc) | Observable form of settled. A callable, so never put it in an if. | | hydrated(doc) / whenHydrated(doc) | The storage half alone: has this document's stored data finished loading? whenHydrated rejects if the load failed. This — not flush() — is the storage gate. | | persisted(doc) | boolean — has the store confirmed every write this peer made to the document? true without a store. Until it is, the exchange sends peers nothing of the document. | | persistedFeed(doc) | Observable form of persisted. A callable, so never put it in an if. | | whenPersisted(doc) | Resolve once persisted. Rejects at once if a store write failed and none has succeeded since, and rejects if one fails while waiting. Writes are retried on their own, so a caller can check persistenceError and wait again. | | persistenceError(doc) | The error of the latest failed store write, cleared by the next write that succeeds. Covers every store write, including one that stores only operations imported from peers, so it can be set while persisted is true. After the seat is lost, the SeatLostError, for good. | | writeRefusal(doc) | Why this document's writes throw, a WriteRefusal (narrow with instanceof), or undefined: a NotAWriterError while a canWrite policy rejects this exchange's own identity, an OfferRefusedError while the document's authority refuses this exchange's operations on it, a WriterRefusedError when another seat of the store writes this json document (kept for the session), a DocumentLoadingError while a stored json document loads, a DocumentClosedError once the document is closed. | | writeRefusalFeed(doc) | Observable form of writeRefusal, e.g. to disable an editor. A callable, so never put it in an if. |

whenSettled and docStatus resolve the authority the same way, so they cannot disagree: call-site opts.authority → the Exchange's Policy.authority → "any".

Bind Functions

| Function | Package | Description | |----------|---------|-------------| | bind({ schema, factory, syncMode }) | @kyneta/schema | General primitive — explicit schema, factory builder, sync mode. | | json.bind(schema) | @kyneta/schema | Plain substrate + authoritative protocol (SYNC_AUTHORITATIVE). | | ephemeral.bind(schema) | @kyneta/schema | Field-level LWW CvRDT, snapshot broadcast, never persisted (SYNC_EPHEMERAL). Presence, cursors, live input. | | loro.bind(schema) | @kyneta/loro-schema | Loro substrate + collaborative protocol (SYNC_COLLABORATIVE). | | yjs.bind(schema) | @kyneta/yjs-schema | Yjs substrate + collaborative protocol (SYNC_COLLABORATIVE). |

Binding Targets

Each binding target is a fixed (substrate, sync-mode, supported-laws) bundle. No strategy parameter — each target has exactly one sync mode.

| Target | Package | syncMode | Description | |--------|---------|----------------|-------------| | json.bind(schema) | @kyneta/schema | SYNC_AUTHORITATIVE | Plain substrate, sequential sync. | | json.replica() | @kyneta/schema | SYNC_AUTHORITATIVE | Plain replica for headless replication. | | ephemeral.bind(schema) | @kyneta/schema | SYNC_EPHEMERAL | Field-level LWW CvRDT, snapshot broadcast. | | ephemeral.replica() | @kyneta/schema | SYNC_EPHEMERAL | Headless replica for relays; merges snapshots without a schema. | | loro.bind(schema) | @kyneta/loro-schema | SYNC_COLLABORATIVE | Loro substrate, collaborative CRDT sync. | | loro.replica() | @kyneta/loro-schema | SYNC_COLLABORATIVE | Loro replica for headless replication. | | yjs.bind(schema) | @kyneta/yjs-schema | SYNC_COLLABORATIVE | Yjs substrate, collaborative CRDT sync. | | yjs.replica() | @kyneta/yjs-schema | SYNC_COLLABORATIVE | Yjs replica for headless replication. | | createBindingTarget(opts) | @kyneta/schema | (custom) | Build a custom binding target with .bind(), .replica(). |

Disposition Constructors

| Function | Package | Description | |----------|---------|-------------| | Interpret(bound) | @kyneta/schema | Full interpretation — schema, ref, changefeed. | | Replicate() | @kyneta/schema | Headless replication — factory resolved from capabilities. | | Defer() | @kyneta/schema | Track for routing, promotable later. | | Reject() | @kyneta/schema | Refuse to track the document. |

Escape Hatches

| Function | Package | Description | |----------|---------|-------------| | unwrap(ref) | @kyneta/schema | Returns the native document or container behind a ref: a Y.Doc or LoroDoc for a document, a Y.Text, LoroText, … for a field. Writes made on it sync and persist. Throws the document's writeRefusal, if it has one. |

Storage

| Export | Description | |--------|-------------| | Store | Interface for persistent storage backends: append, load, and compaction by mark (StoreMark). Sev