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 in sessionStorage, 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 until replica.start runs). Its minted replicaId identifies 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 your view and update. Durable Messages update the Model immediately and persist via a Command (reverting and calling onPersistenceFailure if persistence fails), while local Messages run directly.
  • replica.start runs 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 via status.
  • mounted.dispatch dispatches a Message into the mounted app (container requires an id attribute).

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.