Birch UI v0.1
Pricing

CollaborationDocument

Edit one document from several browsers with Birch UI Document Editor: offline editing with rebase on reconnect, presence, version history, range locks, pluggable backends and a durable reference WebSocket relay.

Open .md

Several people can edit the same document at once. Each editor sends its changes as steps together with the version they were made against, applies the steps of others, and replays its own unconfirmed steps on top of them. One authority per document decides the order of the steps. The package ships that authority, three ways to reach it, and a durable WebSocket relay to start from.

TypeScript
import { createCollabProvider, createDocumentEditor, createSocketBackend } from '@birchui/document';

const backend = createSocketBackend({
  connect: () => new WebSocket('wss://relay.example.com/?token=' + sessionToken),
  room: 'msa-northwind',
});
const editor = createDocumentEditor(host, {
  author: 'Priya Raman',
  content,
  collab: createCollabProvider(backend),
});

editor.on('collabStatus', ({ state, version, unconfirmed }) => showStatus(state));
editor.on('collabConnection', ({ status }) => showConnection(status));
editor.on('presenceChange', ({ collaborators }) => showPeople(collaborators));

Every editor must start from the same document, or let the authority send its snapshot (see Snapshots). Undo only reverts the local person's own edits. With track changes on, each person's insertions and deletions carry their own name.

What this is and is not#

  • A central-authority rebase model, not a CRDT. One authority per document holds the document and the log of accepted steps. A batch of steps is accepted only when its version equals the number of steps the authority already holds and every step applies to the authority's own copy. A refused client fetches what it missed, rebases and sends again. Two clients that cannot reach the authority do not see each other until they reconnect. There is no peer-to-peer mode, no merge without the authority, and no convergence guarantee of the kind a CRDT gives; see Yjs, Automerge and similar libraries for what such a library can and cannot do here.
  • The authority validates. createCollabAuthority({ document }) and the reference relay parse every step with the document schema, apply it to their copy, and refuse a batch that does not apply, breaks the schema, carries an address that is not allow-listed, or exceeds the limits. Lock footprints, snapshots and named versions are derived from that copy, never from what a client sends.
  • Offline editing works. Edits made without a connection stay in the editor as unconfirmed steps and are rebased over the missed steps on reconnect. By default they live in memory, and closing the tab while offline loses them; pass collabStorage to keep them (see Keeping offline edits).
  • Rebasing is positional. When two people change the same words at once, both changes are kept where that is possible, and a step that no longer applies after rebasing (for example text typed inside a paragraph somebody else deleted) is dropped.

Connection status and offline edits#

getCollabConnection() and the collabConnection event report the transport:

Status Meaning
connected The authority is reachable; changes are sent as they are made.
reconnecting The connection was lost and the backend is retrying. Editing continues locally.
offline The backend stopped trying (attempts exhausted, access refused, or closed). Editing continues locally.

getCollabStatus() and the collabStatus event describe the document:

State Meaning
synced Everything typed here is confirmed.
pending Local changes are waiting for confirmation.
offline Not connected; unconfirmed counts the steps waiting to be sent.
desynced Remote steps could not be applied; send a snapshot through onReset or call resetCollab.
disabled No provider is set.

When the connection returns the editor asks for every step and side-channel change after its version, rebases its unconfirmed steps over them and sends them. The status carries connection as well, so one listener is enough for a status badge.

collabRejected fires when local steps had to be withdrawn: reason: 'locked' when they touched a range locked by someone else, reason: 'invalid' when the authority refused them (they did not apply to its document or exceeded a limit), and reason: 'stale' when the editor was reset from a snapshot while it still had unsent steps.

Keeping offline edits#

collabStorage is a hook with load(), save(record) and clear(). While there are unconfirmed steps the editor saves them, with the document body and version they start from, about four times a second and again on pagehide; it clears the record once everything is confirmed. A new editor with the same storage loads the record, goes back to that version, re-applies the steps as local changes, catches up and sends them. collabRestored reports { steps, version }.

TypeScript
import { createDocumentEditor } from '@birchui/document';
import { createIndexedDbOfflineStore, createSocketBackend, createCollabProvider } from '@birchui/document/collab';

const room = 'msa-northwind';
const editor = createDocumentEditor(document.querySelector<HTMLElement>('#editor')!, {
  author: 'Priya Raman',
  collab: createCollabProvider(
    createSocketBackend({ connect: () => new WebSocket('wss://relay.northwind.example/?token=…'), room }),
  ),
  collabStorage: createIndexedDbOfflineStore({ key: `${room}:priya.raman` }),
});
editor.on('collabRestored', ({ steps }) => console.info(`${steps} offline changes restored`));

createIndexedDbOfflineStore({ key, database? }) keeps one record per key in IndexedDB; use a key that names the document and the person. createMemoryOfflineStore() is the same hook in memory, for tests. A record that no longer fits the schema is discarded with a console error. If the person types before the record has loaded, the record is left alone and a warning is logged. A client that stayed offline past the retained log is still reset to the snapshot, and its restored steps are dropped with collabRejected.

When the browser has no indexedDB, createIndexedDbOfflineStore logs one warning and returns the in-memory store, so edits are kept for the life of the page only. When the database cannot be opened (blocked storage, private mode in some browsers), load, save and clear reject; the editor logs the error and carries on without a stored copy, and the next save tries to open the database again.

Presence#

Each person's cursor and selection appear in the others' documents in a stable colour with a name label, and the status bar lists who is here; activating a person jumps to their cursor. Presence is built to survive bad networks:

  • an editor republishes its presence after every reconnect and at least every third of presenceTimeout (30 seconds by default, set on the provider or through createCollabProvider(backend, { presenceTimeout }));
  • a collaborator whose presence has not been refreshed within presenceTimeout is removed, so a peer that vanished without saying goodbye does not linger;
  • the authority removes a client's presence as soon as its connection closes, and the reference relay pings sockets to notice dead ones;
  • going offline clears the list locally.

Comments, page setup and headers#

Comment threads, replies, resolved state, page setup and header and footer changes travel as meta operations next to the steps. The authority keeps them in their own ordered log, so they are delivered again after message loss or a reconnect, and concurrent changes settle on the order the authority recorded (the last writer wins per field).

Comment ids, reply ids and tracked-change ids are 96 random bits (comment-5f0c…) while a session is active, so ids allocated by different clients do not collide. createCollabId(prefix) gives you the same generator.

Version history#

Named versions are stored through the provider:

TypeScript
const signed = await editor.saveCollabVersion('Signed draft'); // null when the provider has no versions channel
const versions = await editor.listCollabVersions(); // [{ id, name, createdAt, author, clientId, version }]
const latest = versions.at(-1);
if (signed && latest) {
  const redline = await editor.diffCollabVersions(signed.id, latest.id); // DocNodeJSON with tracked changes
  const pending = await editor.diffCollabVersions(signed.id, null); // against the open document
  await editor.restoreCollabVersion(signed.id);
}

A version is the complete document at the moment it was saved, including comments and page setup. With a validating authority that is the authority's own copy, not what the saving editor sent. diffCollabVersions runs compareDocuments on two versions and returns a document in which the differences are tracked changes; pass { author, granularity } to control it. restoreCollabVersion replaces the content with an ordinary edit, so it is sent to everyone, can be undone, and never rewrites history. Threads of the restored version that no longer exist are added back; page setup is restored as well. The methods resolve to null, [] or false when the provider has no versions channel.

How versions are stored#

The authority does not keep a full document per version. The first version is stored as a full document; each later one is stored as the steps and document updates (comments, page setup, headers and footers) accepted since the previous version, with a reference to it. Loading, comparing or restoring a version replays those steps onto the nearest full document, so versions.load(id) and the methods above return the same complete document as before. Twelve versions of a 400-paragraph contract with one sentence changed between each take about the size of one copy plus the eleven edits.

A version is stored as a full document again when:

  • there is no earlier version, or the earlier one was written without a document-update counter (versions saved by a release before step diffs);
  • the step log no longer reaches back to the previous version, because a snapshot trimmed it (retainSteps);
  • the steps since the previous version are larger than the document itself, as after a pasted rewrite;
  • 32 versions in a row have been stored as steps, which bounds how much has to be replayed;
  • the authority runs with trustClients: true and has no copy to replay steps on.

To keep versions across a restart of your own authority, store storedVersions() and pass it back:

TypeScript
import { createCollabAuthority } from '@birchui/document/collab';
import type { CollabSnapshot, CollabStoredVersion } from '@birchui/document/collab';

declare const saved: { snapshot: CollabSnapshot; versions: CollabStoredVersion[] };

const authority = createCollabAuthority({ snapshot: saved.snapshot, versions: saved.versions });
const toPersist = {
  snapshot: { document: authority.document()!, version: authority.version(), metaVersion: authority.metaVersion() },
  versions: authority.storedVersions(),
};

A stored version is either { id, name, createdAt, author, clientId, version, metaVersion?, document } or { …, metaVersion, parent, steps, meta }, where parent is the id of the previous version and each meta entry carries the step version it was applied at. Full-document records written by earlier releases have the first shape and stay readable. A version whose chain of parents no longer leads to a full document loads as null, so store and delete the list as a whole rather than record by record.

Range locks#

TypeScript
const lock = await editor.lockRange({ from, to }); // defaults to the selection; null when refused
editor.getLocks(); // every lock, positions follow the document
editor.on('locksChange', ({ locks }) => paintLocks(locks));
if (lock) editor.unlockRange(lock.id);

Locks are optional. While a range is locked, other editors refuse local changes that touch it, and the authority refuses batches that touch it: this covers steps typed before the lock arrived, which are withdrawn with a collabRejected event. Inserting directly before or after a locked range is allowed. A lock request is refused when it overlaps another lock or was made against an older version, so retry after collabStatus reports synced. Locks are held per connection: they are released when the owner disconnects and are not restored on reconnect. The authority follows the ranges through the step maps each client reports with its steps; a client that sends no footprints cannot edit while somebody else holds a lock.

Backends#

The editor talks to a CollabProvider. You rarely write one: implement the smaller CollabBackend and wrap it with createCollabProvider, or use one of the adapters.

Adapter Use
createAuthorityBackend(authority, start?) The central-authority flow in process: createCollabAuthority({ document }) holds its own copy of the document, the logs, presence, locks, versions and snapshots, and validates every step. For tests, servers and single-page demos.
createSocketBackend({ connect, room, … }) Talks to the reference relay over a WebSocket, with reconnect back-off (reconnectMin, reconnectMax, maxAttempts) and a heartbeat. connect returns a browser WebSocket or a ws socket.
createBroadcastChannelBackend({ channel }) Tabs of one browser. One tab calls hostBroadcastChannel(authority, channel) and holds the authority; when that tab closes the others report reconnecting until a host returns. There is no host election.
createWireBackend(link) / createWireEndpoint(authority, send) The JSON protocol behind the two adapters above, for any other message transport.
createLoopbackHub(options) In-memory hub with latency, jitter, message loss and manual stepping for demos and tests.
TypeScript
interface CollabBackend {
  readonly clientId: string | number;
  open(emit: (event: CollabBackendEvent) => void): void;
  version(): number; // the version of the document the editor is created with
  metaVersion(): number;
  submit(payload: CollabStepsPayload): Promise<CollabSubmitResult>;
  pull(sinceVersion: number, sinceMeta: number): void;
  setPresence?(state: PresenceState | null): void;
  sendSnapshot?(snapshot: CollabSnapshot): void;
  locks?: { acquire(request: CollabLockRequest): Promise<CollabLock | null>; release(id: string): void };
  versions?: CollabVersionChannel;
  close(): void;
}

type CollabBackendEvent =
  | { type: 'connection'; status: 'connected' | 'reconnecting' | 'offline' }
  | { type: 'steps'; payload: CollabRemotePayload }
  | { type: 'reset'; snapshot: CollabSnapshot }
  | { type: 'presence'; states: Record<string, PresenceState> }
  | { type: 'locks'; state: CollabLockState }
  | { type: 'snapshotRequest' };

The contract a backend must keep:

  1. submit accepts a batch only when payload.version equals the number of steps already accepted, and answers { accepted: false, reason: 'stale' } otherwise. Every accepted batch is emitted as a steps event to every client, the sender included, with the version it was appended at and one clientIds entry per step.
  2. pull emits the steps after sinceVersion. It may emit reset first when it can no longer serve them.
  3. meta operations are optional to support. When you do, append them to an ordered log and emit them with metaVersion (the index of the first one) and metaClientIds, and replay them from sinceMeta in pull.
  4. connection events tell the editor when to queue and when to catch up. Emit connected once the backend can submit.

This complete backend keeps the log in memory and is compiled as part of the test suite:

TypeScript
import { createCollabProvider } from '@birchui/document';
import type {
  CollabBackend,
  CollabBackendEvent,
  CollabLogEntry,
  CollabStepsPayload,
  CollabSubmitResult,
} from '@birchui/document';

const log: CollabLogEntry[] = [];
const listeners = new Set<(event: CollabBackendEvent) => void>();

function createMemoryBackend(clientId: string): CollabBackend {
  let listener: ((event: CollabBackendEvent) => void) | null = null;
  return {
    clientId,
    open(emit) {
      listener = emit;
      listeners.add(emit);
      emit({ type: 'connection', status: 'connected' });
    },
    version: () => 0,
    metaVersion: () => 0,
    async submit(payload: CollabStepsPayload): Promise<CollabSubmitResult> {
      if (payload.version !== log.length) return { accepted: false, version: log.length, reason: 'stale' };
      for (const step of payload.steps) log.push({ step, clientId });
      const event: CollabBackendEvent = {
        type: 'steps',
        payload: { version: payload.version, steps: payload.steps, clientIds: payload.steps.map(() => clientId) },
      };
      for (const emit of listeners) emit(event);
      return { accepted: true, version: log.length };
    },
    pull(sinceVersion) {
      const entries = log.slice(sinceVersion);
      listener?.({
        type: 'steps',
        payload: {
          version: sinceVersion,
          steps: entries.map((entry) => entry.step),
          clientIds: entries.map((entry) => entry.clientId),
        },
      });
    },
    close() {
      if (listener) listeners.delete(listener);
    },
  };
}

const provider = createCollabProvider(createMemoryBackend('priya'));

Yjs, Automerge and similar libraries#

The editor is not built on a CRDT and the package does not ship an adapter for one. It merges by rebasing steps over a single order of accepted batches, so it cannot consume a CRDT document type such as Y.XmlFragment directly, and binding it to one would mean replacing the rebase plugin, not configuring it.

What Yjs can do is carry the messages between the editors and the one authority, over a provider and server you already run. packages/document/examples/collab-yjs/shared-doc-link.ts is a small bridge that does this. It is an example to copy, not a package export, and it has no dependency on yjs: it is written against the few methods of Y.Doc, Y.Array and Y.Map it uses, so a real Y.Doc can be passed as it is.

JavaScript
import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';
import { createCollabAuthority, createCollabProvider, createWireBackend } from '@birchui/document/collab';
import { createSharedDocLink, hostSharedDoc } from './shared-doc-link';

// In every browser: a Y.Doc used only as the transport.
const transport = new Y.Doc();
const provider = new WebsocketProvider('wss://yjs.northwind.example', 'msa-northwind-transport', transport);
const link = createSharedDocLink(transport, {
  linkId: String(transport.clientID),
  watchConnection(listener) {
    const onStatus = ({ status }) => listener(status === 'connected');
    provider.on('status', onStatus);
    return () => provider.off('status', onStatus);
  },
});
const collab = createCollabProvider(createWireBackend(link, { clientId: 'priya.raman' }));

// In exactly one process that also joins the Y.Doc: the authority.
const authority = createCollabAuthority({ document: startingDocument });
const host = hostSharedDoc(authority, transport, 'host-frankfurt-1');

How it works: each editor writes its wire messages to a Y.Array only it appends to, and the host answers on a second array only the host appends to. An array with a single writer keeps its order, which is the property the protocol needs. A Y.Map announces the current host and registers each link; when another host id appears there, every editor goes to reconnecting, says hello to the new host and catches up. host.drop(linkId) ends the link of an editor that has gone away, which releases its presence and locks; call it when the awareness protocol reports that client as removed.

This is still the central-authority rebase model, with Yjs as the wire:

  • One process must run the authority and be reachable through the shared document. If it is down, editors keep typing locally and nothing is merged until a host is back. Two hosts on one shared document are not supported; the later announcement wins and the earlier host's clients rejoin it.
  • Editors that can reach each other through Yjs but not the host do not see each other's edits. Yjs does not merge the document; it only delivers messages.
  • A new host must start from the previous host's snapshot and stored versions, exactly like any other authority restart.
  • Every message, including each cursor move, stays in the transport document's history. Use a Y.Doc that exists only for this, do not persist it, and start a fresh one (a new room name) from time to time. Durable state is the authority's snapshot and versions, not the Yjs document.
  • The bridge is tested in this repository against an in-memory stand-in with the same methods, and was type-checked against a hand-written copy of the Yjs method signatures. It has not been run against a Yjs release here, so treat it as a starting point.

Appending to one shared array from several peers at once is not an order on its own: concurrent appends can land before entries another peer has already applied, and the editors then diverge. This is why every array in the bridge has a single writer and why the authority, not the array, decides the order of steps. A true peer-to-peer mode with no ordering party is not supported.

Snapshots and catching up#

An authority created with snapshotEvery: n stores a snapshot of its own document every n accepted steps, then drops the steps before the snapshot, keeping retainSteps (2,000 by default) so that clients that were briefly offline can still rebase.

A client whose version is older than the retained log, or newer than the log after data loss on the server, receives the snapshot as a reset followed by the steps after it. A reset replaces the document, so unsent steps of that client are lost; collabRejected reports how many.

Snapshots and named versions are taken from the authority's copy. A snapshot or a version document sent by a client is ignored: sendSnapshot returns false, and versions.save stores the authority's document at its current version whatever the client passed.

What the authority checks#

Check Refusal
version equals the authority's version stale
Every step parses with the document schema, has positions inside the document, applies, and leaves a document that passes the schema check invalid
No link with a script address and no picture address outside the allow-list (see Addresses) invalid
At most maxStepsPerSubmit steps (5,000), maxSubmitBytes of JSON (16 MB), a document of at most maxDocumentSize positions (20,000,000), maxMetaPerSubmit side-channel operations (200) and comment text up to maxCommentLength (100,000) invalid
Comment, page setup and header or footer operations have the expected shape; header and footer content passes the schema invalid
The steps do not touch a range locked by another client, judged by footprints the authority computes from the steps locked

limits on createCollabAuthority and on the relay changes the numbers. The result of a refused submit carries detail with the reason in words. The authority starts from document (the document at version 0) or from snapshot; with neither it starts from an empty document, and editors that start from other content are refused. trustClients: true turns all of this off and relays steps unchecked: use it only where every client is your own code, such as a unit test of a transport.

Reference relay#

packages/document/examples/collab-relay is a Node 20 server with its own package.json (the dependencies are ws and @birchui/document).

Terminal
cd packages/document/examples/collab-relay
npm install
RELAY_TOKEN="$(openssl rand -hex 24)" DATA_DIR=./relay-data PORT=8787 npm start

The relay does not start without RELAY_TOKEN (at least 16 characters): there is no anonymous mode. Clients then connect to ws://localhost:8787/?token=…. index.html in the same folder is a page that does so; it and the command-line relay start from the same starting-document.mjs, because the relay refuses steps made against another document. To embed the relay in your own server, import it. authenticate and createDocument are required, and createRelay throws without them:

JavaScript
import { createCollabDocument } from '@birchui/document/collab';
import { createRelay } from './server.mjs';

const relay = createRelay({
  dataDir: '/var/lib/birchui-relay',
  createDocument: createCollabDocument,
  loadDocument: (roomId) => documents.read(roomId),
  authenticate: async (request) => {
    const session = await sessions.verify(request.headers.cookie);
    return session ? { id: session.userId, name: session.displayName } : null;
  },
  authorize: (user, roomId) => acl.canEdit(user.id, roomId),
  snapshotEvery: 200,
  retainSteps: 2000,
});
const { port } = await relay.listen(8787, '0.0.0.0');
Part Behaviour
Rooms One document per room id ([A-Za-z0-9._-], up to 120 characters). A room is loaded from disk when its first client joins and unloaded when its last one leaves.
createDocument Required. createCollabDocument from @birchui/document/collab; the relay applies every step to the copy it returns and refuses what does not apply.
loadDocument(roomId) The document a room starts from when it has no snapshot on disk, read from your own storage. Without it a new room starts empty.
limits The limits of What the authority checks.
authenticate(request) Required. Called with the HTTP upgrade request (URL, cookies, headers) for every socket and for the HTTP endpoints. Return a user { id, name? } or null. A refused socket receives a fatal error and close code 4401, and the client goes offline instead of retrying. When name is set it replaces the name in that client's presence and versions.
authorize(user, roomId) Optional per-room check; a refusal closes with code 4403.
Step log <dataDir>/<room>/log.ndjson, append-only, one record per step or meta operation, written and fsynced before the batch is acknowledged (fsync: false trades that for speed).
Snapshot <dataDir>/<room>/snapshot.json, the relay's own document every snapshotEvery steps, written to a temporary file, synced and renamed, after which the log is rewritten the same way with the retained tail.
Recovery On start the snapshot and the log are read and the log is replayed onto the snapshot; a torn record at the end of the log is cut off, and a log that does not apply stops the room from opening. Clients reconnect, are told what they missed and send what they typed meanwhile.
Versions <dataDir>/<room>/versions/<id>.json: a full document for the first version, and for later ones the steps since the previous version (see How versions are stored); files with a full document from earlier releases are still read. The relay rebuilds the document when a version is requested. Over the socket through the versions channel; over HTTP as GET /rooms/<room>/versions and GET /rooms/<room>/versions/<id>.
Health GET /health lists loaded rooms with their version and client count.
Liveness Sockets are pinged every heartbeat milliseconds (30 seconds by default) and terminated when they do not answer, which releases their presence and locks.

The relay is a reference, not a product: it runs as one process with one data directory and has no rate limiting. It validates what authenticated clients send (see What the authority checks), which protects the document from a broken or hostile client; it does not decide who may edit which part, so authorize remains your access control. Put TLS and request limits in front of it. The token authenticator of the command-line entry compares in constant time and is meant for a first deployment, not as a user system.

Wire protocol#

Messages are JSON objects. Client to relay: hello { room, clientId }, request { id, method, params } with the methods submit, lock, versionSave, versionList and versionLoad, pull { since, sinceMeta }, presence { state }, unlock { id } and ping. A snapshot message is ignored. Relay to client: welcome, response { id, result }, error { code, message, fatal }, pong, and the backend events steps, reset, presence, locks and snapshotRequest exactly as typed above. A client id must be unique per connection; a second connection with the same id replaces the first.

The provider#

createCollabProvider builds this object for you. Write it by hand only to integrate an existing transport; everything after onRemoteSteps is optional.

TypeScript
interface CollabProvider {
  version: number | (() => number); // the version of the document the editor was created with
  clientId?: string | number;
  metaVersion?: number | (() => number); // set it when meta operations arrive with metaVersion
  sendSteps(payload: CollabStepsPayload): CollabSendResult | Promise<CollabSendResult>; // false or { accepted: false, reason }
  onRemoteSteps(handler: (payload: CollabRemotePayload) => void): () => void;
  requestSteps?(sinceVersion: number, sinceMeta?: number): void;
  onConnection?(handler: (status: 'connected' | 'reconnecting' | 'offline') => void): () => void;
  onStatus?(handler: (status: 'online' | 'offline') => void): () => void; // used when onConnection is absent
  onReset?(handler: (snapshot: CollabSnapshot) => void): () => void;
  presence?: CollabPresenceChannel; // { send(state), subscribe(handler) }
  presenceTimeout?: number; // milliseconds, 0 turns expiry off
  comments?: CollabCommentChannel; // { send(operation), subscribe(handler) }, only used without metaVersion
  versions?: CollabVersionChannel;
  locks?: CollabLockChannel;
  snapshots?: { send(snapshot: CollabSnapshot): void; subscribe(handler: () => void): () => void };
}

getCollabStatus(), getCollabVersion(), getCollabConnection(), getCollaborators(), sendableSteps(), receiveSteps(payload) and resetCollab(snapshot) give the same information and control from code. update({ collab: null }) leaves the session.

Loopback hub#

createLoopbackHub(options) is an in-memory authority for demos and tests. Each hub.connect(clientId) returns a provider with presence, versions, locks and snapshots.

TypeScript
const hub = createLoopbackHub({ document: content, latency: 150, jitter: 40, dropRate: 0.05 });
const priya = hub.connect('priya');
const daniel = hub.connect('daniel');

priya.setConnection('reconnecting'); // edits queue locally
priya.setConnection('connected'); // they are rebased and sent
hub.version(); // number of accepted steps
hub.authority(); // the CollabAuthority behind the hub

latency and jitter delay every message in milliseconds and dropRate loses a share of them, which exercises the catch-up path. With manual: true nothing is delivered until you call hub.step() (one message) or hub.flush() (all of them), and hub.pending() tells you how many are waiting; this makes convergence tests deterministic. connection.setOnline(false) is short for setConnection('offline'), connection.reset(snapshot) replaces a client's document, connection.disconnect() leaves the hub and hub.destroy() releases its timers. The hub's authority validates steps against document, so pass the document every editor starts from; a hub connection reports the hub's current version, so create every editor from that document before anyone types.

How it is tested#

The package's test suite runs a seeded fuzz over the wire protocol: three to six editors make 1,100 rounds of random inserts, deletions, paragraph splits, formatting and comment operations while messages are lost, duplicated and reordered and clients disconnect and reconnect, and every editor must end on the document obtained by applying the authority's log. A second suite starts the relay on a local port, connects editors over real WebSockets, stops and restarts it, and checks recovery from disk, including a version stored as steps. The IndexedDB offline store is tested against a small in-memory IndexedDB, and in Chrome against the real one: an edit typed while disconnected is restored after a page reload and delivered. A second browser test joins two pages over BroadcastChannel with track changes on, cuts one page's connection while both keep typing, and checks that both end on the same document with each insertion and deletion under the right author.

Limits#

  • A central authority must order the steps. There is no peer-to-peer mode and no CRDT. The Yjs bridge in examples/collab-yjs uses Yjs as the transport to that authority and is an example, not a supported adapter; nothing is shipped for Automerge.
  • A version stored as steps needs the versions before it, back to the nearest full document. Deleting single stored versions is not supported.
  • Unsent offline edits are held in memory unless collabStorage is set. A client that stays offline past the retained log is reset to the snapshot and loses them either way.
  • Client ids must be unique per connection. Create a new backend per editor.
  • Locks are per connection and are lost on disconnect. The authority computes what a step touches, so a client cannot write into a range somebody else locked; locks are still a courtesy between editors, not a permission system.
  • The authority checks that steps apply and fit the schema. It does not check who may change what: a signed-in client can delete the whole document with valid steps.
  • The validating authority loads the document schema, which adds about 60 kB (minified) to a bundle that imports only @birchui/document/collab.
  • Concurrent changes to the same comment field, page setup or header settle on the last one the authority recorded.
  • The watermark, line numbers, styles and list definitions are not synchronised. Comments, page setup and headers and footers are.
  • The reference relay is a single process with file storage and no horizontal scaling.
  • Remote cursor positions are sent as document positions and can be briefly off while steps are in flight.

↑ ↓ to move, Enter to open, Esc to close