### 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}
)
}
// Wrap app in RepoContext to inject the repo
function App() {
return (
"automerge:3ksb..."} />
)
}
```
--------------------------------
### Add WebSocket Adapter to Repo
Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo/README.md
Integrates the WebSocket client adapter into the Automerge Repo configuration to connect to a sync server.
```typescript
// main.tsx
import { WebSocketClientAdapter } from "@automerge/automerge-repo-network-websocket" // <-- add this line
// ...
const repo = new Repo({
network: [
new BroadcastChannelNetworkAdapter(),
new WebSocketClientAdapter("ws://localhost:3030"), // <-- add this line
],
storage: new IndexedDBStorageAdapter(),
})
// ...
```
--------------------------------
### NodeFSStorageAdapter for Filesystem Persistence (Node.js)
Source: https://context7.com/automerge/automerge-repo/llms.txt
Persist Automerge documents as files in a local directory using Node.js. This adapter is ideal for Node.js sync servers and CLI tools, providing filesystem-based storage.
```typescript
import { Repo } from "@automerge/automerge-repo"
import { NodeFSStorageAdapter } from "@automerge/automerge-repo-storage-nodefs"
const repo = new Repo({
storage: new NodeFSStorageAdapter(
"./automerge-data" // base directory (default: "automerge-repo-data")
),
})
const handle = repo.create<{ log: string[] }>({ log: [] })
handle.change(d => d.log.push("Server started"))
await repo.flush() // Force a write (changes are auto-saved with debouncing)
```
--------------------------------
### RepoContext
Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md
A convenience context for Automerge-Repo Solid apps. It allows you to pass the repo higher up in your app. It's optional; you can also pass a repo as an option to `useDocHandle` and `useDocument`.
```APIDOC
### RepoContext
A convenience context for Automerge-Repo Solid apps. Optional: if you prefer you
can pass a repo as an option to `useDocHandle` and `useDocument`.
```tsx
```
```
--------------------------------
### makeDocSignal
Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md
Similar to `createDocSignal`, but without a reactive input. This is the underlying primitive for `createDocSignal`.
```APIDOC
## makeDocSignal
Just like `createDocSignal`, but without a reactive input.
Underlying primitive for [`createDocSignal`](#createdocsignal).
```ts
makeDocSignal(handle: DocHandle): Accessor>
```
### Example
```tsx
// example
const handle = repo.find(url)
const doc = makeDocSignal<{ count: number }>(handle)
return {doc()?.count}
```
```
--------------------------------
### Clone Automerge Repo
Source: https://github.com/automerge/automerge-repo/blob/main/examples/svelte-counter/README.md
Clone the Automerge Repo monorepo to your local device to begin.
```bash
git clone git@github.com:automerge/automerge-repo.git
```
--------------------------------
### createAutomergeStore
Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-svelte-store/README.md
Creates an Automerge store factory from a repo instance. This factory can then be used to create or find Automerge documents as Svelte stores.
```APIDOC
## createAutomergeStore(repo)
### Description
Creates an Automerge store factory from a repo instance.
### Parameters
#### Path Parameters
- **repo** (Repo) - Required - An instance of the Automerge Repo.
### Returns
- (AutomergeStoreFactory) - A factory object for creating and managing Automerge document stores.
```
--------------------------------
### makeDocumentProjection
Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md
Similar to `createDocumentProjection`, but operates without a reactive input. This is the underlying primitive for `createDocumentProjection`.
```APIDOC
## makeDocumentProjection
Just like `createDocumentProjection`, but without a reactive input.
Underlying primitive for [`createDocumentProjection`](#createDocumentProjection).
```ts
makeDocumentProjection(handle: Handle): 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}
```
```
--------------------------------
### Network Adapter: WebSocketServerAdapter for running a sync server
Source: https://context7.com/automerge/automerge-repo/llms.txt
Accepts WebSocket connections and syncs documents between clients in Node.js. Typically used with the `ws` package. Configure the keep-alive ping interval and a share policy.
```typescript
import { Repo } from "@automerge/automerge-repo"
import { WebSocketServerAdapter } from "@automerge/automerge-repo-network-websocket"
import { NodeFSStorageAdapter } from "@automerge/automerge-repo-storage-nodefs"
import { WebSocketServer } from "ws"
const wss = new WebSocketServer({ port: 3030 })
const serverRepo = new Repo({
storage: new NodeFSStorageAdapter("./data"),
network: [
new WebSocketServerAdapter(
wss,
5000 // keep-alive ping interval in ms (default: 5000)
),
],
// Servers typically only share docs that peers explicitly request
sharePolicy: async (peerId, documentId) => false,
})
console.log("Sync server listening on ws://localhost:3030")
```
--------------------------------
### makeDocumentProjection for Non-Reactive DocHandle View
Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md
Use `makeDocumentProjection` for a fine-grained view from a `DocHandle` without a reactive input. This is the underlying primitive for `createDocumentProjection`.
```ts
makeDocumentProjection(handle: Handle): 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}
```
--------------------------------
### useDocHandle Hook for DocHandle Resource
Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md
Use the `useDocHandle` hook to retrieve a `DocHandle` from the repository as a Solid `Resource`. This is ideal for passing to `createDocumentProjection`. The `repo` option can be omitted if using `RepoContext`.
```ts
useDocHandle(
() => AnyDocumentId,
options?: {repo: Repo}
): Resource>
```
```tsx
const handle = useDocHandle(id, { repo })
// or
const handle = useDocHandle(id)
```
--------------------------------
### RepoContext Provider for Automerge Repo
Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-solid-primitives/readme.md
Provide the Automerge `Repo` instance to the Solid application using `RepoContext.Provider`. This allows child components to access the repo via `useRepo` without prop drilling.
```tsx
```
--------------------------------
### Network Adapter: `WebSocketServerAdapter` — run a sync server
Source: https://context7.com/automerge/automerge-repo/llms.txt
Used in Node.js to accept WebSocket connections and sync documents between clients. Typically used with the `ws` package's `WebSocketServer`.
```APIDOC
## Network Adapter: `WebSocketServerAdapter` — run a sync server
Used in Node.js to accept WebSocket connections and sync documents between clients. Typically used with the `ws` package's `WebSocketServer`.
```typescript
import { Repo } from "@automerge/automerge-repo"
import { WebSocketServerAdapter } from "@automerge/automerge-repo-network-websocket"
import { NodeFSStorageAdapter } from "@automerge/automerge-repo-storage-nodefs"
import { WebSocketServer } from "ws"
const wss = new WebSocketServer({ port: 3030 })
const serverRepo = new Repo({
storage: new NodeFSStorageAdapter("./data"),
network: [
new WebSocketServerAdapter(
wss,
5000 // keep-alive ping interval in ms (default: 5000)
),
],
// Servers typically only share docs that peers explicitly request
sharePolicy: async (peerId, documentId) => false,
})
console.log("Sync server listening on ws://localhost:3030")
```
```
--------------------------------
### React Hooks and Context
Source: https://context7.com/automerge/automerge-repo/llms.txt
Provides React context and hooks to easily access and utilize the Automerge Repo instance within React components.
```APIDOC
## React Integration
### Description
Integrates Automerge Repo with React applications using `RepoContext` and the `useRepo` hook.
### Components and Hooks
- **`RepoContext`**: A React context that makes a `Repo` instance available throughout the component tree.
- **`useRepo()`**: A hook that allows components to access the `Repo` instance provided by `RepoContext`.
```
--------------------------------
### Repo Methods
Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo/README.md
The Repo object manages multiple Automerge documents and provides methods for document creation, retrieval, import, export, and event subscription.
```APIDOC
## Repo.create(initialValue?: T)
### Description
Creates a new Automerge.Doc and returns a DocHandle for it. Accepts an optional initial value for the document.
### Parameters
- **initialValue** (T) - Optional - The initial value for the document.
### Returns
- **DocHandle** - A handle to the newly created document.
```
```APIDOC
## Repo.find(docId: DocumentId): Promise>
### Description
Looks up a given document either on the local machine or over configured networks. Returns a promise that resolves when the document is loaded or throws if load fails.
### Parameters
- **docId** (DocumentId) - Required - The ID of the document to find.
### Returns
- **Promise>** - A promise that resolves with a handle to the document.
```
```APIDOC
## Repo.delete(docId: DocumentId)
### Description
Deletes the local copy of a document from the local cache and local storage. This does not currently delete the document from any other peers.
### Parameters
- **docId** (DocumentId) - Required - The ID of the document to delete.
```
```APIDOC
## Repo.import(binary: Uint8Array): Promise>
### Description
Imports a document binary (from export() or Automerge.save(doc)) into the repo, returning a new handle.
### Parameters
- **binary** (Uint8Array) - Required - The binary representation of the document.
### Returns
- **Promise>** - A promise that resolves with a handle to the imported document.
```
```APIDOC
## Repo.export(docId: DocumentId): Promise
### Description
Exports the document. Returns a Promise containing either the Uint8Array of the document or undefined if the document is currently unavailable.
### Parameters
- **docId** (DocumentId) - Required - The ID of the document to export.
### Returns
- **Promise** - A promise that resolves with the document's binary data or undefined.
```
```APIDOC
## Repo.on("document", ({ handle: DocHandle }) => void)
### Description
Registers a callback to be fired each time a new document is loaded or created.
### Parameters
- **callback** ({ handle: DocHandle }) - The function to call when a document is loaded or created.
```
```APIDOC
## Repo.on("delete-document", ({ handle: DocHandle }) => void)
### Description
Registers a callback to be fired each time a new document is deleted.
### Parameters
- **callback** ({ handle: DocHandle }) - The function to call when a document is deleted.
```
--------------------------------
### getContextRepo
Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-svelte-store/README.md
Retrieves the Automerge repo instance from the current component's context.
```APIDOC
## getContextRepo()
### Description
Gets the Automerge repo from the current component's context.
### Returns
- (Repo | undefined) - The Automerge Repo instance from context, or undefined if not set.
```
--------------------------------
### document
Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-svelte-store/README.md
A convenience method to load an Automerge document, either from the repo in context or a provided repo instance. Returns a Promise that resolves to the document store.
```APIDOC
## document(docIdOrUrl, repoInstance?)
### Description
Convenience method to load a document from the repo in context or a provided repo.
### Parameters
#### Path Parameters
- **docIdOrUrl** (string) - Required - The ID or URL of the document to load.
- **repoInstance** (Repo) - Optional - An explicit Repo instance to use for loading the document.
### Returns
- (Promise) - A Promise that resolves to the Svelte store for the Automerge document.
```
--------------------------------
### Document Store API
Source: https://github.com/automerge/automerge-repo/blob/main/packages/automerge-repo-svelte-store/README.md
The Automerge document store, returned by `find()` and `create()`, adheres to Svelte's writable store contract and provides additional methods for interacting with Automerge documents.
```APIDOC
## Store API
The document store returned by `find()` and `create()` implements Svelte's writable store contract with these additional methods:
### Methods
- **change(fn)**: Make changes to the document. The `fn` parameter is a callback function that receives the document as an argument and should contain the mutations.
- **url**: A property that returns the URL of the document.
- **documentId**: A property that returns the ID of the document.
- **handle**: A property that provides access to the underlying Automerge document handle for more advanced operations.
```
--------------------------------
### useDocHandle
Source: https://context7.com/automerge/automerge-repo/llms.txt
Returns the raw `DocHandle` itself, which provides direct access to methods like `handle.change()`, `handle.broadcast()`, and `handle.view()`. Useful when more control over the document is needed.
```APIDOC
## React: `useDocHandle` — access the raw `DocHandle`
Returns the `DocHandle` itself (rather than the doc state), useful when you need to call `handle.change()`, `handle.broadcast()`, `handle.view()` etc. directly.
### Parameters
- `url` (AutomergeUrl): The URL of the document.
- `options` (object, optional): Configuration options.
- `suspense` (boolean, optional): If true, enables Suspense mode. Defaults to false.
### Returns
- `handle` (DocHandle | undefined): The `DocHandle` for the document. Undefined in non-suspense mode while loading.
### Example (Non-Suspense Mode)
```tsx
import { useDocHandle } from "@automerge/automerge-repo-react-hooks"
import { AutomergeUrl } from "@automerge/automerge-repo"
interface NoteDoc { title: string; body: string }
function NoteEditor({ url }: { url: AutomergeUrl }) {
// Non-suspense: handle may be undefined while loading
const handle = useDocHandle(url)
const exportNote = async () => {
if (!handle) return
const binary = await handle.doc() // get raw doc
// ...serialize or send binary
}
const broadcastCursor = () => {
handle?.broadcast({ type: "cursor", line: 5, col: 12 })
}
return (
)
}
```
### Example (Suspense Mode)
```tsx
import { useDocHandle } from "@automerge/automerge-repo-react-hooks"
import { AutomergeUrl } from "@automerge/automerge-repo"
interface NoteDoc { title: string; body: string }
function NoteEditorSuspending({ url }: { url: AutomergeUrl }) {
// Suspense mode: handle is always defined
const handleSync = useDocHandle(url, { suspense: true })
const history = handleSync.history()
return (
Document history length: {history.length}
)
}
```
```
--------------------------------
### Network Adapter: WebSocketClientAdapter for connecting to a sync server
Source: https://context7.com/automerge/automerge-repo/llms.txt
Connects to a remote sync server over WebSocket in browsers and Node.js. Automatically retries on disconnect. Configure the retry interval in milliseconds.
```typescript
import { Repo } from "@automerge/automerge-repo"
import { WebSocketClientAdapter } from "@automerge/automerge-repo-network-websocket"
import { IndexedDBStorageAdapter } from "@automerge/automerge-repo-storage-indexeddb"
const repo = new Repo({
storage: new IndexedDBStorageAdapter(),
network: [
new WebSocketClientAdapter(
"wss://sync.example.com",
5000 // retry interval in ms (default: 5000; set to 0 to disable retries)
),
],
})
const handle = repo.create<{ text: string }>({ text: "Hello!" })
// Changes are automatically synced to the server
handle.change(d => { d.text = "Hello, world!" })
```