@vielzeug/codex 26.11.16 → 26.11.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/catalog.json +105 -55
- package/data/llms-full.txt +724 -236
- package/data/llms.txt +2 -1
- package/data/manifest.json +1 -1
- package/data/packages/archive.json +13 -2
- package/data/packages/assay.json +12 -1
- package/data/packages/bard.json +38 -0
- package/data/packages/forge.json +5 -0
- package/data/packages/lingua.json +2 -2
- package/data/packages/mesh.json +3 -3
- package/data/packages/ore.json +12 -1
- package/data/packages/patchwork.json +5 -0
- package/data/packages/prism.json +12 -1
- package/data/packages/refine.json +12 -1
- package/data/packages/scout.json +17 -20
- package/data/packages/tandem.json +3 -3
- package/data/packages/tavern.json +8 -2
- package/package.json +2 -2
- package/skills/vielzeug/SKILL.md +1 -0
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"apiSource": "// Public root surface of @vielzeug/tandem. Every public export goes through this file.\n\nexport { TandemDisposedError, TandemError } from './errors';\nexport { createSync } from './tandem';\nexport type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Tandem: Offline-first sync engine'\ndescription: Offline-first sync engine with rev baselines, tombstoned deletions, and idle-batched pushes for browser applications.\npackage: tandem\ncategory: sync\nkeywords: [sync, offline, conflict, tombstone, rev, replication, last-write-wins]\nrelated: [vault, postmaster, sentinel, ripple]\nexports: [createSync, SyncPort, SyncGateway, SyncHandle, TandemEvent, TandemError, TandemDisposedError]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tandem\" />\n\n## Why Tandem?\n\nA local-first app keeps its records in IndexedDB but must still reach a server: batch bursts of edits into one upload, propagate deletions that a plain pull would resurrect, and reconcile two devices that edited the same record while offline. Tandem drives that round trip against any backend, tracking a per-record write counter so a push carries only what actually changed.\n\n```ts\n// Before\n// Hand-rolled: debounce each save, POST the whole table, hope deletions survive.\nlet timer;\nfunction onSave(record) {\n clearTimeout(timer);\n timer = setTimeout(() => fetch('/sync', { method: 'POST', body: JSON.stringify(allRecords()) }), 3000);\n}\n\n// After\nimport { createSync } from '@vielzeug/tandem';\n\nconst sync = createSync({ gateway, port, idleDelayMs: 3000 });\nsync.changed(); // a local edit happened: the engine batches and pushes dirty records\n```\n\n| Feature | Tandem | RxSync | PowerSync |\n| --------------------------------------- | -------------------------------------------- | ----------------------------------- | ----------------------------------- |\n| Bundle size | <PackageInfo package=\"tandem\" type=\"size\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Zero runtime dependencies | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Backend-agnostic (bring your `port`) | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Storage-agnostic (bring your `gateway`) | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> |\n| Tombstoned deletions + rev conflicts | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> |\n\n<div class=\"decision-callout\">\n\n**Use `tandem` when** you already own a local store and a backend and want the sync scheduler: dirty tracking, batching, hide-flows, and conflict reconcile: without adopting a database or a server.\n\n**Consider `PowerSync` when** you want a managed sync service with its own SQLite client and server component rather than a scheduler over your existing storage.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/tandem\n```\n\n```sh [npm]\nnpm install @vielzeug/tandem\n```\n\n```sh [yarn]\nyarn add @vielzeug/tandem\n```\n\n:::\n\n## Quick Start\n\nImplement the two seams: a `SyncPort` for the server and a `SyncGateway` for local storage: then start the scheduler. Records are opaque to Tandem; it reads only `id` and `rev`, and every rev comparison is the engine's: the gateway upserts, validates, and tombstones.\n\n```ts\nimport { createSync, type SyncGateway, type SyncPort } from '@vielzeug/tandem';\n\nconst port: SyncPort = {\n pull: (since) => fetch(`/sync?since=${since ?? ''}`).then((r) => r.json()),\n push: async (records, deletions) => {\n const response = await fetch('/sync', { method: 'POST', body: JSON.stringify({ records, deletions }) });\n if (!response.ok) throw new Error(await response.text()); // divergence → the engine pulls to reconcile\n },\n};\n\nconst gateway: SyncGateway = {\n records: () => localRecords.map((record) => ({ entity: 'docs', record })),\n pendingDeletions: () => readTombstones(),\n applyRecords: (pulled) => upsert(pulled), // the engine pre-filters; you validate untrusted records\n applyDeletions: (deletions) => removeLocal(deletions),\n clearDeletions: (deletions) => dropTombstones(deletions),\n loadState: () => readSyncState(),\n saveState: (state) => writeSyncState(state),\n};\n\nconst sync = createSync({ gateway, port });\nsync.tap((event) => console.debug('sync', event)); // observe pushes, pulls, warnings\nmyStore.subscribe(() => sync.changed()); // a local write happened\n\n// On account switch or teardown: after flushing this account's work:\nawait sync.flush();\nsync.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createSync()`**: drives a port against a gateway with a serialized push queue.\n- **`SyncPort`**: the server seam: `pull(since)` and `push(records, deletions)`.\n- **`SyncGateway`**: the storage seam: upserts, tombstones, and the persisted baseline: the engine owns every rev comparison.\n- **`rev` baselines**: a record is dirty exactly when its rev is above the last-synced one, across reloads.\n- **`changed()`**: wire it to your write path; the engine debounces a burst into one push.\n- **`flush()`**: a full cycle on demand: pull remote changes, then push dirty records; rejects on failure.\n- **Hide-flows**: flushes with `keepalive` on `pagehide`/`hidden`, runs a full cycle on return to the foreground.\n- **`tap()`**: typed `TandemEvent`s for pushes, pulls, invalid records, and warnings.\n- **Lifecycle-owned**: `dispose()`, `disposed`, `disposalSignal`, and `[Symbol.dispose]`; post-dispose `changed()`/`flush()` fail with `TandemDisposedError`.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Vault](/vault/): the typed storage core most gateways wrap; its IndexedDB adapter is a natural `records()`/`applyRecords()` backend.\n- [Postmaster](/postmaster/): the durable outbox half of offline sync; pair it with Tandem for at-least-once mutations alongside state sync.\n- [Sentinel](/sentinel/): subscribable browser state; its network signal can gate when you call `flush()`.\n- [Ripple](/ripple/): signals and effects; `store.subscribe(() => sync.changed())` is the usual wiring.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Tandem: API Reference'\ndescription: Factory, port and gateway contracts, events, and types for Tandem.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| -------------- | ------------------------------------------ | ------------------------ | ----------------------------------------------------------- |\n| `createSync()` | Scheduler driving a port against a gateway | Sync (queues async work) | Boot runs pull-then-push; dispose before switching accounts |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | --------------------------------------------------------------------------------------------- |\n| `@vielzeug/tandem` | `createSync`, `TandemError`, `TandemDisposedError`, port/gateway contracts, events, and types |\n\n## Factories\n\n### `createSync()`\n\n```ts\nfunction createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle;\n```\n\nStarts a sync scheduler: it loads the persisted baseline, pulls remote changes, pushes anything dirty, then flushes on `changed()`, on tab hide, and on foreground return.\n\n| Parameter | Type | Description
|
|
6
|
-
"usage": "---\ntitle: 'Tandem: Usage Guide'\ndescription: 'How to drive offline sync with @vielzeug/tandem: ports, gateways, rev baselines, tombstones, and reconciliation.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nTandem sits between your storage and your server. You implement two interfaces and call `createSync`; the engine handles batching, dirty tracking, hide-flows, and conflict reconcile.\n\n```ts\nimport { createSync, type SyncGateway, type SyncPort } from '@vielzeug/tandem';\n\ninterface Doc {\n id: string;\n rev: number;\n title: string;\n}\n\nconst port: SyncPort<Doc> = {\n async pull(since) {\n return fetch(`/sync/pull?since=${since ?? ''}`).then((response) => response.json());\n },\n async push(records, deletions, options) {\n const response = await fetch('/sync/push', {\n body: JSON.stringify({ records, deletions }),\n headers: { 'Content-Type': 'application/json' },\n keepalive: options?.keepalive,\n method: 'POST',\n });\n if (!response.ok) throw new Error(`server diverged: ${await response.text()}`);\n },\n};\n\nconst gateway: SyncGateway<Doc> = {\n records: () => docs.map((record) => ({ entity: 'docs', record })),\n pendingDeletions: () => readTombstones(),\n async applyRecords(pulled) {\n // The engine already filtered these to records the server is ahead on;\n // validate the untrusted remotes and upsert the rest.\n const skipped: string[] = [];\n for (const { record } of pulled) {\n if (!isValid(record)) skipped.push(record.id);\n else upsert(record);\n }\n return skipped;\n },\n applyDeletions: (deletions) => Promise.all(deletions.map((d) => remove(d.id))),\n clearDeletions: (deletions) => Promise.all(deletions.map((d) => dropTombstone(d.id))),\n loadState: () => readRow('syncState'),\n saveState: (state) => writeRow('syncState', state),\n};\n\nconst sync = createSync<Doc>({ gateway, port });\n```\n\n## Track Dirty Records with Revs\n\nTandem never diffs record contents. Each record carries a `rev` counting its committed writes, and the gateway persists a baseline of the newest rev the server has seen. A record is dirty exactly when its current rev is above that baseline.\n\n```ts\n// Your write path bumps the rev on every committed change.\nfunction saveDoc(id: string, patch: Partial<Doc>): void {\n const current = docs.find((doc) => doc.id === id)!;\n upsert({ ...current, ...patch, rev: current.rev + 1 });\n sync.changed(); // schedule a flush\n}\n```\n\nBecause the baseline is persisted, dirtiness survives a reload: a record edited while offline is still above the baseline when the app restarts, and the boot sequence pushes it. The engine never asks your gateway to compare revs: ahead, dirty, and deletion precedence are all its decisions.\n\n## Propagate Deletions with Tombstones\n\nA plain pull cannot carry a deletion: the record is gone. Record a tombstone when you delete locally; Tandem pushes it and clears it only once the server acknowledges.\n\n```ts\nfunction deleteDoc(id: string): void {\n remove(id);\n writeTombstone({ deletedAt: new Date().toISOString(), entity: 'docs', id });\n sync.changed();\n}\n```\n\nA remote deletion loses to a local record with unpushed changes: if your local rev is above the baseline, Tandem keeps your edit and pushes it instead of applying the deletion. The guard runs both ways: a pulled record whose id is locally tombstoned, or deleted in the same pull, never applies, so a backend without an incremental cursor cannot resurrect your deletions.\n\n## Batch Changes and Flush\n\nCall `changed()` on every local write. The engine debounces a burst into one push after `idleDelayMs` (default 3000), and serializes pushes so two never overlap.\n\n```ts\nconst sync = createSync({ gateway, idleDelayMs: 1500, port });\n\n// Force a full cycle now: on a save button, or before navigating away.\ntry {\n await sync.flush();\n} catch {\n // the cycle failed: edits stay local and dirty; the next cycle retries them\n}\n```\n\n`flush()` pulls remote changes and then pushes dirty records, so it is also the wiring point for a returning network connection. It rejects when either half fails; the records stay dirty and the next cycle retries them. After `dispose()`, `flush()` rejects with `TandemDisposedError` and `changed()` throws it: a leaked scheduler fails loudly instead of silently stopping. If your reactive wiring can fire after disposal, unsubscribe from your store before disposing the handle, or guard with `sync.disposed`.\n\nTandem also flushes on its own: it pushes with `keepalive: true` when the tab hides or closes, and runs a full cycle when the tab returns to the foreground. Serve the keepalive push with `navigator.sendBeacon` or a `keepalive` fetch so it survives the tab closing.\n\n## Reconcile a Rejected Push\n\nWhen the server is ahead of the lineage you pushed, reject the push. Tandem immediately pulls to reconcile, then the next flush retries with the merged state. Ambient flushes (debounce, hide) report the failure as a `warning` event; `flush()` additionally rejects with the port's error.\n\n```ts\nasync push(records, deletions) {\n const response = await fetch('/sync/push', { body: JSON.stringify({ records, deletions }), method: 'POST' });\n if (response.status === 409) throw new Error('server ahead'); // triggers a reconcile pull\n}\n```\n\n## Observe with tap()\n\n`tap()` is the observation seam: pushes, pulls, refused records, and warnings. Handler errors are swallowed, so an observer never breaks sync.\n\n```ts\nconst unsubscribe = sync.tap((event) => {\n switch (event.type) {\n case 'push':\n case 'pull':\n console.debug(`sync ${event.type}: ${event.records} records`);\n break;\n case 'invalid':\n console.warn(event.message, event.skipped);\n break;\n case 'warning':\n console.warn(event.message, event.error); // push rejected, network failure, etc.\n break;\n }\n});\n```\n\n## Lifecycle and Disposal\n\nDispose before switching accounts: the baseline is per-account state and a running scheduler would push into the wrong port.\n\n```ts\nconst sync = createSync({ gateway, port });\n// ...\nsync.dispose(); // stops the scheduler, clears the timer, removes document/window listeners\n```\n\n`disposed` and `disposalSignal` report the state; `[Symbol.dispose]` lets you scope it with `using`.\n\n```ts\n{\n using sync = createSync({ gateway, port });\n sync.changed();\n} // disposed here\n```\n\n## Testing\n\nDrive the engine against in-memory doubles. A `SyncPort` double records pushes and returns scripted pulls; a `SyncGateway` double is a record array plus a tombstone list plus a state row.\n\n```ts\nimport { createSync } from '@vielzeug/tandem';\n\nconst pushes: unknown[][] = [];\nconst port: SyncPort = {\n pull: async () => ({ cursor: null, deletions: [], records: [] }),\n push: async (records, deletions) => void pushes.push([records, deletions]),\n};\n\nconst sync = createSync({ gateway: fakeGateway, idleDelayMs: 10, port });\nawait vi.waitFor(() => expect(pushes.length).toBe(1)); // startup push\nsync.dispose();\n```\n\n## Framework Integration\n\nTandem is framework-neutral. Wire `changed()` to your reactive layer and `dispose()` to the component or scope lifecycle.\n\n::: code-group\n\n```ts [Vue 3]\nimport { onScopeDispose, watch } from 'vue';\n\nconst sync = createSync({ gateway, port });\nwatch(store.records, () => sync.changed(), { deep: true });\nonScopeDispose(() => sync.dispose());\n```\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\n\nconst syncRef = useRef(createSync({ gateway, port }));\nuseEffect(() => {\n const sync = syncRef.current;\n return () => sync.dispose();\n}, []);\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onDestroy } from 'svelte';\n const sync = createSync({ gateway, port });\n $effect(() => { $records; sync.changed(); });\n onDestroy(() => sync.dispose());\n</script>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n- **Vault**: the usual `gateway` backend. Its IndexedDB adapter stores records and the sync-state row; `records()` reads them from storage (it may be async), `applyRecords()` writes through the codec.\n- **Postmaster**: complementary, not overlapping. Postmaster guarantees at-least-once delivery of discrete mutations; Tandem keeps whole-record state in step. Apps that need both run them side by side.\n- **Sentinel**: subscribe to `createNetwork()` and call `sync.flush()` when the connection returns; the cycle pulls and pushes, so remote changes land without waiting for the next foreground return.\n- **Ripple**: `store.subscribe(() => sync.changed())` is the idiomatic wiring for a signal-backed store.\n\n## Best Practices\n\n- Bump `rev` on every committed write: the whole dirty model depends on it.\n- Validate remote records in `applyRecords()` and return the ids you refuse; never trust a pulled record.\n- Keep `records()` free of remote session mirrors: it must return only this device's own records.\n- Dispose on account switch; a stale scheduler pushes into the wrong port.\n- Serve `keepalive` pushes with `sendBeacon` or a `keepalive` fetch so they survive tab close.\n- Reject a push on divergence instead of silently overwriting; let the reconcile pull merge.\n- Persist the sync-state row per account, alongside the records it describes.\n- Call `flush()` before actions that assume both sides are current, such as a share or export, and handle its rejection.\n",
|
|
4
|
+
"index": "---\ntitle: 'Tandem: Offline-first sync engine'\ndescription: Offline-first sync engine with rev baselines, tombstoned deletions, and idle-batched pushes for browser applications.\npackage: tandem\ncategory: sync\nkeywords: [sync, offline, conflict, tombstone, rev, replication, last-write-wins]\nrelated: [vault, postmaster, sentinel, ripple]\nexports: [createSync, SyncPort, SyncGateway, SyncHandle, TandemEvent, TandemError, TandemDisposedError]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tandem\" />\n\n## Why Tandem?\n\nA local-first app keeps its records in IndexedDB but must still reach a server: batch bursts of edits into one upload, propagate deletions that a plain pull would resurrect, and reconcile two devices that edited the same record while offline. Tandem drives that round trip against any backend, tracking a per-record write counter so a push carries only what actually changed.\n\n```ts\n// Before\n// Hand-rolled: debounce each save, POST the whole table, hope deletions survive.\nlet timer;\nfunction onSave(record) {\n clearTimeout(timer);\n timer = setTimeout(() => fetch('/sync', { method: 'POST', body: JSON.stringify(allRecords()) }), 3000);\n}\n\n// After\nimport { createSync } from '@vielzeug/tandem';\n\nconst sync = createSync({ gateway, port, idleDelayMs: 3000 });\nsync.changed(); // a local edit happened: the engine batches and pushes dirty records\n```\n\n| Feature | Tandem | RxSync | PowerSync |\n| --------------------------------------- | -------------------------------------------- | ----------------------------------- | ----------------------------------- |\n| Bundle size | <PackageInfo package=\"tandem\" type=\"size\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Zero runtime dependencies | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Backend-agnostic (bring your `port`) | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Storage-agnostic (bring your `gateway`) | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> |\n| Tombstoned deletions + rev conflicts | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> |\n\n<div class=\"decision-callout\">\n\n**Use `tandem` when** you already own a local store and a backend and want the sync scheduler: dirty tracking, batching, hide-flows, and conflict reconcile: without adopting a database or a server.\n\n**Consider `PowerSync` when** you want a managed sync service with its own SQLite client and server component rather than a scheduler over your existing storage.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/tandem\n```\n\n```sh [npm]\nnpm install @vielzeug/tandem\n```\n\n```sh [yarn]\nyarn add @vielzeug/tandem\n```\n\n:::\n\n## Quick Start\n\nImplement the two seams: a `SyncPort` for the server and a `SyncGateway` for local storage: then start the scheduler. Records are opaque to Tandem; it reads only `id` and `rev`, and every rev comparison is the engine's: the gateway upserts, validates, and tombstones.\n\n```ts\nimport { createSync, type SyncGateway, type SyncPort } from '@vielzeug/tandem';\n\nconst port: SyncPort = {\n pull: (since) => fetch(`/sync?since=${since ?? ''}`).then((r) => r.json()),\n push: async (records, deletions) => {\n const response = await fetch('/sync', { method: 'POST', body: JSON.stringify({ records, deletions }) });\n if (!response.ok) throw new Error(await response.text()); // divergence → the engine pulls to reconcile\n },\n};\n\nconst gateway: SyncGateway = {\n records: () => localRecords.map((record) => ({ entity: 'docs', record })),\n pendingDeletions: () => readTombstones(),\n applyRecords: (pulled) => upsert(pulled), // the engine pre-filters; you validate untrusted records\n applyDeletions: (deletions) => removeLocal(deletions),\n clearDeletions: (deletions) => dropTombstones(deletions),\n loadState: () => readSyncState(),\n saveState: (state) => writeSyncState(state),\n};\n\nconst sync = createSync({ gateway, port });\nsync.tap((event) => console.debug('sync', event)); // observe pushes, pulls, warnings\nmyStore.subscribe(() => sync.changed()); // a local write happened\n\n// On account switch or teardown: after flushing this account's work:\nawait sync.flush();\nsync.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createSync()`**: drives a port against a gateway with a serialized push queue.\n- **`SyncPort`**: the server seam: `pull(since)` and `push(records, deletions)`.\n- **`SyncGateway`**: the storage seam: upserts, tombstones, and the persisted baseline: the engine owns every rev comparison.\n- **`rev` baselines**: a record is dirty exactly when its rev is above the last-synced one, across reloads.\n- **`changed()`**: wire it to your write path; the engine debounces a burst into one push.\n- **`flush()`**: a full cycle on demand: pull remote changes, then push dirty records; rejects on failure.\n- **Hide-flows**: flushes with `keepalive` on `pagehide`/`hidden`, runs a full cycle on return to the foreground; `ambient: false` plus `autoStart: false` turn the scheduler into a pull-when-told engine for short-lived connections.\n- **`tap()`**: typed `TandemEvent`s for pushes, pulls, invalid records, and warnings.\n- **Lifecycle-owned**: `dispose()`, `disposed`, `disposalSignal`, and `[Symbol.dispose]`; post-dispose `changed()`/`flush()` fail with `TandemDisposedError`.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Vault](/vault/): the typed storage core most gateways wrap; its IndexedDB adapter is a natural `records()`/`applyRecords()` backend.\n- [Postmaster](/postmaster/): the durable outbox half of offline sync; pair it with Tandem for at-least-once mutations alongside state sync.\n- [Sentinel](/sentinel/): subscribable browser state; its network signal can gate when you call `flush()`.\n- [Ripple](/ripple/): signals and effects; `store.subscribe(() => sync.changed())` is the usual wiring.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: 'Tandem: API Reference'\ndescription: Factory, port and gateway contracts, events, and types for Tandem.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| -------------- | ------------------------------------------ | ------------------------ | ----------------------------------------------------------- |\n| `createSync()` | Scheduler driving a port against a gateway | Sync (queues async work) | Boot runs pull-then-push; dispose before switching accounts |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | --------------------------------------------------------------------------------------------- |\n| `@vielzeug/tandem` | `createSync`, `TandemError`, `TandemDisposedError`, port/gateway contracts, events, and types |\n\n## Factories\n\n### `createSync()`\n\n```ts\nfunction createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle;\n```\n\nStarts a sync scheduler: it loads the persisted baseline, pulls remote changes, pushes anything dirty, then flushes on `changed()`, on tab hide, and on foreground return. `autoStart: false` defers the opening cycle to the first explicit `flush()`; `ambient: false` drops the tab-lifecycle hooks.\n\n| Parameter | Type | Description |\n| --------------------- | ---------------------- | ------------------------------------------------------------------ |\n| `options.ambient` | `boolean \\| undefined` | Wire tab hide/close and foreground return to sync (default `true`) |\n| `options.autoStart` | `boolean \\| undefined` | Run a full cycle on creation (default `true`) |\n| `options.gateway` | `SyncGateway<TRecord>` | The device's storage seam |\n| `options.idleDelayMs` | `number \\| undefined` | Quiet period before a flush (default `3000`) |\n| `options.port` | `SyncPort<TRecord>` | The server seam |\n\n**Returns** a `SyncHandle`. Ambient flushes never reject: they surface failures as `warning` events through `tap()`. An explicit `flush()` rejects when its cycle fails.\n\n**Example**\n\n```ts\nimport { createSync } from '@vielzeug/tandem';\n\nconst sync = createSync({ gateway, idleDelayMs: 1500, port });\nsync.changed();\nawait sync.flush();\nsync.dispose();\n```\n\n#### `SyncHandle` methods\n\n| Member | Description |\n| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |\n| `changed()` | Notes a local change and (re)starts the idle flush timer; throws `TandemDisposedError` after `dispose` |\n| `dispose()` | Stops the scheduler, clears the timer, removes document/window listeners |\n| `disposed` | `true` once disposed |\n| `disposalSignal` | `AbortSignal` aborted on dispose |\n| `flush()` | Runs a full cycle: pull, then push; resolves when it completes, rejects when it fails, and rejects with `TandemDisposedError` after `dispose` |\n| `tap(handler, options?)` | Observes `TandemEvent`s; returns an unsubscribe function |\n| `[Symbol.dispose]()` | Calls `dispose()` for `using` scopes |\n\n## Contracts\n\n### `SyncPort`\n\nThe server seam. `pull(since)` returns remote records, remote deletions, and the next cursor. `push(records, deletions, options)` sends local changes; reject it when the server diverged so the engine pulls to reconcile. `options.keepalive` marks a flush that must survive the tab closing.\n\n### `SyncGateway`\n\nThe storage seam. The engine owns every rev comparison: it calls your gateway with the decisions already made.\n\n| Member | Contract |\n| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |\n| `records()` | This device's own records, remote mirrors excluded; sync or async, so a disk-backed gateway can read from storage instead of holding a mirror |\n| `pendingDeletions()` | Tombstones the server has not acknowledged |\n| `applyRecords(records)` | Upsert the given records: already filtered to what the server is ahead on; return the ids that failed validation |\n| `applyDeletions(deletions)` | Remove records deleted remotely |\n| `clearDeletions(deletions)` | Drop the given tombstones a successful push carried |\n| `loadState()` | The persisted `SyncState`, or `null` on a fresh device |\n| `saveState(state)` | Persist the baseline after a completed pull or push |\n\n## Events\n\n### `TandemEvent`\n\n```ts\ntype TandemEvent =\n | { readonly records: number; readonly type: 'pull' }\n | { readonly records: number; readonly type: 'push' }\n | { readonly message: string; readonly skipped: readonly string[]; readonly type: 'invalid' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' }\n | { readonly type: 'dispose' };\n```\n\n`invalid` reports record ids `applyRecords` refused; `warning` reports a rejected push or transport failure and carries the original cause in `error` beside its `message`; `pull` and `push` report the record counts applied and pushed. `dispose` fires once, before tappers are cleared.\n\n## Types\n\n### `SyncRecordBase`\n\n```ts\ninterface SyncRecordBase {\n readonly id: string;\n readonly rev: number;\n}\n```\n\nThe only shape Tandem reads from a record: identity and a write counter. `rev` is required: the dirty model is a rev comparison, so every synced record carries one from birth.\n\n### `SyncEnvelope`\n\n```ts\ninterface SyncEnvelope<TRecord extends SyncRecordBase = SyncRecordBase> {\n readonly entity: string;\n readonly record: TRecord;\n}\n```\n\nA record paired with the entity (table or kind) it belongs to.\n\n### `SyncDeletion`\n\n```ts\ninterface SyncDeletion {\n readonly deletedAt?: string;\n readonly entity: string;\n readonly id: string;\n}\n```\n\nA tombstone: a deletion that travels to the server on the next push. `deletedAt` is set by whoever recorded the deletion and the engine never reads it: include it when your server wants the timestamp, omit it otherwise.\n\n### `SyncState`\n\n```ts\ninterface SyncState {\n cursor: string | null;\n revs: Record<string, number>;\n}\n```\n\nThe persisted baseline. `revs` maps `\"${entity}:${id}\"` to the newest rev the server has seen.\n\n### `SyncPullResult`\n\n```ts\ninterface SyncPullResult<TRecord extends SyncRecordBase = SyncRecordBase> {\n readonly cursor: string | null;\n readonly deletions: readonly SyncDeletion[];\n readonly records: readonly SyncEnvelope<TRecord>[];\n}\n```\n\n### `SyncOptions`\n\n```ts\ninterface SyncOptions<TRecord extends SyncRecordBase = SyncRecordBase> {\n ambient?: boolean;\n autoStart?: boolean;\n gateway: SyncGateway<TRecord>;\n idleDelayMs?: number;\n port: SyncPort<TRecord>;\n}\n```\n\n## Errors\n\n### `TandemError`\n\n```ts\nclass TandemError extends Error {}\n```\n\nBase class for every error Tandem throws; `instanceof TandemError` catches them all in one branch.\n\n### `TandemDisposedError`\n\n```ts\nclass TandemDisposedError extends TandemError {}\n```\n\nThrown by `changed()` and rejected by `flush()` after `dispose()`. A scheduler that stops silently is a sync engine's worst failure: the device keeps editing while nothing uploads, so a leaked handle fails loudly instead.\n\nBeyond disposal, Tandem defines no error classes. A rejected `push` is expected input, not a failure: the engine pulls to reconcile and reports it as a `warning` event. `flush()` additionally rejects with the underlying port or gateway error; dirty records survive the failure and retry on the next cycle.\n",
|
|
6
|
+
"usage": "---\ntitle: 'Tandem: Usage Guide'\ndescription: 'How to drive offline sync with @vielzeug/tandem: ports, gateways, rev baselines, tombstones, and reconciliation.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nTandem sits between your storage and your server. You implement two interfaces and call `createSync`; the engine handles batching, dirty tracking, hide-flows, and conflict reconcile.\n\n```ts\nimport { createSync, type SyncGateway, type SyncPort } from '@vielzeug/tandem';\n\ninterface Doc {\n id: string;\n rev: number;\n title: string;\n}\n\nconst port: SyncPort<Doc> = {\n async pull(since) {\n return fetch(`/sync/pull?since=${since ?? ''}`).then((response) => response.json());\n },\n async push(records, deletions, options) {\n const response = await fetch('/sync/push', {\n body: JSON.stringify({ records, deletions }),\n headers: { 'Content-Type': 'application/json' },\n keepalive: options?.keepalive,\n method: 'POST',\n });\n if (!response.ok) throw new Error(`server diverged: ${await response.text()}`);\n },\n};\n\nconst gateway: SyncGateway<Doc> = {\n records: () => docs.map((record) => ({ entity: 'docs', record })),\n pendingDeletions: () => readTombstones(),\n async applyRecords(pulled) {\n // The engine already filtered these to records the server is ahead on;\n // validate the untrusted remotes and upsert the rest.\n const skipped: string[] = [];\n for (const { record } of pulled) {\n if (!isValid(record)) skipped.push(record.id);\n else upsert(record);\n }\n return skipped;\n },\n applyDeletions: (deletions) => Promise.all(deletions.map((d) => remove(d.id))),\n clearDeletions: (deletions) => Promise.all(deletions.map((d) => dropTombstone(d.id))),\n loadState: () => readRow('syncState'),\n saveState: (state) => writeRow('syncState', state),\n};\n\nconst sync = createSync<Doc>({ gateway, port });\n```\n\n## Track Dirty Records with Revs\n\nTandem never diffs record contents. Each record carries a `rev` counting its committed writes, and the gateway persists a baseline of the newest rev the server has seen. A record is dirty exactly when its current rev is above that baseline.\n\n```ts\n// Your write path bumps the rev on every committed change.\nfunction saveDoc(id: string, patch: Partial<Doc>): void {\n const current = docs.find((doc) => doc.id === id)!;\n upsert({ ...current, ...patch, rev: current.rev + 1 });\n sync.changed(); // schedule a flush\n}\n```\n\nBecause the baseline is persisted, dirtiness survives a reload: a record edited while offline is still above the baseline when the app restarts, and the boot sequence pushes it. The engine never asks your gateway to compare revs: ahead, dirty, and deletion precedence are all its decisions.\n\n## Propagate Deletions with Tombstones\n\nA plain pull cannot carry a deletion: the record is gone. Record a tombstone when you delete locally; Tandem pushes it and clears it only once the server acknowledges.\n\n```ts\nfunction deleteDoc(id: string): void {\n remove(id);\n writeTombstone({ deletedAt: new Date().toISOString(), entity: 'docs', id });\n sync.changed();\n}\n```\n\nA remote deletion loses to a local record with unpushed changes: if your local rev is above the baseline, Tandem keeps your edit and pushes it instead of applying the deletion. The guard runs both ways: a pulled record whose id is locally tombstoned, or deleted in the same pull, never applies, so a backend without an incremental cursor cannot resurrect your deletions.\n\n## Batch Changes and Flush\n\nCall `changed()` on every local write. The engine debounces a burst into one push after `idleDelayMs` (default 3000), and serializes pushes so two never overlap.\n\n```ts\nconst sync = createSync({ gateway, idleDelayMs: 1500, port });\n\n// Force a full cycle now: on a save button, or before navigating away.\ntry {\n await sync.flush();\n} catch {\n // the cycle failed: edits stay local and dirty; the next cycle retries them\n}\n```\n\n`flush()` pulls remote changes and then pushes dirty records, so it is also the wiring point for a returning network connection. It rejects when either half fails; the records stay dirty and the next cycle retries them. After `dispose()`, `flush()` rejects with `TandemDisposedError` and `changed()` throws it: a leaked scheduler fails loudly instead of silently stopping. If your reactive wiring can fire after disposal, unsubscribe from your store before disposing the handle, or guard with `sync.disposed`.\n\nTandem also flushes on its own: it pushes with `keepalive: true` when the tab hides or closes, and runs a full cycle when the tab returns to the foreground. Serve the keepalive push with `navigator.sendBeacon` or a `keepalive` fetch so it survives the tab closing.\n\nFor a connection that cannot survive an ambient flush, both behaviors are options: `ambient: false` drops the tab-lifecycle hooks, and `autoStart: false` defers the opening cycle to your first `flush()` call. The boot job still loads the persisted baseline, so dirt detection works from the first tick:\n\n```ts\nconst sync = createSync({ ambient: false, autoStart: false, gateway, port });\n\n// Pull and push only when the app says the connection is ready:\nawait sync.flush();\n```\n\n## Reconcile a Rejected Push\n\nWhen the server is ahead of the lineage you pushed, reject the push. Tandem immediately pulls to reconcile, then the next flush retries with the merged state. Ambient flushes (debounce, hide) report the failure as a `warning` event; `flush()` additionally rejects with the port's error.\n\n```ts\nasync push(records, deletions) {\n const response = await fetch('/sync/push', { body: JSON.stringify({ records, deletions }), method: 'POST' });\n if (response.status === 409) throw new Error('server ahead'); // triggers a reconcile pull\n}\n```\n\n## Observe with tap()\n\n`tap()` is the observation seam: pushes, pulls, refused records, and warnings. Handler errors are swallowed, so an observer never breaks sync.\n\n```ts\nconst unsubscribe = sync.tap((event) => {\n switch (event.type) {\n case 'push':\n case 'pull':\n console.debug(`sync ${event.type}: ${event.records} records`);\n break;\n case 'invalid':\n console.warn(event.message, event.skipped);\n break;\n case 'warning':\n console.warn(event.message, event.error); // push rejected, network failure, etc.\n break;\n }\n});\n```\n\n## Lifecycle and Disposal\n\nDispose before switching accounts: the baseline is per-account state and a running scheduler would push into the wrong port.\n\n```ts\nconst sync = createSync({ gateway, port });\n// ...\nsync.dispose(); // stops the scheduler, clears the timer, removes document/window listeners\n```\n\n`disposed` and `disposalSignal` report the state; `[Symbol.dispose]` lets you scope it with `using`.\n\n```ts\n{\n using sync = createSync({ gateway, port });\n sync.changed();\n} // disposed here\n```\n\n## Testing\n\nDrive the engine against in-memory doubles. A `SyncPort` double records pushes and returns scripted pulls; a `SyncGateway` double is a record array plus a tombstone list plus a state row.\n\n```ts\nimport { createSync } from '@vielzeug/tandem';\n\nconst pushes: unknown[][] = [];\nconst port: SyncPort = {\n pull: async () => ({ cursor: null, deletions: [], records: [] }),\n push: async (records, deletions) => void pushes.push([records, deletions]),\n};\n\nconst sync = createSync({ gateway: fakeGateway, idleDelayMs: 10, port });\nawait vi.waitFor(() => expect(pushes.length).toBe(1)); // startup push\nsync.dispose();\n```\n\n## Framework Integration\n\nTandem is framework-neutral. Wire `changed()` to your reactive layer and `dispose()` to the component or scope lifecycle.\n\n::: code-group\n\n```ts [Vue 3]\nimport { onScopeDispose, watch } from 'vue';\n\nconst sync = createSync({ gateway, port });\nwatch(store.records, () => sync.changed(), { deep: true });\nonScopeDispose(() => sync.dispose());\n```\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\n\nconst syncRef = useRef(createSync({ gateway, port }));\nuseEffect(() => {\n const sync = syncRef.current;\n return () => sync.dispose();\n}, []);\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onDestroy } from 'svelte';\n const sync = createSync({ gateway, port });\n $effect(() => { $records; sync.changed(); });\n onDestroy(() => sync.dispose());\n</script>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n- **Vault**: the usual `gateway` backend. Its IndexedDB adapter stores records and the sync-state row; `records()` reads them from storage (it may be async), `applyRecords()` writes through the codec.\n- **Postmaster**: complementary, not overlapping. Postmaster guarantees at-least-once delivery of discrete mutations; Tandem keeps whole-record state in step. Apps that need both run them side by side.\n- **Sentinel**: subscribe to `createNetwork()` and call `sync.flush()` when the connection returns; the cycle pulls and pushes, so remote changes land without waiting for the next foreground return.\n- **Ripple**: `store.subscribe(() => sync.changed())` is the idiomatic wiring for a signal-backed store.\n\n## Best Practices\n\n- Bump `rev` on every committed write: the whole dirty model depends on it.\n- Validate remote records in `applyRecords()` and return the ids you refuse; never trust a pulled record.\n- Keep `records()` free of remote session mirrors: it must return only this device's own records.\n- Dispose on account switch; a stale scheduler pushes into the wrong port.\n- Serve `keepalive` pushes with `sendBeacon` or a `keepalive` fetch so they survive tab close.\n- Reject a push on divergence instead of silently overwriting; let the reconcile pull merge.\n- Persist the sync-state row per account, alongside the records it describes.\n- Call `flush()` before actions that assume both sides are current, such as a share or export, and handle its rejection.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Tandem: Examples'\ndescription: Offline sync recipes for two-device editing, deletions, and account switching.\n---\n\n## Examples\n\n- [Sync a Vault Store](./examples/sync-a-vault-store.md)\n- [Make Store Commands Undoable](./examples/make-store-commands-undoable.md)\n- [Keep Deletions from Resurrecting](./examples/keep-deletions-from-resurrecting.md)\n- [Switch Accounts Safely](./examples/switch-accounts-safely.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"apiSource": "// Public root surface of @vielzeug/tavern. Every public export goes through this file.\n\n// The mesh peer rides tavern's own event payloads; re-exported so the tavern import\n// alone types them.\nexport type { MeshPeer } from '@vielzeug/mesh';\nexport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nexport { joinTavern } from './guest';\nexport { hostTavern } from './host';\nexport type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: Tavern\ndescription: 'Table sessions over mesh: host-owned state replication with guest command forwarding'\npackage: tavern\ncategory: utilities\nkeywords: [session, host, guest, replication, mesh, commands, snapshots, collaboration, peer-to-peer]\nexports:\n [\n hostTavern,\n joinTavern,\n TavernCommand,\n TavernCommands,\n TavernSubject,\n TavernHost,\n TavernHostOptions,\n TavernHostEvent,\n TavernGuest,\n TavernGuestOptions,\n TavernGuestEvent,\n TavernJoinResult,\n TavernError,\n TavernPairingError,\n TavernDisposedError,\n ]\nrelated: [mesh, ledger, herald]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tavern\" />\n\n## Why Tavern?\n\nPeer-to-peer apps share one arrangement problem: the canonical state of something: a document, a dashboard, a record: lives on exactly one device, while every other participant should see it and be able to change it from their own. Tavern turns that arrangement into a session: **one host owns the canonical state, guests mirror it, and every guest command is forwarded through the host's own command table**, so remote actions follow exactly the same code path as local ones.\n\n```ts\n// Before: hand-rolled session orchestration: pairing, protocol validation,\n// command routing, snapshot broadcasting, notice relaying, presence tracking.\nconst host = createMeshHost({\n /* ... */\n});\nhost.on('command', ({ peerId, payload }) => {\n const command = mySchema.safeParse(payload);\n if (!command.success) {\n host.send(peerId, 'rejected', {\n /* ... */\n });\n return;\n }\n try {\n applySubjectCommand(command.data.name, subject, command.data.args);\n } catch (error) {\n host.send(peerId, 'rejected', {\n /* ... */\n });\n }\n});\nbus.on('subject:updated', () => {\n host.broadcast('snapshot', snapshotFor(subject));\n});\n// ... 40+ more lines of plumbing\n\n// After: tavern owns the protocol, the validation, the broadcasting.\nconst host = hostTavern({\n commands: { rename: (args) => store.rename(docId, args[0] as string) },\n subject: {\n onChanged: (listener) => store.onUpdated(docId, listener),\n onRemoved: (listener) => store.onRemoved(docId, listener),\n snapshot: () => store.read(docId),\n },\n});\n```\n\n| Feature | Tavern | Raw mesh | Socket.io rooms |\n| ------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"tavern\" type=\"size\" /> | <PackageInfo package=\"mesh\" type=\"size\" /> | N/A |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Host-authoritative commands | <ore-icon name=\"check\" size=\"16\"></ore-icon>: same table as local UI | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: wire it yourself | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: wire it yourself |\n| Snapshot replication | <ore-icon name=\"check\" size=\"16\"></ore-icon>: microtask-coalesced | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Out-of-band pairing (QR / copy-paste) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon>: needs a server |\n| Notice relaying | <ore-icon name=\"check\" size=\"16\"></ore-icon>: consumer-defined wire shape | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: server-mediated |\n\n<div class=\"decision-callout\">\n\n**Use Tavern when** one device should own the canonical state of something: a shared document, a live dashboard, a record under review, and every other device should mirror it and send commands back through the host's own command table, which stays the single validation path.\n\n**Consider raw `@vielzeug/mesh` when** you need P2P messaging without the host-authoritative replication model: chat, whiteboards, file transfer
|
|
4
|
+
"index": "---\ntitle: Tavern\ndescription: 'Table sessions over mesh: host-owned state replication with guest command forwarding'\npackage: tavern\ncategory: utilities\nkeywords: [session, host, guest, replication, mesh, commands, snapshots, collaboration, peer-to-peer]\nexports:\n [\n hostTavern,\n joinTavern,\n TavernCommand,\n TavernCommands,\n TavernSubject,\n TavernHost,\n TavernHostOptions,\n TavernHostEvent,\n TavernGuest,\n TavernGuestOptions,\n TavernGuestEvent,\n TavernJoinResult,\n TavernError,\n TavernPairingError,\n TavernDisposedError,\n ]\nrelated: [mesh, ledger, herald]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tavern\" />\n\n## Why Tavern?\n\nPeer-to-peer apps share one arrangement problem: the canonical state of something: a document, a dashboard, a record: lives on exactly one device, while every other participant should see it and be able to change it from their own. Tavern turns that arrangement into a session: **one host owns the canonical state, guests mirror it, and every guest command is forwarded through the host's own command table**, so remote actions follow exactly the same code path as local ones.\n\n```ts\n// Before: hand-rolled session orchestration: pairing, protocol validation,\n// command routing, snapshot broadcasting, notice relaying, presence tracking.\nconst host = createMeshHost({\n /* ... */\n});\nhost.on('command', ({ peerId, payload }) => {\n const command = mySchema.safeParse(payload);\n if (!command.success) {\n host.send(peerId, 'rejected', {\n /* ... */\n });\n return;\n }\n try {\n applySubjectCommand(command.data.name, subject, command.data.args);\n } catch (error) {\n host.send(peerId, 'rejected', {\n /* ... */\n });\n }\n});\nbus.on('subject:updated', () => {\n host.broadcast('snapshot', snapshotFor(subject));\n});\n// ... 40+ more lines of plumbing\n\n// After: tavern owns the protocol, the validation, the broadcasting.\nconst host = hostTavern({\n commands: { rename: (args) => store.rename(docId, args[0] as string) },\n subject: {\n onChanged: (listener) => store.onUpdated(docId, listener),\n onRemoved: (listener) => store.onRemoved(docId, listener),\n snapshot: () => store.read(docId),\n },\n});\n```\n\n| Feature | Tavern | Raw mesh | Socket.io rooms |\n| ------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"tavern\" type=\"size\" /> | <PackageInfo package=\"mesh\" type=\"size\" /> | N/A |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Host-authoritative commands | <ore-icon name=\"check\" size=\"16\"></ore-icon>: same table as local UI | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: wire it yourself | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: wire it yourself |\n| Snapshot replication | <ore-icon name=\"check\" size=\"16\"></ore-icon>: microtask-coalesced | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Out-of-band pairing (QR / copy-paste) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon>: needs a server |\n| Notice relaying | <ore-icon name=\"check\" size=\"16\"></ore-icon>: consumer-defined wire shape | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: server-mediated |\n\n<div class=\"decision-callout\">\n\n**Use Tavern when** one device should own the canonical state of something: a shared document, a live dashboard, a record under review, and every other device should mirror it and send commands back through the host's own command table, which stays the single validation path.\n\n**Consider raw `@vielzeug/mesh` when** you need P2P messaging without the host-authoritative replication model: chat, whiteboards, or custom topologies. Mesh carries bounded typed messages (capped by `maxMessageBytes`, 65 536 by default) with no chunking or acknowledgements: file transfer needs app-level chunking and acknowledgements built on top.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/tavern\n```\n\n```sh [npm]\nnpm install @vielzeug/tavern\n```\n\n```sh [yarn]\nyarn add @vielzeug/tavern\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { hostTavern, joinTavern } from '@vielzeug/tavern';\n\n// Host: wire the command table and snapshot access for the shared subject.\nconst host = hostTavern({\n commands: {\n rename: (args) => myStore.rename(docId, args[0] as string),\n append: (args) => myStore.append(docId, args[0] as string),\n },\n subject: {\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\n\n// Produce a single-use invitation code; deliver it out-of-band (QR, copy/paste).\nconst invitationCode = await host.createInvitationCode();\n\n// Guest: consume the invitation code, produce an answer code for the host.\nconst { answerCode, guest, ready } = await joinTavern({\n invitationCode,\n mount: (snapshot) => parseAndMount(snapshot),\n name: 'Alex',\n});\nawait host.acceptAnswerCode(answerCode);\n\n// `ready` settles once the first snapshot arrives and mounts: the mirror is live.\nawait ready;\n\n// The guest's commands run through the host's own table; their effect\n// arrives with the next snapshot, so a successful command needs no ack.\nguest.sendCommand('rename', ['Quarterly report']);\n\n// Cleanup: hosting ends for every guest; onEnded fires exactly once on both sides.\nhost.dispose();\nguest.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`hostTavern`**: host one subject: pairing, protocol validation, command application, coalesced snapshot broadcasts\n- **`joinTavern`**: join as a guest: consume the invitation code, produce the answer code, mirror the host's snapshots\n- **`TavernCommands`**: the host's command table as a plain record of handlers: the same functions the host's own UI calls, so remote actions cannot bypass validation\n- **`ready` promise**: the join lifecycle is awaitable: `ready` resolves with the mounted mirror or rejects with why the session never came up\n- **Coalesced snapshots**: bursts of local changes ship one snapshot per microtask, not one per change\n- **`onEnded` fires exactly once**: on both handles: channel drops, subject removal, and explicit disposal share a single idempotent cleanup path\n- **Typed errors**: `TavernPairingError` covers every unusable pasted code with the mesh failure chained as `cause`\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Mesh](/mesh/): the P2P transport underneath: WebRTC pairing, data channels, QR-optimized codecs.\n- [Ledger](/ledger/): undo/redo history for the commands the host applies.\n- [Herald](/herald/): typed event bus for the local notice stream tavern relays.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
5
|
"api": "---\ntitle: 'Tavern: API Reference'\ndescription: Public API of @vielzeug/tavern.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --------------------- | ---------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------- |\n| `hostTavern()` | Host a subject: pairing, command validation, snapshot broadcast | Sync factory | Disposing ends hosting for every guest |\n| `joinTavern()` | Join a session: consume invitation code, produce answer code | Async | The session lives only after the host accepts and the first snapshot mounts |\n| `TavernHost` | Host handle: invitation, answer acceptance, kick, notice relay, presence tap | N/A | `dispose()` is idempotent; control-plane methods throw `TavernDisposedError` after |\n| `TavernGuest` | Guest handle: command forwarding, rejection tap, disposal | N/A | `dispose()` fires `onEnded` exactly once |\n| `TavernJoinResult` | Join outcome: answer code, guest handle, and the `ready` promise | N/A | A `ready` nobody awaits never surfaces as an unhandled rejection |\n| `TavernHostEvent` | Host observability union for `tap()`: presence, warnings, dispose | N/A | Lifecycle transitions are `onEnded`, not events |\n| `TavernGuestEvent` | Guest observability union for `tap()`: rejections, warnings, dispose | N/A | The opening transition is `ready`, not an event |\n| `TavernCommands` | The host's command table: a record of handlers keyed by command name | N/A | A name the record does not hold rejects without applying |\n| `TavernSubject` | Snapshot reading, change and removal subscriptions | N/A | `snapshot` returning `null` skips the broadcast |\n| `TavernError` | Base error for every Tavern failure | N/A | N/A |\n| `TavernPairingError` | The consumer pasted the wrong kind of pairing code | N/A | N/A |\n| `TavernDisposedError` | A stopped host or ended guest was used again | N/A | N/A |\n\n## Package Entry Point\n\n| Import | Purpose |\n| -------------------------- | ----------------------------------------------- |\n| `@vielzeug/tavern` | Complete public Tavern API |\n| `@vielzeug/tavern/testing` | Test seam: the fake WebRTC factory for sessions |\n\nThe `MeshPeer` type carried by host events and the `peers` getter is re-exported here, so a single import types everything.\n\n## `hostTavern(options)`\n\nCreates a mesh host for one subject. Guest commands are validated against the wire shape (Tavern's own protocol) and checked against `commands`: a name the table does not hold rejects without applying, and a handler that throws rejects the guest with the error's message. Declaring `subject.id` makes the session _named_: every guest command must name that id as `sendCommand`'s `target`, and a command that omits or misses it rejects before the table runs. Local changes (via `subject.onChanged`) re-broadcast `subject.snapshot()`: coalesced on a microtask; `subject.onRemoved` ends hosting. Presence and transport warnings are reported through `tap()` as `TavernHostEvent`s, and the live peer list is the `peers` getter; hosting ending: from removal or `dispose()`: fires `onEnded` exactly once. `relayNotice` serializes through `serializeNotice` and broadcasts to every guest.\n\n**Returns:** `TavernHost`: the host handle.\n\n| Option | Type | Description |\n| ------------------ | ----------------------------- | ----------------------------------------------------------------------------- |\n| `commands?` | `TavernCommands` | The command table guest actions run through; omit for a read-only session |\n| `onEnded?` | `() => void` | Hosting ended: the subject was removed or `dispose()` ran. Fires exactly once |\n| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |\n| `serializeNotice?` | `(notice) => unknown \\| null` | Serializes a local notice for `relayNotice`; null skips that notice |\n| `subject` | `TavernSubject` | Snapshot reading, change and removal subscriptions for the hosted subject |\n\n**Example**\n\n```ts\nimport { hostTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n commands: {\n rename: (args) => myStore.rename(docId, args[0] as string),\n append: (args) => myStore.append(docId, args[0] as string),\n },\n subject: {\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\n```\n\n### `TavernHost` members\n\n| Member | Type | Behavior |\n| ------------------------ | -------------------------------- | ---------------------------------------------------------------------------------------- |\n| `acceptAnswerCode()` | `(code) => Promise<MeshPeer>` | Consumes a guest's answer code; resolves with the peer once the channel is open |\n| `createInvitationCode()` | `() => Promise<string>` | Produces a single-use invitation code, QR-compact when the environment allows |\n| `disposalSignal` | `AbortSignal` | Aborted when hosting ends |\n| `dispose()` | `() => void` | Stops hosting: closes every channel and detaches all subscriptions; idempotent |\n| `disposed` | `boolean` | Whether hosting has ended |\n| `kick()` | `(peerId) => void` | Disconnects one guest; the guest observes it and fires `onEnded` |\n| `peers` | `readonly MeshPeer[]` | The guests currently connected |\n| `relayNotice()` | `(notice) => void` | Broadcasts `serializeNotice(notice)` to every guest. Dropped after hosting ended |\n| `tap()` | `(handler, opts?) => () => void` | Subscribes to `TavernHostEvent`s; handler errors are swallowed; detaches on abort or end |\n| `[Symbol.dispose]()` | `() => void` | Delegates to `dispose()`; enables `using` declarations |\n\n## `joinTavern(options)`\n\nJoins a session as a guest: decodes the invitation code, opens the mesh guest, and returns the answer code to show back. Snapshots mount through `mount` as they arrive; the first non-null mount settles `ready`. The session ends exactly once: from the channel dropping (`TavernError`), an early exit before mounting (`TavernDisposedError`), or disposal.\n\n**Returns:** `Promise<TavernJoinResult<Mounted>>`: the answer code, the guest handle, and the `ready` promise. Rejects with `TavernPairingError` when the invitation code cannot be used.\n\n| Option | Type | Description |\n| ---------------- | ------------------------------- | --------------------------------------------------------------------------------------- |\n| `invitationCode` | `string` | The invitation code the host produced |\n| `mount` | `(snapshot) => Mounted \\| null` | Turns a received snapshot into the mounted mirror; null ignores it. Called per snapshot |\n| `name` | `string` | The guest's display name on the channel |\n| `onEnded?` | `(subject: Mounted) => void` | The channel ended after joining; receives the mounted subject for unmounting |\n| `onNotice?` | `(wire: unknown) => void` | Receives a notice the host relayed: re-emit it in the local UI |\n| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |\n\n**Example**\n\n```ts\nimport { joinTavern } from '@vielzeug/tavern';\n\nconst { answerCode, guest, ready } = await joinTavern({\n invitationCode,\n mount: (snapshot) => mySchema.parse(snapshot),\n name: 'Alex',\n onEnded: (subject) => unmountMirror(subject),\n});\nawait host.acceptAnswerCode(answerCode);\nawait ready; // the mirror is live\n```\n\n### `TavernJoinResult<Mounted>` members\n\n| Member | Type | Behavior |\n| ------------ | ------------------ | ------------------------------------------------------------------------------------------------ |\n| `answerCode` | `string` | The answer code to show back to the host, QR-compact when the environment allows |\n| `guest` | `TavernGuest` | The guest handle |\n| `ready` | `Promise<Mounted>` | Resolves with the mounted subject on the first mount; rejects with why the session never came up |\n\n### `TavernGuest` members\n\n| Member | Type | Behavior |\n| -------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |\n| `disposalSignal` | `AbortSignal` | Aborted when the session ends |\n| `dispose()` | `() => void` | Leaves the session; `onEnded` fires exactly once |\n| `disposed` | `boolean` | Whether the session has ended |\n| `sendCommand()` | `(name, args?, target?) => void` | Forwards a command to the host's table; `target` is required on a named session; throws `TavernDisposedError` after the session ended |\n| `tap()` | `(handler, opts?) => () => void` | Subscribes to `TavernGuestEvent`s; handler errors are swallowed; detaches on abort or end |\n| `[Symbol.dispose]()` | `() => void` | Delegates to `dispose()`; enables `using` declarations |\n\n## Types\n\n### `TavernCommands`\n\n```ts\ntype TavernCommand = (args: readonly unknown[]) => void;\ntype TavernCommands = Record<string, TavernCommand>;\n```\n\nThe host's command table, keyed by name: the same functions the host's own UI calls, so guest actions follow exactly the same validation path as local ones. A missing key rejects the guest with `The host has no command named \"...\"`; a throwing handler rejects with its message. Omit the table entirely for a read-only session.\n\n### `TavernSubject`\n\n```ts\ninterface TavernSubject {\n readonly id?: string;\n onChanged(listener: () => void): () => void;\n onRemoved(listener: () => void): () => void;\n snapshot(): unknown;\n}\n```\n\nHow the host reads and watches the single subject it shares. `onChanged` is the re-broadcast trigger; `onRemoved` ends hosting; `snapshot()` returns the JSON-serializable state to broadcast, or `null` while the subject is missing (the broadcast skips). A throwing `snapshot` is reported as a `warning` tap event instead of crashing the host. `id` is the subject's stable identity: declaring it puts every command under target verification: guests must pass the id as `sendCommand`'s `target`, and a missing or mismatched target rejects with `That command does not target the hosted subject.` before the command table runs. The target is a guest claim, not a proof: the guard catches misrouted commands, while handlers and the command table stay the authorization boundary. Omit `id` for anonymous sessions, where targets carry no meaning.\n\n### `TavernHostEvent`\n\n| Variant | Fires when |\n| -------------------------------------- | ---------------------------------------------------------- |\n| `{ type: 'peer-joined'; peer }` | A guest's channel opened |\n| `{ type: 'peer-left'; peer; reason? }` | A guest's channel closed |\n| `{ type: 'warning'; message; error }` | A transport error or a throwing snapshot read was survived |\n| `{ type: 'dispose' }` | Hosting ended and the tap stream is about to clear |\n\n### `TavernGuestEvent`\n\n| Variant | Fires when |\n| ------------------------------------------ | ------------------------------------------------------ |\n| `{ type: 'rejected'; commandId; message }` | The host rejected a forwarded command |\n| `{ type: 'warning'; message; error }` | A transport error was survived |\n| `{ type: 'dispose' }` | The session ended and the tap stream is about to clear |\n\n## Errors\n\n### `TavernError`\n\nBase class for every Tavern failure; `instanceof TavernError` narrows the whole hierarchy. Channel failures before the first snapshot reject `ready` with this class.\n\n### `TavernPairingError`\n\nThe code the consumer pasted could not be used: garbage, the wrong kind, an expired invitation, or an answer the host refuses. The underlying `@vielzeug/mesh` failure is chained as `cause`.\n\n### `TavernDisposedError`\n\nA stopped host or ended guest was used again: control-plane calls throw it so leaked handles surface, and it rejects `ready` when the guest leaves before the first snapshot.\n\n## Testing\n\n`@vielzeug/tavern/testing` re-exports `createFakeRtc()` (and the `FakeRtc` type): an in-process fake WebRTC factory you pass as the `rtc` option of `hostTavern` and `joinTavern` to drive a real host/guest pair inside one test process, with no browser or network. Consuming this subpath keeps mesh, tavern's transport, out of your dev dependencies.\n\n```ts\nimport { hostTavern, joinTavern } from '@vielzeug/tavern';\nimport { createFakeRtc } from '@vielzeug/tavern/testing';\n\nconst { rtc } = createFakeRtc();\nconst host = hostTavern({ rtc, subject });\nconst guest = await joinTavern({ invitationCode: await host.createInvitationCode(), mount, name, rtc });\n```\n",
|
|
6
6
|
"usage": "---\ntitle: 'Tavern: Usage Guide'\ndescription: How to use @vielzeug/tavern.\n---\n\n[[toc]]\n\n## Basic Usage\n\nHost one subject per session; guests join through the invitation/answer code pair. A session always carries exactly one subject: the guest handle needs no routing keys, and the host's command table is the single validation path for local and remote actions alike.\n\n```ts\nimport { hostTavern, joinTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n commands: { rename: (args) => myStore.rename(docId, args[0] as string) },\n subject: {\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\nconst invitationCode = await host.createInvitationCode();\n\nconst { answerCode, guest, ready } = await joinTavern({\n invitationCode,\n mount: (snapshot) => parseAndMount(snapshot),\n name: 'Alex',\n});\nawait host.acceptAnswerCode(answerCode);\nawait ready;\n\nguest.sendCommand('rename', ['Quarterly report']);\n```\n\n## Host a Subject\n\nThe host validates every guest command against its command table: a name the table does not hold rejects without applying, and a handler that throws rejects the guest with its message. The snapshot re-broadcasts on every local change: coalesced on a microtask, so bursts of changes ship one snapshot, not many. `onEnded` fires exactly once when hosting ends, whether the subject was removed or the host was disposed: reset your session UI there instead of intercepting your own `onRemoved` seam.\n\n```ts\nimport { hostTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n commands: {\n rename: (args) => myStore.rename(docId, args[0] as string),\n append: (args) => myStore.append(docId, args[0] as string),\n },\n onEnded: () => updateSessionUi(), // hosting ended: subject removed or disposed\n subject: {\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\n\n// Presence and transport warnings arrive through tap(); the peer list is a getter.\nhost.tap((event) => {\n if (event.type === 'peer-joined') toast(`${event.peer.name ?? 'A guest'} joined`);\n if (event.type === 'peer-left') toast(`${event.peer.name ?? 'A guest'} left`);\n if (event.type === 'warning') log.warn(event.message, event.error);\n updatePeerList(host.peers); // always current inside a presence event\n});\n\nconst invitationCode = await host.createInvitationCode();\n// Show the invitation code (QR or copy/paste); the guest returns an answer code.\nawait host.acceptAnswerCode(answerCode);\n\n// Kick a peer; the guest observes a disconnect and fires onEnded.\nhost.kick(peerId);\n\nhost.dispose(); // stop hosting: every guest disconnects\n```\n\nOmit `commands` for a read-only session: guests mirror the subject, and every command rejects with `The host has no command named \"...\"`.\n\n## Name the Subject to Guard Command Targets\n\nA guest tab can mirror more than one subject, so a command alone does not say enough: it must name what it acts on. Declaring `subject.id` makes tavern verify that: every command needs the hosted subject's id as `sendCommand`'s third argument, and a missing or mismatched `target` rejects with a `rejected` tap event before the command table ever runs. Without `id`, the session stays anonymous and targets carry no meaning.\n\n```ts\nconst host = hostTavern({\n commands: { rename: (args) => myStore.rename(docId, args[0] as string) },\n subject: {\n id: docId, // named session: guests must target this id\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\n\n// Guest side: the mirror knows which subject it is mirroring.\nguest.sendCommand('rename', ['Quarterly report'], docId);\n```\n\nThe guard stops honest misrouting: a stray command meant for another subject in a guest tab fails loudly instead of silently mutating the hosted one. It cannot make a paired guest honest: the target is a claim, not a proof, so handlers must keep acting on their own subject and the command table remains the authorization boundary for what guests may do.\n\n## Join as a Guest\n\nJoining consumes the invitation code and produces the answer code to show back. The session goes live once the host accepts the answer and the first snapshot mounts: that transition settles the `ready` promise, so there is no race between the handshake and your code attaching handlers.\n\n```ts\nimport { joinTavern } from '@vielzeug/tavern';\n\nconst { answerCode, guest, ready } = await joinTavern({\n invitationCode,\n mount: (snapshot) => sanitizeAndMount(snapshot),\n name: 'Alex',\n onEnded: (subject) => unmountMirror(subject.id),\n});\nguest.tap((event) => {\n if (event.type === 'rejected') showToast(event.message); // event.commandId names the command it answers\n if (event.type === 'warning') log.warn(event.message, event.error);\n});\n\ntry {\n await ready; // resolves with the mounted mirror once the first snapshot arrives\n} catch (error) {\n showError(error.message); // the channel failed, the host closed it, or the guest left early\n}\n\nguest.sendCommand('rename', ['New name']);\nguest.dispose(); // leave; onEnded fires with the mounted subject exactly once\n```\n\nThe snapshot arrives as parsed JSON: `mount` receives `unknown` and should validate before trusting it. It is called for every snapshot the host broadcasts. Returning `null` ignores one; the first non-null return becomes the mounted subject: it settles `ready` and is passed to `onEnded` when the session ends. A `ready` you never await is safe: its rejection is pre-handled and never surfaces as an unhandled rejection.\n\n## Relay Notices\n\nNotices are ephemeral out-of-band UI signals: a toast fired elsewhere, a comment added. Catalog keys rather than prose cross the wire, so each client translates locally. The host serializes its own notices with `serializeNotice` and relays them with `relayNotice`; guests receive them through `onNotice`.\n\n```ts\n// Host side: forward local notices through the session.\nconst host = hostTavern({\n /* ... */\n serializeNotice: (notice) => (isLocalNotice(notice) ? toWireShape(notice) : null),\n});\nhost.relayNotice(localNotice); // null from serializeNotice skips this one\n\n// Guest side: re-emit received notices in the local UI.\nconst { guest } = await joinTavern({\n /* ... */\n onNotice: (wire) => bus.emit('notify', wire),\n});\n```\n\n**Echo guard**: a tab that both hosts and guests must prevent re-broadcasting a wire-originated notice back to its own guests: `onNotice` emits locally, the host's local subscription picks it up, and without a guard it would loop. One boolean set during `onNotice` and checked in `serializeNotice` is sufficient: the consumer owns this because only they know their local event system.\n\n## Observe with tap()\n\nBoth handles expose `tap()` for observability: presence and warnings on the host, rejections and warnings on the guest. Handler errors are swallowed, and the subscription detaches when its signal aborts or the session ends. Lifecycle stays out of the observability stream: `ready` covers the opening transition on the guest, and `onEnded` covers the closing transition on both handles.\n\n```ts\nimport type { TavernGuestEvent, TavernHostEvent } from '@vielzeug/tavern';\n\nhost.tap((event: TavernHostEvent) => {\n if (event.type === 'warning') log.warn(event.message, event.error); // the original error, not just text\n if (event.type === 'dispose') log.info('hosting ended');\n});\nguest.tap((event: TavernGuestEvent) => {\n if (event.type === 'rejected') log.info(`command ${event.commandId} rejected: ${event.message}`);\n});\n```\n\n## Handle Pairing Mistakes\n\nEvery user-input pairing failure surfaces as `TavernPairingError` from both `acceptAnswerCode` and `joinTavern`: a garbage code, the wrong code kind, an expired invitation, or an answer the host refuses. Catch it to show a helpful message instead of a raw error; the underlying mesh failure is chained as `cause` when you need it.\n\n```ts\nimport { hostTavern, TavernPairingError } from '@vielzeug/tavern';\n\ntry {\n await host.acceptAnswerCode(pastedCode);\n} catch (error) {\n if (error instanceof TavernPairingError) {\n showToast(error.message); // \"That code is an invitation, not a guest answer.\"\n } else {\n throw error;\n }\n}\n```\n\n## Working with Other Vielzeug Libraries\n\nTavern builds on `@vielzeug/mesh` for the WebRTC transport, pairing codes, and QR-optimized codecs. You do not interact with mesh directly: tavern owns the protocol, but the `rtc` option accepts a `MeshRtcFactory` for testing or non-browser runtimes. The peers carried by tap events and the {@link TavernHost.peers} getter are mesh types, re-exported by tavern so one import types everything.\n\n```ts\nimport type { MeshRtcFactory } from '@vielzeug/mesh';\nimport { hostTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n // ... commands, subject\n rtc: myTestRtcFactory, // inject an in-memory WebRTC fake\n});\n```\n\nPair `@vielzeug/ledger` on the host to give the commands tavern applies an undo history: commands applied through the table land in the ledger like local ones.\n\n## Best Practices\n\n- Keep the command table the same functions the host's own UI calls, so guest actions cannot bypass local validation.\n- Return `null` from `snapshot` while the subject is missing: the broadcast simply skips.\n- Reset host-side session UI in `onEnded`: it fires exactly once for subject removal and explicit disposal alike, so you never need to double-wire your own `onRemoved` seam.\n- Await `ready` before trusting the mirror: it names the exact reason a session never came up, and its rejection is safe to ignore when you do not care.\n- Treat notices as catalog keys, not prose: each client translates locally.\n- Guard against notice echo if a tab can both host and guest: one boolean in `serializeNotice` is sufficient.\n- Dispose guests and hosts when their screen unmounts; channels also clean up on disconnect through `onEnded`, which fires exactly once on both sides.\n- Catch `TavernPairingError` separately from other errors: it means the pasted code could not be used, not that something is broken.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Tavern: Examples'\ndescription: Practical examples and recipes for @vielzeug/tavern.\n---\n\n## Examples\n\n- [Share State Across Devices](./examples/share-state-across-devices.md)\n"
|
|
8
8
|
},
|
|
9
|
-
"examples": [
|
|
9
|
+
"examples": [
|
|
10
|
+
{
|
|
11
|
+
"id": "session-basic",
|
|
12
|
+
"code": "import { hostTavern, joinTavern } from '@vielzeug/tavern'\n\n// In-memory WebRTC fake (same shape as the mesh example): tavern pairs over mesh.\nconst fakeRtc = (() => {\n const links = new Map()\n const bag = () => {\n const ls = new Map()\n return {\n addEventListener: (t, f) => ls.set(t, [...(ls.get(t) ?? []), f]),\n removeEventListener: (t, f) => ls.set(t, (ls.get(t) ?? []).filter((x) => x !== f)),\n emit: (t, e = {}) => (ls.get(t) ?? []).forEach((f) => f(e)),\n }\n }\n const channel = () =>\n Object.assign(bag(), {\n readyState: 'connecting',\n remote: null,\n send(data) {\n if (this.remote?.readyState === 'open') queueMicrotask(() => this.remote.emit('message', { data }))\n },\n open() {\n this.readyState = 'open'\n this.emit('open')\n },\n close() {\n if (this.readyState === 'closed') return\n this.readyState = 'closed'\n this.emit('close')\n this.remote?.close()\n },\n })\n const pc = (token) =>\n Object.assign(bag(), {\n connectionState: 'new',\n iceConnectionState: 'new',\n iceGatheringState: 'new',\n localDescription: null,\n createDataChannel() {\n this.dc = channel()\n return this.dc\n },\n createOffer() {\n links.set(token, { host: this })\n return Promise.resolve({ sdp: 'offer:' + token, type: 'offer' })\n },\n createAnswer() {\n const link = [...links.values()].find((l) => l.guest === this)\n return Promise.resolve({ sdp: 'answer:' + link.hostToken + ':' + token, type: 'answer' })\n },\n setLocalDescription(d) {\n this.localDescription = d\n this.iceGatheringState = 'complete'\n return Promise.resolve()\n },\n setRemoteDescription(d) {\n if (d.type === 'offer') {\n const hostToken = d.sdp.split(':')[1].trim()\n const link = links.get(hostToken)\n link.guest = this\n link.hostToken = hostToken\n return Promise.resolve()\n }\n const hostToken = d.sdp.replace('answer:', '').split(':')[0].trim()\n const link = links.get(hostToken)\n const guestChannel = channel()\n const hostChannel = link.host.dc\n hostChannel.remote = guestChannel\n guestChannel.remote = hostChannel\n link.guest.emit('datachannel', { channel: guestChannel })\n queueMicrotask(() => {\n hostChannel.open()\n guestChannel.open()\n })\n return Promise.resolve()\n },\n close() {\n this.dc?.close()\n },\n })\n let n = 0\n return { createPeerConnection: () => pc('pc' + ++n) }\n})()\n\n// The hosted subject: tavern reads snapshot(), re-broadcasts on onChanged, ends on onRemoved.\nfunction createStore(initial) {\n let state = initial\n const listeners = new Set()\n return {\n state: () => state,\n set(next) {\n state = next\n listeners.forEach((f) => f())\n },\n subject: {\n onChanged(listener) {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n onRemoved() {\n return () => {}\n },\n snapshot: () => state,\n },\n }\n}\n\nconst store = createStore({ hp: 20, log: [] })\n\n// The command table is the same code path the host's own UI would call.\nconst commands = {\n damage: ([amount]) => {\n const s = store.state()\n store.set({ hp: Math.max(0, s.hp - Number(amount)), log: [...s.log, 'hit for ' + amount] })\n },\n}\n\nconst host = hostTavern({ rtc: fakeRtc, subject: store.subject, commands })\nhost.tap((e) => {\n if (e.type === 'peer-joined') console.log('host: guest joined', e.peer.id)\n})\n\nconst invitationCode = await host.createInvitationCode()\n\nconst { guest, answerCode, ready } = await joinTavern({\n rtc: fakeRtc,\n invitationCode,\n name: 'Tablet',\n mount: (snapshot) => {\n console.log('guest mounted snapshot:', JSON.stringify(snapshot))\n return snapshot\n },\n})\n\nawait host.acceptAnswerCode(answerCode)\nawait ready\nconsole.log('session open, host peers:', host.peers.length)\n\n// Guest commands forward to the host's table; the effect arrives with the next snapshot.\nguest.sendCommand('damage', [7])\nawait new Promise((r) => setTimeout(r, 10))\n\nconsole.log('host state:', JSON.stringify(store.state()))\n\nguest.dispose()\nhost.dispose()\nconsole.log('disposed:', guest.disposed, host.disposed)",
|
|
13
|
+
"name": "Host & Guest Session"
|
|
14
|
+
}
|
|
15
|
+
],
|
|
10
16
|
"typeSignatures": {
|
|
11
17
|
"MeshPeer": "export type { MeshPeer } from '@vielzeug/mesh';",
|
|
12
18
|
"TavernDisposedError": "export { TavernDisposedError, TavernError, TavernPairingError } from './errors';",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vielzeug/codex",
|
|
3
|
-
"version": "26.11.
|
|
3
|
+
"version": "26.11.18",
|
|
4
4
|
"description": "MCP server exposing all Vielzeug docs to AI clients",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
54
|
"@types/node": "^26.6.6",
|
|
55
|
-
"@vielzeug/refine": "26.11.
|
|
55
|
+
"@vielzeug/refine": "26.11.18",
|
|
56
56
|
"typescript": "^6.0.3",
|
|
57
57
|
"vitest": "^5.1.0"
|
|
58
58
|
}
|
package/skills/vielzeug/SKILL.md
CHANGED
|
@@ -49,6 +49,7 @@ If a need matches a package below, use that package. Do not reimplement signals,
|
|
|
49
49
|
- `@vielzeug/archive`: Community content publishing for Cloudflare Workers + D1: a hardened Worker core over per-collection payload schemas
|
|
50
50
|
- `@vielzeug/arsenal`: Non-trivial TypeScript utilities: retry, cancellation, cache, safe-path, serialization, prototype-pollution-guarded collections
|
|
51
51
|
- `@vielzeug/assay`: Framework-agnostic DOM testing primitives: scoped queries, event dispatch, async waiting
|
|
52
|
+
- `@vielzeug/bard`: Lifecycle-owned Web Audio mixing: buses with ducking, buffered SFX and sprites, procedural synth, streamed tracks, and crossfading music decks
|
|
52
53
|
- `@vielzeug/beacon`: Guided onboarding and contextual product tours for web applications
|
|
53
54
|
- `@vielzeug/clockwork`: Framework-neutral finite state machines with pure transitions and actors
|
|
54
55
|
- `@vielzeug/coins`: Currency formatting and exchange utilities for monetary arithmetic
|