Sync / foldkit-sync
Run it in the browser
Three steps connect TodoSync in the browser: open tab storage and a replica, mount the application over it, and start the exchange loop.
ts
import { Effect, Scope } from 'effect'
import { modifyFields } from 'foldkit/struct'
import { Sync } from 'foldkit-sync'
const container = document.getElementById('app')!
// This tab's store, kept across reloads; its connection lives for the page.
const scope = Effect.runSync(Scope.make())
const replica = await Effect.runPromise(
Sync.tabStorage('todos').pipe(
Effect.flatMap(TodoSync.openReplica),
Effect.provideService(Scope.Scope, scope),
),
)
const mounted = Sync.mount(App, TodoSync, {
replica,
container,
view: (model, h) => ({
title: 'Todos',
body: h.ul([], model.todos.map(todo => h.li([], [todo.title]))),
}),
onPersistenceFailure: (model, error) =>
modifyFields(model, { lastError: () => Option.some(error.message) }),
})
Effect.runFork(
Effect.provide(replica.start, Sync.transport.socket({ url: 'wss://example.com/sync' })),
)
mounted.dispatch(Message.CreatedTodo({ id: crypto.randomUUID(), title: 'Milk' }))What each call does:
Sync.tabStorage('todos')opens this tab's IndexedDB store using a key insessionStorage, so reloads reopen the same store (including unsent edits) while duplicated tabs get separate stores.openReplica(storage)reads the saved committed snapshot, cursor, and outbox locally (deferring network sync untilreplica.startruns). Its mintedreplicaIdidentifies one store—never a person—so operation ids (replicaId:count) never collide across browsers; pass{ replicaId }in tests or servers.Sync.mount(App, TodoSync, …)runs Foldkit with yourviewandupdate. DurableMessages update theModelimmediately and persist via a Command (reverting and callingonPersistenceFailureif persistence fails), while localMessages run directly.replica.startruns the exchange loop on startup, after each submit, and on server commit notices, retrying failed exchanges with backoff from 0.5 s to 30 s (or immediately on the next edit) and reporting issues viastatus.mounted.dispatchdispatches aMessageinto the mounted app (containerrequires anidattribute).
Reload the page: todos restores from the outbox and committed snapshot while selectedTodoId resets to Option.none().
mounted also exposes model(), subscribe, observe, committed, settled(), and dispose() (which awaits in-flight persists while leaving the replica open; close the replica via scope). Pair settled() with Frames.track from foldkit-mixins/testing (await frames.settle(mounted)) in tests.