@homeostate/crdt-automerge
v0.3.0
Published
Automerge CRDT backend for @homeostate/core
Maintainers
Readme
@homeostate/crdt-automerge
Automerge backend for
@homeostate/core.
It maps the synced state onto one key of an Automerge document (objects become maps, arrays
lists, and strings ImmutableStrings or, where you choose, text), one Automerge change per
write.
Install
npm install @homeostate/core @homeostate/crdt-automerge @automerge/automerge@automerge/automerge 3.x is a peer dependency. It ships WebAssembly; for bundler setup see
Automerge's documentation.
Usage
Automerge documents are immutable, so createAutomergeHandle holds the current one for the
backend and your replication code to share:
import * as A from "@automerge/automerge";
import { createSyncEngine } from "@homeostate/core";
import {
createAutomergeBackend,
createAutomergeHandle,
} from "@homeostate/crdt-automerge";
const handle = createAutomergeHandle(A.init());
const engine = createSyncEngine(
createAutomergeBackend(handle, "shared"),
adapter,
);
engine.connect();
// Replication is yours to wire:
handle.subscribe(({ doc, local }) => {
if (local) send(A.getLastLocalChange(doc));
});
onMessage((change) => handle.update((doc) => A.applyChanges(doc, [change])[0]));handle.doc() returns the current document, handle.change(fn) applies a local change, and
handle.update(fn) replaces the document with the result of any Automerge call. See the
documentation for details.
To let an automerge-repo Repo store and sync the
document instead, pass one of its DocHandles:
createAutomergeBackend(await repo.find(url), "shared");Strings are ImmutableString values, so concurrent writes keep one of them. Pass text to
store chosen strings as Automerge text, whose concurrent edits merge character by character:
createAutomergeBackend(handle, "shared", {
text: (path) => path[0] === "todos" && path[2] === "title",
});To persist the document, pass createAutomergePersistable(handle) to createPersistence, or
use a Repo's storage adapter; see the
persistence guide.
License
MIT — see LICENSE. Includes code derived from zustand-middleware-yjs; see THIRD_PARTY_NOTICES.md.
