### Run Demo Apps Source: https://github.com/automerge/automerge-repo/blob/main/CONTRIBUTING.md Execute this command to start the demo applications after installing dependencies and building packages. ```sh pnpm dev ``` -------------------------------- ### Install Dependencies and Build Packages Source: https://github.com/automerge/automerge-repo/blob/main/CONTRIBUTING.md Run these commands to install all necessary project dependencies and build the packages. This step is required before running demo applications. ```sh pnpm install pnpm build ``` -------------------------------- ### Install @automerge/vanillajs Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-vanillajs/README.md Install the package using npm, yarn, or pnpm. ```bash npm install @automerge/vanillajs # or yarn add @automerge/vanillajs # or pnpm add @automerge/vanillajs ``` -------------------------------- ### Install automerge-repo-svelte-store Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-svelte-store/README.md Install the Svelte store package using npm. ```bash npm install @automerge/automerge-repo-svelte-store ``` -------------------------------- ### Install WebSocket Network Adapter Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo/README.md Installs the WebSocket network adapter for real-time synchronization. ```bash yarn add automerge-repo-network-websocket ``` -------------------------------- ### Start Sync Server Source: https://github.com/automerge/automerge-repo/blob/main/examples/svelte-counter/README.md Run the local automerge repo sync server to enable cross-browser synchronization. ```bash pnpm start:syncserver ``` -------------------------------- ### Install @automerge/react Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-react/README.md Install the package using npm, yarn, or pnpm. ```bash npm install @automerge/react # or yarn add @automerge/react # or pnpm add @automerge/react ``` -------------------------------- ### Install Solid Automerge Primitives Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md Install the necessary packages for Solid Automerge integration. ```sh pnpm add solid-js @automerge/automerge-repo @automerge/automerge-repo-solid-primitives ``` -------------------------------- ### Vanilla JS: Automerge Repo Convenience Package Source: https://context7.com/automerge/automerge-repo/llms.txt A single import package for browser environments that includes `@automerge/automerge-repo` and common browser adapters. Simplifies setup by reducing the number of explicit installations. ```typescript import { Repo, BroadcastChannelNetworkAdapter, MessageChannelNetworkAdapter, WebSocketClientAdapter, IndexedDBStorageAdapter, isValidAutomergeUrl, parseAutomergeUrl, } from "@automerge/automerge-vanillajs" // Full repo setup in a single import const repo = new Repo({ storage: new IndexedDBStorageAdapter(), network: [ new BroadcastChannelNetworkAdapter(), new WebSocketClientAdapter("wss://sync.example.com"), ], }) const handle = repo.create<{ title: string; body: string }>({ title: "Hello", body: "", }) handle.on("change", ({ doc }) => { document.getElementById("preview")!.textContent = doc.body }) handle.change(d => { d.body = "World" }) ``` -------------------------------- ### Basic Automerge Store Setup in Svelte Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-svelte-store/README.md Initialize an Automerge Repo and create a store from it. Load or create documents using the store's methods. ```svelte ``` -------------------------------- ### Run Svelte Demo Dev Server Source: https://github.com/automerge/automerge-repo/blob/main/examples/svelte-counter/README.md Start the vite dev server for the Svelte demo application from the root directory of the monorepo. ```bash pnpm dev:svelte-demo ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/automerge/automerge-repo/blob/main/examples/svelte-counter/README.md Install all project dependencies using pnpm, the required package manager for the monorepo. ```bash pnpm install ``` -------------------------------- ### Initialize Automerge Repo with Adapters Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-vanillajs/README.md Create a new Automerge Repo instance, configuring it with desired network and storage adapters. This example shows how to use MessageChannel, IndexedDB, and WebSocket adapters. ```javascript import { Repo, MessageChannelNetworkAdapter, IndexedDBStorageAdapter, WebSocketClientAdapter, } from "@automerge/vanillajs" // Create a repo with your chosen adapters const repo = new Repo({ network: [ new MessageChannelNetworkAdapter(/* your message channel to another repo here */), new IndexedDBStorageAdapter(), new WebSocketClientAdapter("wss://sync.automerge.org"), ], }) // Create a new document const handle = repo.create() // Load an existing document const existingHandle = repo.find(documentId) // Listen for changes handle.on("change", () => { console.log("Document changed:", handle.docSync()) }) ``` -------------------------------- ### Install Dependencies Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo/README.md Installs necessary dependencies for the Automerge Repo project using Yarn. ```bash yarn yarn dev ``` -------------------------------- ### Create Vite React App Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo/README.md Sets up a new React project with Vite and installs Automerge-related packages. ```bash yarn create vite # Project name: hello-automerge-repo # Select a framework: React # Select a variant: TypeScript cd hello-automerge-repo yarn yarn add @automerge/automerge @automerge/automerge-repo-react-hooks @automerge/automerge-repo-network-broadcastchannel @automerge/automerge-repo-storage-indexeddb vite-plugin-wasm ``` -------------------------------- ### useDocHandle Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md Get a `DocHandle` from the repo as a resource. This is perfect for handing to `createDocumentProjection`. ```APIDOC ## useDocHandle Get a [DocHandle](https://automerge.org/docs/repositories/dochandles/) from the repo as a [resource](https://docs.solidjs.com/reference/basic-reactivity/create-resource). Perfect for handing to `createDocumentProjection`. ```ts useDocHandle( () => AnyDocumentId, options?: {repo: Repo} ): Resource> ``` ### Examples ```tsx const handle = useDocHandle(id, { repo }) // or const handle = useDocHandle(id) ``` The `repo` option can be left out if you are using [RepoContext](#repocontext). ``` -------------------------------- ### useRepo Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md Get the Automerge repo instance from the context. ```APIDOC ### useRepo Get the repo from the [context](#repocontext). ```ts useRepo(): Repo ``` #### e.g. ```ts const repo = useRepo() ``` ``` -------------------------------- ### createDocumentProjection Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md Get a fine-grained live view from a signal automerge `DocHandle`. This is the underlying primitive for `useDocument` and works with `useHandle`. ```APIDOC ## createDocumentProjection Get a fine-grained live view from a signal automerge `DocHandle`. Underlying primitive for [`useDocument`](#usedocument-). Works with [`useHandle`](#usehandle). ```ts createDocumentProjection(() => AutomergeUrl): Doc ``` ### Example ```tsx // example const handle = repo.find(url) const doc = makeDocumentProjection<{ items: { title: string }[] }>(handle) // subscribes fine-grained to doc.items[1].title return

{doc.items[1].title}

``` ``` -------------------------------- ### useDocument Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md Get a fine-grained live view of an automerge document from its URL. When the handle receives changes, it converts the incoming automerge patch ops to precise solid store updates, giving you fine-grained reactivity that's consistent across space and time. Returns `[doc, handle]`. ```APIDOC ## useDocument Get a fine-grained live view of an automerge document from its URL. When the handle receives changes, it converts the incoming automerge patch ops to precise solid store updates, giving you fine-grained reactivity that's consistent across space and time. Returns `[doc, handle]`. ```ts useDocument( () => AutomergeURL, options?: {repo: Repo} ): [Doc, DocHandle] ``` ### Example ```tsx // example const [url, setURL] = createSignal(props.url) const [doc, handle] = useDocument(url, { repo }) const inc = () => handle()?.change(d => d.count++) return ``` The `{repo}` option can be left out if you are using [RepoContext](#repocontext). ``` -------------------------------- ### createDocumentProjection for Reactive DocHandle View Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md Use `createDocumentProjection` to get a fine-grained live view from a signal `DocHandle`. This primitive works with `useHandle` and provides reactive access to document properties. ```ts createDocumentProjection(() => AutomergeUrl): Doc ``` ```tsx // example const handle = repo.find(url) const doc = makeDocumentProjection<{ items: { title: string }[] }>(handle) // subscribes fine-grained to doc.items[1].title return

{doc.items[1].title}

``` -------------------------------- ### useDocument Hook for Live Document View Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md Use the `useDocument` hook to get a fine-grained live view of an Automerge document from its URL. It converts Automerge patch operations to precise Solid store updates for reactivity. The `{repo}` option can be omitted if using `RepoContext`. ```ts useDocument( () => AutomergeURL, options?: {repo: Repo} ): [Doc, DocHandle] ``` ```tsx // example const [url, setURL] = createSignal(props.url) const [doc, handle] = useDocument(url, { repo }) const inc = () => handle()?.change(d => d.count++) return ``` -------------------------------- ### makeDocSignal for Non-Reactive DocHandle Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md Use `makeDocSignal` to get a coarse-grained accessor for a `DocHandle` without a reactive input. This is the underlying primitive for `createDocSignal`. ```ts makeDocSignal(handle: DocHandle): Accessor> ``` ```tsx // example const handle = repo.find(url) const doc = makeDocSignal<{ count: number }>(handle) return {doc()?.count} ``` -------------------------------- ### Automerge Store with Svelte 5 Runes Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-svelte-store/README.md Utilize Svelte 5 runes for a more declarative and ergonomic way to manage Automerge documents. This example uses `$state`, `$derived`, and `$effect` for state management and document loading. ```svelte {#if loading}

Loading document...

{:else if error}

Error: {error.message}

{:else} {/if} ``` -------------------------------- ### createDocSignal for Reactive DocHandle Signal Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md Use `createDocSignal` to get a coarse-grained reactive signal for a `DocHandle`. This primitive is the underlying implementation for `useDocSignal` and works with `useDocHandle`. ```ts createDocSignal(() => DocHandle): Accessor> ``` -------------------------------- ### Repo Initialization and Basic Operations Source: https://context7.com/automerge/automerge-repo/llms.txt Demonstrates how to initialize a Repo instance with storage and network adapters, and perform basic document operations like creating, finding, cloning, exporting, importing, and deleting documents. ```APIDOC ## Repo Initialization and Basic Operations ### Description Initialize a `Repo` instance with storage and network adapters. Manage documents using `DocHandle`s. Perform operations such as creating new documents, finding existing ones by URL, cloning documents, exporting to binary format, importing from binary, and deleting documents. ### Methods - `new Repo(config)`: Constructor for the `Repo` class. - `create(initialValue)`: Creates a new Automerge document with an optional initial value. - `find(url)`: Finds and returns a `DocHandle` for an existing document by its URL. - `clone(handle)`: Clones an existing document, creating a new `DocHandle` that shares history. - `export(url)`: Exports a document to its binary representation. - `import(binary)`: Imports a document from its binary representation. - `delete(url)`: Deletes a document from local storage and sync. - `shutdown()`: Gracefully shuts down the repo, flushing writes and disconnecting adapters. - `on('document', ({ handle }) => ...)`: Event listener for newly discovered or created documents. - `on('delete-document', ({ documentId }) => ...)`: Event listener for document deletions. ### Parameters #### Repo Constructor Config - `storage` (StorageAdapter): An instance of a storage adapter (e.g., `IndexedDBStorageAdapter`). - `network` (NetworkAdapter[]): An array of network adapter instances (e.g., `BroadcastChannelNetworkAdapter`, `WebSocketClientAdapter`). - `sharePolicy` (function): A function to determine if a document should be shared with a peer. - `isEphemeral` (boolean): Whether to persist sync state (default: `false`). - `saveDebounceRate` (number): Milliseconds between storage writes (default: `100`). #### `create` Method - `initialValue` (object, optional): The initial content of the document. #### `find` Method - `url` (string): The Automerge URL of the document to find. #### `clone` Method - `handle` (DocHandle): The `DocHandle` of the document to clone. #### `export` Method - `url` (string): The Automerge URL of the document to export. #### `import` Method - `binary` (Uint8Array): The binary data of the document to import. #### `delete` Method - `url` (string): The Automerge URL of the document to delete. ### Request Example ```typescript import { Repo } from "@automerge/automerge-repo" import { IndexedDBStorageAdapter } from "@automerge/automerge-repo-storage-indexeddb" import { BroadcastChannelNetworkAdapter } from "@automerge/automerge-repo-network-broadcastchannel" const repo = new Repo({ storage: new IndexedDBStorageAdapter("my-app"), network: [new BroadcastChannelNetworkAdapter()] }) // Create a new document const handle = repo.create<{ count: number }>({ count: 0 }) console.log(handle.url) // Re-open an existing document const existingHandle = await repo.find<{ count: number }>(handle.url) // Clone a document const clonedHandle = repo.clone(existingHandle) // Export a document const binary: Uint8Array = await repo.export(handle.url) // Import a document const importedHandle = repo.import<{ count: number }>(binary) // Delete a document repo.delete(handle.url) // Listen for new documents repo.on("document", ({ handle }) => { console.log("New doc:", handle.url) }) // Shut down the repo await repo.shutdown() ``` ### Response #### Success Response - `handle` (DocHandle): A handle to the Automerge document. - `url` (string): The Automerge URL of the document. - `binary` (Uint8Array): The binary representation of the document. - `importedHandle` (DocHandle): A handle to the imported Automerge document. #### Response Example ```json { "handle": { /* DocHandle object */ }, "url": "automerge:3ksb...", "binary": "Uint8Array [...]", "importedHandle": { /* DocHandle object */ } } ``` ``` -------------------------------- ### Initialize and Use Automerge Repo Source: https://context7.com/automerge/automerge-repo/llms.txt Demonstrates creating a Repo instance with storage and network adapters, managing documents (create, find, clone, export, import, delete), and handling repo shutdown and events. Configure storage and network adapters, and optionally set a share policy. ```typescript import { Repo } from "@automerge/automerge-repo" import { IndexedDBStorageAdapter } from "@automerge/automerge-repo-storage-indexeddb" import { BroadcastChannelNetworkAdapter } from "@automerge/automerge-repo-network-broadcastchannel" import { WebSocketClientAdapter } from "@automerge/automerge-repo-network-websocket" // Create a repo with storage + two network adapters const repo = new Repo({ storage: new IndexedDBStorageAdapter("my-app"), network: [ new BroadcastChannelNetworkAdapter(), new WebSocketClientAdapter("wss://sync.example.com"), ], // Only share docs with peers that explicitly request them (server-style) sharePolicy: async (peerId, documentId) => false, isEphemeral: false, // persist sync state saveDebounceRate: 200, // ms between storage writes (default: 100) }) // Create a new document with an optional initial value const handle = repo.create<{ count: number }>({ count: 0 }) console.log(handle.url) // "automerge:3ksb..." // Persist the URL so the document can be re-opened later localStorage.setItem("docUrl", handle.url) // Re-open an existing document by URL (loads from storage, then network) const existingHandle = await repo.find<{ count: number }>(handle.url) // Clone a document (shares history — changes can be merged back) const clonedHandle = repo.clone(existingHandle) // Export a document to binary (Automerge binary format) const binary: Uint8Array = await repo.export(handle.url) // Import a binary document const importedHandle = repo.import<{ count: number }>(binary) // Delete a document from local storage and sync (does NOT delete from remote peers) repo.delete(handle.url) // Gracefully shut down — flush pending writes and disconnect adapters await repo.shutdown() // Listen for any newly discovered or created document repo.on("document", ({ handle }) => { console.log("New doc:", handle.url) }) repo.on("delete-document", ({ documentId }) => { console.log("Deleted:", documentId) }) ``` -------------------------------- ### Create Automerge Repo with Storage and Network Adapters Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo/README.md Instantiates a new Repo with specified network and storage adapters. The sharePolicy determines peer connection behavior. ```typescript const repo = new Repo({ network: [new BroadcastChannelNetworkAdapter()], storage: new IndexedDBStorageAdapter(), sharePolicy: async (peerId: PeerId, documentId: DocumentId) => true, // this is the default }) ``` -------------------------------- ### Using the Presence Class in Automerge Repo Source: https://context7.com/automerge/automerge-repo/llms.txt Demonstrates how to initialize and use the Presence class for managing ephemeral state. Requires importing `Repo` and `Presence` from `@automerge/automerge-repo`. Ensure a `Repo` instance and a `DocHandle` are available. ```typescript import { Repo, Presence } from "@automerge/automerge-repo" interface CursorState { cursor: { x: number; y: number } userName: string } const repo = new Repo({ /* ... */ }) const handle = repo.create() const presence = new Presence({ handle, }) presence.start({ initialState: { cursor: { x: 0, y: 0 }, userName: "Alice" }, heartbeatMs: 10000, peerTtlMs: 60000, }) // Broadcast a channel update to all peers presence.broadcast("cursor", { x: 150, y: 300 }) // Listen for peer state events presence.on("update", () => { const peerView = presence.getPeerStates() for (const peer of peerView.peers()) { console.log(peer.peerId, peer.state?.cursor) } }) presence.on("heartbeat", () => console.log("Peer heartbeat received")) presence.on("goodbye", () => console.log("Peer disconnected gracefully")) // Get current local state const local = presence.getLocalState() // Stop broadcasting and clean up presence.stop() ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/automerge/automerge-repo/blob/main/examples/svelte-counter/README.md Change the current directory to the cloned automerge-repo. ```bash cd automerge-repo ``` -------------------------------- ### useRepo Hook to Access Automerge Repo Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md Use the `useRepo` hook to get the Automerge `Repo` instance from the nearest `RepoContext` in the component tree. ```ts useRepo(): Repo ``` ```ts const repo = useRepo() ``` -------------------------------- ### Initialize Automerge Repo in React App Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo/README.md Sets up the Automerge Repo with BroadcastChannel and IndexedDB adapters, and initializes the root document. ```typescript // src/main.tsx import React from "react" import ReactDOM from "react-dom/client" import App from "./App.js" import { Repo } from "@automerge/automerge-repo" import { BroadcastChannelNetworkAdapter } from "@automerge/automerge-repo-network-broadcastchannel" import { IndexedDBStorageAdapter } from "@automerge/automerge-repo-storage-indexeddb" import { RepoContext } from "@automerge/automerge-repo-react-hooks" const repo = new Repo({ network: [new BroadcastChannelNetworkAdapter()], storage: new IndexedDBStorageAdapter(), }) let rootDocId = localStorage.rootDocId if (!rootDocId) { const handle = repo.create() localStorage.rootDocId = rootDocId = handle.documentId } ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( ) ``` -------------------------------- ### Create Node App with NPM Source: https://github.com/automerge/automerge-repo/blob/main/packages/create-repo-node-app/README.md Use this command to create a new Node.js project with Automerge Repo using NPM. Replace `` with your desired project directory name. ```bash npm create @automerge/repo-node-app ``` -------------------------------- ### Solid.js: createDocumentProjection and makeDocSignal Source: https://context7.com/automerge/automerge-repo/llms.txt Lower-level utilities for building custom reactive pipelines. `createDocumentProjection` offers fine-grained reactivity, while `makeDocSignal` provides a non-hook accessor for use outside component trees. ```tsx import { createDocumentProjection, makeDocSignal } from "@automerge/automerge-repo-solid-primitives" // createDocumentProjection: fine-grained reactive projection (uses immer-style tracking) // Works with any accessor that returns a DocHandle function FineGrainedNote(props: { handle: () => DocHandle | undefined }) { const doc = createDocumentProjection(props.handle) // Only the parts of the JSX that access doc().title will re-render when title changes return

{doc()?.title}

} // makeDocSignal: non-hook version (usable outside Solid component trees) // Returns an accessor that updates when the document changes function standaloneSignal(handle: DocHandle) { const docAccessor = makeDocSignal(() => handle) // docAccessor() returns the current NoteDoc or undefined return docAccessor } ``` -------------------------------- ### Create Node App with Yarn Source: https://github.com/automerge/automerge-repo/blob/main/packages/create-repo-node-app/README.md Use this command to create a new Node.js project with Automerge Repo using Yarn. Replace `` with your desired project directory name. ```bash yarn create @automerge/repo-node-app ``` -------------------------------- ### Run Tests Source: https://github.com/automerge/automerge-repo/blob/main/CONTRIBUTING.md Use this command to run the project's tests. Note that tests currently require Node 20 and are not compatible with Node 22. ```sh pnpm test ``` -------------------------------- ### Svelte: Automerge Repo Store Integration Source: https://context7.com/automerge/automerge-repo/llms.txt Wraps a DocHandle into a Svelte-compatible readable store. Use with `$` auto-subscription syntax for reactive updates. ```svelte ``` -------------------------------- ### Create and Use Automerge Repo with React Hooks Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-react/README.md Demonstrates how to create a pre-configured Automerge Repo instance and use the `useDocument` hook within a React component to access document content. ```tsx import { createRepo, useDocument } from "@automerge/react" // Create a pre-configured repo instance const repo = createRepo({ websocketUrl: "ws://localhost:8080", // optional enableStorage: true, // optional, defaults to true enableMessageChannel: true, // optional, defaults to true }) // Use in your React components function MyComponent() { const doc = useDocument(repo, "my-doc-id") if (!doc) return
Loading...
return
{doc.content}
} ``` -------------------------------- ### createRepo Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-react/README.md Creates a pre-configured Automerge Repo instance with common adapters. This function initializes the repository with specified options for network connectivity and storage. ```APIDOC ## createRepo(options?: CreateRepoOptions) ### Description Creates a pre-configured Automerge Repo instance with common adapters. ### Parameters #### Options - **websocketUrl** (string) - Optional - The URL of the WebSocket server to connect to. - **enableStorage** (boolean) - Optional - Whether to enable IndexedDB storage (default: true). - **enableMessageChannel** (boolean) - Optional - Whether to enable MessageChannel network adapter (default: true). ``` -------------------------------- ### Build the Monorepo Source: https://github.com/automerge/automerge-repo/blob/main/examples/svelte-counter/README.md Build the entire automerge-repo monorepo. This command must be run from the root directory. ```bash pnpm build ``` -------------------------------- ### Solid.js: useDocument and useDocHandle Primitives Source: https://context7.com/automerge/automerge-repo/llms.txt Provides fine-grained reactive accessors (`useDocument`) or coarse-grained signals (`useDocHandle` with `createDocSignal`) for Automerge documents in Solid.js applications. Requires wrapping the app in `RepoContext`. ```tsx import { createSignal } from "solid-js" import { Repo } from "@automerge/automerge-repo" import { IndexedDBStorageAdapter } from "@automerge/automerge-repo-storage-indexeddb" import { useDocument, useDocHandle, createDocSignal, RepoContext, } from "@automerge/automerge-repo-solid-primitives" interface NoteDoc { title: string; content: string } const repo = new Repo({ storage: new IndexedDBStorageAdapter() }) function NoteEditor(props: { url: () => string }) { // Fine-grained reactive accessor: only re-renders affected parts const [doc, handle] = useDocument(props.url) // Or just get a coarse-grained signal (re-renders on any change) const docHandle = useDocHandle(props.url) const docSignal = createDocSignal(docHandle) return (

{doc()?.title}