@vielzeug/codex 26.11.24 → 26.11.25
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/README.md +5 -4
- package/data/snapshot.json +1 -0
- package/dist/catalog.d.ts +35 -39
- package/dist/catalog.js +112 -139
- package/dist/catalog.js.map +1 -1
- package/dist/cli.js +25 -16
- package/dist/cli.js.map +1 -1
- package/dist/http.js +1 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +5 -7
- package/dist/index.js +4 -6
- package/dist/index.js.map +1 -1
- package/dist/server.d.ts +9 -7
- package/dist/server.js +14 -6
- package/dist/server.js.map +1 -1
- package/dist/snapshot.d.ts +8 -22
- package/dist/snapshot.js +41 -176
- package/dist/snapshot.js.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/packages.js +49 -82
- package/dist/tools/packages.js.map +1 -1
- package/dist/tools/refine.d.ts +1 -2
- package/dist/tools/refine.js +90 -82
- package/dist/tools/refine.js.map +1 -1
- package/dist/tools/schema.d.ts +2 -1
- package/dist/tools/schema.js +9 -5
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/shared.d.ts +2 -2
- package/dist/types.d.ts +77 -64
- package/dist/types.js +6 -2
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
- package/skills/vielzeug/SKILL.md +18 -20
- package/data/catalog.json +0 -2539
- package/data/llms-full.txt +0 -40978
- package/data/llms.txt +0 -60
- package/data/manifest.json +0 -4
- package/data/packages/archive.json +0 -87
- package/data/packages/arsenal.json +0 -270
- package/data/packages/assay.json +0 -52
- package/data/packages/atlas.json +0 -81
- package/data/packages/bard.json +0 -38
- package/data/packages/beacon.json +0 -51
- package/data/packages/clockwork.json +0 -69
- package/data/packages/codex.json +0 -37
- package/data/packages/coins.json +0 -99
- package/data/packages/conduit.json +0 -67
- package/data/packages/courier.json +0 -66
- package/data/packages/dnd.json +0 -60
- package/data/packages/familiar.json +0 -38
- package/data/packages/flux.json +0 -97
- package/data/packages/focus.json +0 -51
- package/data/packages/forge.json +0 -65
- package/data/packages/gesture.json +0 -65
- package/data/packages/herald.json +0 -80
- package/data/packages/illusionist.json +0 -132
- package/data/packages/ink.json +0 -41
- package/data/packages/keymap.json +0 -55
- package/data/packages/ledger.json +0 -60
- package/data/packages/lingua.json +0 -68
- package/data/packages/mesh.json +0 -52
- package/data/packages/necromancer.json +0 -55
- package/data/packages/orbit.json +0 -100
- package/data/packages/ore.json +0 -78
- package/data/packages/palette.json +0 -42
- package/data/packages/patchwork.json +0 -55
- package/data/packages/postmaster.json +0 -49
- package/data/packages/prism.json +0 -99
- package/data/packages/pulse.json +0 -71
- package/data/packages/refine.json +0 -36
- package/data/packages/ripple.json +0 -84
- package/data/packages/rune.json +0 -78
- package/data/packages/sandbox.json +0 -26
- package/data/packages/scout.json +0 -66
- package/data/packages/scribe.json +0 -57
- package/data/packages/scroll.json +0 -110
- package/data/packages/sentinel.json +0 -46
- package/data/packages/sigil.json +0 -52
- package/data/packages/sourcerer.json +0 -86
- package/data/packages/spell.json +0 -126
- package/data/packages/stage.json +0 -26
- package/data/packages/tabula.json +0 -39
- package/data/packages/tandem.json +0 -31
- package/data/packages/tavern.json +0 -34
- package/data/packages/tempo.json +0 -68
- package/data/packages/vault.json +0 -81
- package/data/packages/ward.json +0 -77
- package/data/packages/wayfinder.json +0 -126
- package/data/packages/wire.json +0 -51
- package/data/refine.json +0 -17277
- package/dist/consumer.d.ts +0 -17
- package/dist/consumer.js +0 -114
- package/dist/consumer.js.map +0 -1
- package/dist/port.d.ts +0 -2
- package/dist/port.js +0 -12
- package/dist/port.js.map +0 -1
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
{
|
|
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
|
-
"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, 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
|
-
"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
|
-
"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
|
-
"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
|
-
},
|
|
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
|
-
],
|
|
16
|
-
"typeSignatures": {
|
|
17
|
-
"MeshPeer": "export type { MeshPeer } from '@vielzeug/mesh';",
|
|
18
|
-
"TavernDisposedError": "export { TavernDisposedError, TavernError, TavernPairingError } from './errors';",
|
|
19
|
-
"TavernError": "export { TavernDisposedError, TavernError, TavernPairingError } from './errors';",
|
|
20
|
-
"TavernPairingError": "export { TavernDisposedError, TavernError, TavernPairingError } from './errors';",
|
|
21
|
-
"joinTavern": "export { joinTavern } from './guest';",
|
|
22
|
-
"hostTavern": "export { hostTavern } from './host';",
|
|
23
|
-
"TavernCommand": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
24
|
-
"TavernCommands": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
25
|
-
"TavernGuest": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
26
|
-
"TavernGuestEvent": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
27
|
-
"TavernGuestOptions": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
28
|
-
"TavernHost": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
29
|
-
"TavernHostEvent": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
30
|
-
"TavernHostOptions": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
31
|
-
"TavernJoinResult": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';",
|
|
32
|
-
"TavernSubject": "export type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';"
|
|
33
|
-
}
|
|
34
|
-
}
|
package/data/packages/tempo.json
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"apiSource": "// Tempo keeps this re-export so all consumers share one Temporal implementation and version.\nexport { Temporal } from '@js-temporal/polyfill';\nexport { toInstant, toZoned } from './_convert';\nexport { endOf, startOf } from './boundary';\nexport { isAfter, isBefore, isSame } from './compare';\nexport { difference, isValid, now, nowInstant, parse, shift } from './core';\nexport {\n CadenceError,\n TempoError,\n TempoInvalidInputError,\n TempoInvalidTzError,\n TempoMissingTzError,\n TempoUnsupportedInputError,\n} from './errors';\nexport {\n format,\n formatDuration,\n formatInstant,\n formatParts,\n formatRange,\n formatRangeParts,\n formatRelative,\n formatTimer,\n formatZoned,\n parseDuration,\n} from './format';\nexport type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';\n",
|
|
3
|
-
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Tempo: Temporal date and time utilities'\ndescription: Explicit Temporal parsing, timezone-safe arithmetic, and localized date/time formatting for TypeScript.\npackage: tempo\ncategory: time\nkeywords: [temporal, date-time, timezone, formatting, arithmetic, dst, intl]\nrelated: [rune, vault]\nexports:\n [\n Temporal,\n parse,\n now,\n nowInstant,\n isValid,\n toInstant,\n toZoned,\n shift,\n difference,\n isBefore,\n isAfter,\n isSame,\n startOf,\n endOf,\n format,\n formatParts,\n formatRange,\n formatRangeParts,\n formatInstant,\n formatZoned,\n formatRelative,\n parseDuration,\n formatDuration,\n formatTimer,\n TempoError,\n TempoInvalidInputError,\n TempoInvalidTzError,\n TempoMissingTzError,\n TempoUnsupportedInputError,\n ]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tempo\" />\n\n## Why Tempo?\n\nDate/time bugs come from treating an instant and a wall-clock value as interchangeable. Tempo requires an explicit parse target and requires `timeZone` whenever a wall-clock value becomes an instant.\n\n```ts\n// Before\nconst reminder = new Date(meeting.getTime() - 15 * 60_000);\n\n// After\nimport { parse, shift } from '@vielzeug/tempo';\n\nconst localMeeting = parse('2026-03-21T10:30:00', { as: 'plainDateTime' });\nconst reminder = shift(localMeeting, { minutes: -15 }, { timeZone: 'America/New_York' });\n```\n\n| Feature | Tempo | date-fns | Native Date |\n| ----------------------------- | ---------------------------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | <PackageInfo package=\"tempo\" type=\"size\" /> | ~10 kB | 0 kB |\n| Zero dependencies | <ore-icon name=\"x\" size=\"16\"></ore-icon> `@js-temporal/polyfill` | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Explicit wall-time conversion | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| DST-safe arithmetic | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual | Manual |\n| Localized formatting | <ore-icon name=\"check\" size=\"16\"></ore-icon> `Intl` | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Tempo when** you need Temporal values, explicit timezone rules, and DST-safe operations.\n\n**Consider native `Date` when** your data is only elapsed milliseconds and you do not need calendar or timezone behavior.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/tempo\n```\n\n```sh [npm]\nnpm install @vielzeug/tempo\n```\n\n```sh [yarn]\nyarn add @vielzeug/tempo\n```\n\n:::\n\n## Quick Start\n\nParse a wall-clock input explicitly, attach its timezone, then format it for a user.\n\n```ts\nimport { format, parse, shift } from '@vielzeug/tempo';\n\nconst localMeeting = parse('2026-03-21T10:30:00', { as: 'plainDateTime' });\nconst reminder = shift(localMeeting, { minutes: -15 }, { timeZone: 'America/New_York' });\nconst text = format(reminder, {\n locale: 'en-US',\n pattern: 'short',\n});\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `parse()`: Requires an explicit ISO target: instant, zoned date-time, plain date-time, or plain date.\n- `toInstant()` / `toZoned()`: Convert wall-clock and absolute values with explicit timezone semantics.\n- `shift()` / `difference()`: Apply DST-safe arithmetic across instant, zoned, and wall-clock inputs.\n- `startOf()` / `endOf()`: Resolve timezone-aware calendar boundaries, including configurable week starts.\n- `format()` / `formatRelative()` / `formatDuration()`: Render localized values through `Intl`, including calendar-aware relative months and years.\n- `formatTimer()`: Deterministic stopwatch clocks (`47:12`, `1:02:35`) for elapsed-time UI.\n- `@vielzeug/tempo/cadence`: RFC 5545 RRULE engine — parse, lazy DST-correct expansion, and `RDATE`/`EXDATE` merging.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [Cadence (RRULE)](./cadence.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Rune](/rune/): format stable Temporal timestamps before writing structured log records.\n- [Vault](/vault/): derive explicit expiry moments before storing records with TTL policies.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Tempo: API Reference'\ndescription: Reference for Tempo Temporal parsing, conversion, arithmetic, comparison, boundary, and formatting APIs.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --------------------------------------- | ---------------------------------------------- | -------------- | -------------------------------------------- |\n| `parse()` | Parse ISO text to an explicit Temporal kind | Sync | `as` is required |\n| `isValid()` | Narrow an unknown runtime value to `TimeInput` | Sync | Does not parse strings |\n| `toInstant()` | Resolve a value as an absolute instant | Sync | Plain values require `timeZone` |\n| `toZoned()` | Project a value to a zone | Sync | Preserves instant, changes wall-clock fields |\n| `shift()` / `difference()` | Timezone-aware arithmetic | Sync | Calendar operations require a timezone |\n| `isBefore()` / `isAfter()` / `isSame()` | Compare absolute values or calendar units | Sync | Plain values require `timeZone` |\n| `startOf()` / `endOf()` | Resolve calendar boundaries | Sync | Weeks default to Monday |\n| `format()` family | Localized and machine formatting | Sync | Use `timeZone`, not `tz` |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------------- | ---------------------------------------------------------------------------------------- |\n| `@vielzeug/tempo` | Tempo utilities, errors, types, and shared `Temporal` namespace |\n| `@vielzeug/tempo/cadence` | RFC 5545 recurrence: `parseCadence`, `toCadence`, `expandCadence`, `resolveCadenceDates` |\n\nCadence has its own reference: [Cadence](./cadence.md).\n\n## Core Functions\n\n### `parse(input, { as })`\n\n```ts\nparse(input: string, options: { as: 'instant' }): Temporal.Instant;\nparse(input: string, options: { as: 'zonedDateTime' }): Temporal.ZonedDateTime;\nparse(input: string, options: { as: 'plainDateTime' }): Temporal.PlainDateTime;\nparse(input: string, options: { as: 'plainDate' }): Temporal.PlainDate;\n```\n\nParses an ISO 8601 string as the requested temporal kind.\n\n**Parameters**\n\n| Parameter | Type | Description |\n| ------------ | --------- | -------------------- |\n| `input` | `string` | ISO 8601 input |\n| `options.as` | `ParseAs` | Required result kind |\n\n**Returns:** Requested Temporal value.\n\n**Example:**\n\n```ts\nimport { parse } from '@vielzeug/tempo';\n\nconst instant = parse('2026-03-21T10:15:30Z', { as: 'instant' });\n```\n\n---\n\n### `isValid(value)`\n\n```ts\nisValid(value: unknown): value is TimeInput;\n```\n\nReturns whether `value` is a Tempo-supported Temporal value. It does not parse ISO strings.\n\n**Example:**\n\n```ts\nimport { isValid, parse } from '@vielzeug/tempo';\n\nconst value: unknown = parse('2026-03-21T10:15:30Z', { as: 'instant' });\nconst valid = isValid(value); // true\n```\n\n---\n\n### `now({ timeZone })` / `nowInstant()`\n\n```ts\nnow(options: { timeZone: string }): Temporal.ZonedDateTime;\nnowInstant(): Temporal.Instant;\n```\n\nReturns current zoned or absolute time.\n\n**Example:**\n\n```ts\nimport { now, nowInstant } from '@vielzeug/tempo';\n\nnow({ timeZone: 'Europe/Berlin' });\nnowInstant();\n```\n\n---\n\n### `toInstant(input, options?)` / `toZoned(input, options)`\n\n```ts\ntoInstant(input: AbsoluteTime): Temporal.Instant;\ntoInstant(input: WallTime, options: { timeZone: string } & DisambiguationOptions): Temporal.Instant;\ntoZoned(input: TimeInput, options: { timeZone: string } & DisambiguationOptions): Temporal.ZonedDateTime;\n```\n\n`toInstant()` resolves wall-clock values to an absolute instant. `toZoned()` projects any value into a required timezone, preserving the instant.\n\n**Example:**\n\n```ts\nimport { parse, toInstant, toZoned } from '@vielzeug/tempo';\n\nconst local = parse('2026-11-01T01:30:00', { as: 'plainDateTime' });\nconst instant = toInstant(local, { disambiguation: 'later', timeZone: 'America/New_York' });\ntoZoned(instant, { timeZone: 'Europe/Berlin' });\n```\n\n---\n\n## Arithmetic and Comparison\n\n### `shift(input, duration, options?)`\n\n```ts\nshift(input: Temporal.ZonedDateTime, duration: Temporal.DurationLike, options?: ShiftOptions): Temporal.ZonedDateTime;\nshift(input: Exclude<TimeInput, Temporal.ZonedDateTime>, duration: Temporal.DurationLike, options: ShiftOptions & { timeZone: string }): Temporal.ZonedDateTime;\n```\n\nAdds a duration through zoned calendar rules.\n\n**Returns:** `Temporal.ZonedDateTime`.\n\n---\n\n### `difference({ start, end, ...options })`\n\n```ts\ndifference(input: DifferenceInput): Temporal.Duration;\n```\n\nReturns the signed duration from `start` to `end` with optional Temporal rounding.\n\n**Returns:** `Temporal.Duration`.\n\n---\n\n### `isBefore()` / `isAfter()` / `isSame()`\n\n```ts\nisBefore(a: TimeInput, b: TimeInput, options?: CompareOptions): boolean;\nisAfter(a: TimeInput, b: TimeInput, options?: CompareOptions): boolean;\nisSame(a: TimeInput, b: TimeInput, options?: CompareOptions): boolean;\n```\n\nCompare absolute instants or their containing calendar units.\n\n**Returns:** A boolean comparison result.\n\n---\n\n### `startOf()` / `endOf()`\n\n```ts\nstartOf(input: TimeInput, unit: BoundaryUnit, options?: BoundaryOptions): Temporal.ZonedDateTime;\nendOf(input: TimeInput, unit: BoundaryUnit, options?: BoundaryOptions): Temporal.ZonedDateTime;\n```\n\nReturns the first or last nanosecond of a timezone-aware calendar unit.\n\n**Returns:** `Temporal.ZonedDateTime`.\n\n## Formatting\n\n### `format(input, options?)`\n\n```ts\nformat(input: TimeInput, options?: FormatOptions): string;\n```\n\nFormats a value through `Intl.DateTimeFormat`.\n\n**Example:**\n\n```ts\nimport { format, parse } from '@vielzeug/tempo';\n\nformat(parse('2026-03-21T10:15:30Z', { as: 'instant' }), {\n locale: 'en-GB',\n pattern: 'short',\n timeZone: 'UTC',\n});\n```\n\n### `formatInstant()` / `formatZoned()` / `formatRelative()` / `formatDuration()` / `formatTimer()`\n\n```ts\nformatInstant(input: TimeInput, options?: TimeZoneOptions): string;\nformatZoned(input: TimeInput, options?: TimeZoneOptions): string;\nformatRelative(input: AbsoluteTime, options?: RelativeFormatOptions): string;\nformatDuration(input: string | Temporal.DurationLike, options?: DurationFormatOptions): string;\nformatTimer(input: string | Temporal.DurationLike, options?: TimerFormatOptions): string;\n```\n\n`formatInstant()` produces UTC transport text (`timeZone` needed for wall-time input, ignored for `Instant`). `formatZoned()` produces zoned ISO text (`timeZone` required for non-`ZonedDateTime` input). `formatRelative()` uses fixed units for short spans and complete calendar months or years in the requested or inferred timezone. Zoned inputs with different zones require `options.timeZone`. `formatDuration()` falls back to English when `Intl.DurationFormat` is unavailable. `formatTimer()` renders a stopwatch-style clock: `47:12` under an hour, `1:02:35` from an hour up: deterministic and locale-independent; sub-second parts are truncated, negative durations clamp to zero, `days` fold into hours, and durations above days throw `TempoInvalidInputError`.\n\n### `formatParts()` / `formatRange()` / `formatRangeParts()`\n\n```ts\nformatParts(input: TimeInput, options?: FormatOptions): Intl.DateTimeFormatPart[];\nformatRange(start: TimeInput, end: TimeInput, options?: FormatOptions): string;\nformatRangeParts(\n start: TimeInput,\n end: TimeInput,\n options?: FormatOptions,\n): ReturnType<Intl.DateTimeFormat['formatRangeToParts']>;\n```\n\nReturn `Intl` parts or localized range strings using `FormatOptions`. Range inputs are order-free: reversed bounds format like the sorted pair.\n\n### `parseDuration()`\n\n```ts\nparseDuration(input: string | Temporal.DurationLike): Temporal.Duration;\n```\n\nParses an ISO 8601 duration string or `Temporal.DurationLike` into a `Temporal.Duration`.\n\n## Types\n\n```ts\ntype AbsoluteTime = Temporal.Instant | Temporal.ZonedDateTime;\ntype WallTime = Temporal.PlainDate | Temporal.PlainDateTime;\ntype TimeInput = AbsoluteTime | WallTime;\ntype ParseAs = 'instant' | 'plainDate' | 'plainDateTime' | 'zonedDateTime';\ntype Disambiguation = 'compatible' | 'earlier' | 'later' | 'reject';\ntype CalendarUnit = 'day' | 'month' | 'week' | 'year';\ntype BoundaryUnit = 'day' | 'hour' | 'minute' | 'month' | 'week' | 'year';\ntype WeekStartDay = 1 | 2 | 3 | 4 | 5 | 6 | 7;\ntype FormatPattern = 'date-only' | 'long' | 'medium' | 'short' | 'time-only';\ntype TempoUnit =\n | 'day'\n | 'hour'\n | 'microsecond'\n | 'millisecond'\n | 'minute'\n | 'month'\n | 'nanosecond'\n | 'second'\n | 'week'\n | 'year';\ninterface TimeZoneOptions {\n timeZone?: string;\n}\ninterface DisambiguationOptions {\n disambiguation?: Disambiguation;\n}\ninterface ShiftOptions extends DisambiguationOptions, TimeZoneOptions {}\ninterface DifferenceInput extends DisambiguationOptions, TimeZoneOptions {\n end: TimeInput;\n largestUnit?: Temporal.DateTimeUnit;\n roundingIncrement?: number;\n roundingMode?: Temporal.RoundingMode;\n smallestUnit?: Temporal.DateTimeUnit;\n start: TimeInput;\n}\ninterface BoundaryOptions extends TimeZoneOptions {\n weekStartsOn?: WeekStartDay;\n}\ninterface CompareOptions extends TimeZoneOptions {\n unit?: BoundaryUnit;\n weekStartsOn?: WeekStartDay;\n}\ntype FormatOptions =\n | { intl: Intl.DateTimeFormatOptions; locale?: Intl.LocalesArgument; pattern?: never; timeZone?: string }\n | { intl?: never; locale?: Intl.LocalesArgument; pattern?: FormatPattern; timeZone?: string };\ninterface RelativeFormatOptions extends TimeZoneOptions {\n base?: AbsoluteTime;\n locale?: Intl.LocalesArgument;\n numeric?: Intl.RelativeTimeFormatNumeric;\n style?: Intl.RelativeTimeFormatStyle;\n}\ninterface DurationFormatOptions {\n locale?: Intl.LocalesArgument;\n style?: 'digital' | 'long' | 'narrow' | 'short';\n}\n```\n\n## Errors\n\n| Error | Trigger | Notable properties |\n| ---------------------------- | --------------------------------------- | --------------------------------------------- |\n| `TempoError` | Base Tempo error | `instanceof TempoError` narrows every subtype |\n| `CadenceError` | Cadence rule cannot be parsed/expanded | Also exported from `@vielzeug/tempo/cadence` |\n| `TempoInvalidInputError` | Invalid parse or duration input | Extends `TempoError` |\n| `TempoInvalidTzError` | Invalid IANA zone or offset | Extends `TempoError` |\n| `TempoMissingTzError` | Wall time without required `timeZone` | Extends `TempoError` |\n| `TempoUnsupportedInputError` | Non-Temporal input passed to conversion | Extends `TempoError` |\n\nEvery Tempo error thrown from `parse()`, `parseDuration()`, and timezone validation carries the original Temporal error on its `cause` property (ES2022). Inspect `err.cause` for root-cause details when debugging.\n",
|
|
6
|
-
"usage": "---\ntitle: 'Tempo: Usage Guide'\ndescription: Parse explicit Temporal values, resolve wall-clock time, perform timezone-aware arithmetic, and format dates with Tempo.\n---\n\n[[toc]]\n\n## Basic Usage\n\nParse ISO input with a declared target. Convert plain values with `timeZone` before treating them as an instant.\n\n```ts\nimport { format, parse, shift } from '@vielzeug/tempo';\n\nconst local = parse('2026-03-21T10:15:30', { as: 'plainDateTime' });\nconst reminder = shift(local, { minutes: -15 }, { timeZone: 'America/New_York' });\n\nformat(reminder, { locale: 'en-US', pattern: 'short' });\n```\n\n## Parse ISO Values\n\nChoose the value your boundary actually represents. Tempo does not auto-detect ISO strings.\n\n```ts\nimport { parse } from '@vielzeug/tempo';\n\nconst occurredAt = parse('2026-03-21T10:15:30Z', { as: 'instant' });\nconst meeting = parse('2026-03-21T10:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' });\nconst localStart = parse('2026-03-21T10:15:30', { as: 'plainDateTime' });\nconst birthday = parse('2026-03-21', { as: 'plainDate' });\n```\n\n## Convert Timezones\n\nUse `toZoned()` to project a value into a display timezone. Use `toInstant()` only when resolving a wall-clock value.\n\n```ts\nimport { parse, toInstant, toZoned } from '@vielzeug/tempo';\n\nconst local = parse('2026-11-01T01:30:00', { as: 'plainDateTime' });\nconst firstOccurrence = toInstant(local, {\n disambiguation: 'earlier',\n timeZone: 'America/New_York',\n});\n\nconst berlin = toZoned(firstOccurrence, { timeZone: 'Europe/Berlin' });\n```\n\n## Calculate and Compare\n\nUse Tempo helpers when an operation must resolve timezones or compare calendar units. Use Temporal methods directly when values are already the exact kind and timezone you need.\n\n```ts\nimport { difference, isAfter, isBefore, isSame, parse, shift } from '@vielzeug/tempo';\n\nconst start = parse('2026-03-21T10:00:00Z', { as: 'instant' });\nconst end = parse('2026-03-21T12:00:00Z', { as: 'instant' });\n\nconst duration = difference({ end, largestUnit: 'hour', start });\nconst isWithinWindow = isAfter(end, start) && isBefore(end, parse('2026-03-21T14:00:00Z', { as: 'instant' }));\n\nconst sameDay = isSame(start, end, { timeZone: 'UTC', unit: 'day' });\n\nconst local = parse('2026-03-08T01:30:00', { as: 'plainDateTime' });\nconst tomorrow = shift(local, { days: 1 }, { timeZone: 'America/New_York' });\n```\n\n## Format Values\n\nUse `format()` for UI, `formatInstant()` for transport, and `formatZoned()` for a zoned ISO string.\n\n```ts\nimport { format, formatInstant, formatRelative, formatZoned, parse } from '@vielzeug/tempo';\n\nconst instant = parse('2026-03-21T10:15:30Z', { as: 'instant' });\n\nformat(instant, { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' });\nformatInstant(instant);\nformatZoned(instant, { timeZone: 'Europe/Berlin' });\nformatRelative(instant, { base: parse('2026-03-21T09:15:30Z', { as: 'instant' }) });\n```\n\n`formatRelative()` uses fixed elapsed-time units for short spans and complete calendar months or years for longer spans. Pass `timeZone` when calendar-relative output must use a specific regional calendar boundary.\n\nUse `formatTimer()` for stopwatch-style clocks: elapsed timers, recorded durations: where localized prose does not fit:\n\n```ts\nimport { formatTimer } from '@vielzeug/tempo';\n\nformatTimer('PT47M12S'); // '47:12'\nformatTimer({ milliseconds: 3_753_000 }); // '1:02:33'\nformatTimer('PT5M', { hours: 'always' }); // '0:05:00'\n```\n\n## Testing\n\nPin reference instants so relative and boundary assertions stay deterministic.\n\n```ts\nimport { formatRelative, parse, startOf } from '@vielzeug/tempo';\n\nconst base = parse('2026-06-01T00:00:00Z', { as: 'instant' });\nconst value = parse('2026-06-04T00:00:00Z', { as: 'instant' });\n\nformatRelative(value, { base, locale: 'en-US' }); // 'in 3 days'\nstartOf(value, 'month').toString(); // '2026-06-01T00:00:00+00:00[UTC]'\n```\n\n## Framework Integration\n\nPass ISO strings through component props. Parse and format at the rendering boundary.\n\n::: code-group\n\n```tsx [React]\nimport { format, parse } from '@vielzeug/tempo';\n\nconst label = format(parse(iso, { as: 'instant' }), { locale: 'en-US', pattern: 'medium', timeZone: 'UTC' });\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { format, parse } from '@vielzeug/tempo';\n\nconst props = defineProps<{ iso: string }>();\nconst label = format(parse(props.iso, { as: 'instant' }), { locale: 'en-US', pattern: 'medium', timeZone: 'UTC' });\n</script>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { format, parse } from '@vielzeug/tempo';\n export let iso: string;\n $: label = format(parse(iso, { as: 'instant' }), { locale: 'en-US', pattern: 'medium', timeZone: 'UTC' });\n</script>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### With Rune\n\nWrite stable UTC timestamps to structured logs.\n\n```ts\nimport { formatInstant, nowInstant } from '@vielzeug/tempo';\n\nlogger.info({ timestamp: formatInstant(nowInstant()) }, 'server started');\n```\n\n### With Vault\n\nCalculate an explicit instant before storing an expiring record.\n\n```ts\nimport { now } from '@vielzeug/tempo';\n\nconst expiresAt = now({ timeZone: 'UTC' }).add({ minutes: 30 }).toInstant();\n```\n\n## Best Practices\n\n- Parse strings with their actual temporal meaning and pass `timeZone` when resolving plain values.\n- Use `disambiguation` for DST overlap and gap handling.\n- Use Tempo helpers for timezone resolution and calendar units; use Temporal directly for already-normalized values.\n- Store instants for transport and database values.\n- Use `formatInstant()` for machine output and `format()` for user-facing text.\n- Pass `timeZone` to `formatRelative()` when month and year boundaries must use a specific region.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Tempo: Examples'\ndescription: Practical examples and recipes for tempo.\n---\n\n## Examples\n\n- [DST-Safe Arithmetic](./examples/dst-safe-arithmetic.md)\n- [Locale Formatting](./examples/locale-formatting.md)\n- [Timezone Conversion](./examples/timezone-conversion.md)\n"
|
|
8
|
-
},
|
|
9
|
-
"examples": [
|
|
10
|
-
{
|
|
11
|
-
"id": "meeting-duration",
|
|
12
|
-
"code": "import { difference, format, parse, shift, toInstant, toZoned } from '@vielzeug/tempo'\n\nconst local = parse('2026-03-21T10:00:00', { as: 'plainDateTime' })\nconst start = toInstant(local, { timeZone: 'America/New_York' })\nconst end = shift(start, { hours: 2 }, { timeZone: 'America/New_York' })\n\nconsole.log('Duration:', difference({ end, largestUnit: 'hour', start }).toString())\nconsole.log('New York:', format(end, { locale: 'en-US', pattern: 'short' }))\nconsole.log('Berlin:', format(toZoned(end, { timeZone: 'Europe/Berlin' }), { locale: 'de-DE', pattern: 'short' }))",
|
|
13
|
-
"name": "Timezone-Aware Arithmetic and Formatting"
|
|
14
|
-
}
|
|
15
|
-
],
|
|
16
|
-
"typeSignatures": {
|
|
17
|
-
"Temporal": "export { Temporal } from '@js-temporal/polyfill';",
|
|
18
|
-
"toInstant": "export { toInstant, toZoned } from './_convert';",
|
|
19
|
-
"toZoned": "export { toInstant, toZoned } from './_convert';",
|
|
20
|
-
"endOf": "export { endOf, startOf } from './boundary';",
|
|
21
|
-
"startOf": "export { endOf, startOf } from './boundary';",
|
|
22
|
-
"isAfter": "export { isAfter, isBefore, isSame } from './compare';",
|
|
23
|
-
"isBefore": "export { isAfter, isBefore, isSame } from './compare';",
|
|
24
|
-
"isSame": "export { isAfter, isBefore, isSame } from './compare';",
|
|
25
|
-
"difference": "export { difference, isValid, now, nowInstant, parse, shift } from './core';",
|
|
26
|
-
"isValid": "export { difference, isValid, now, nowInstant, parse, shift } from './core';",
|
|
27
|
-
"now": "export { difference, isValid, now, nowInstant, parse, shift } from './core';",
|
|
28
|
-
"nowInstant": "export { difference, isValid, now, nowInstant, parse, shift } from './core';",
|
|
29
|
-
"parse": "export { difference, isValid, now, nowInstant, parse, shift } from './core';",
|
|
30
|
-
"shift": "export { difference, isValid, now, nowInstant, parse, shift } from './core';",
|
|
31
|
-
"CadenceError": "export {\n CadenceError,\n TempoError,\n TempoInvalidInputError,\n TempoInvalidTzError,\n TempoMissingTzError,\n TempoUnsupportedInputError,\n} from './errors';",
|
|
32
|
-
"TempoError": "export {\n CadenceError,\n TempoError,\n TempoInvalidInputError,\n TempoInvalidTzError,\n TempoMissingTzError,\n TempoUnsupportedInputError,\n} from './errors';",
|
|
33
|
-
"TempoInvalidInputError": "export {\n CadenceError,\n TempoError,\n TempoInvalidInputError,\n TempoInvalidTzError,\n TempoMissingTzError,\n TempoUnsupportedInputError,\n} from './errors';",
|
|
34
|
-
"TempoInvalidTzError": "export {\n CadenceError,\n TempoError,\n TempoInvalidInputError,\n TempoInvalidTzError,\n TempoMissingTzError,\n TempoUnsupportedInputError,\n} from './errors';",
|
|
35
|
-
"TempoMissingTzError": "export {\n CadenceError,\n TempoError,\n TempoInvalidInputError,\n TempoInvalidTzError,\n TempoMissingTzError,\n TempoUnsupportedInputError,\n} from './errors';",
|
|
36
|
-
"TempoUnsupportedInputError": "export {\n CadenceError,\n TempoError,\n TempoInvalidInputError,\n TempoInvalidTzError,\n TempoMissingTzError,\n TempoUnsupportedInputError,\n} from './errors';",
|
|
37
|
-
"format": "export {\n format,\n formatDuration,\n formatInstant,\n formatParts,\n formatRange,\n formatRangeParts,\n formatRelative,\n formatTimer,\n formatZoned,\n parseDuration,\n} from './format';",
|
|
38
|
-
"formatDuration": "export {\n format,\n formatDuration,\n formatInstant,\n formatParts,\n formatRange,\n formatRangeParts,\n formatRelative,\n formatTimer,\n formatZoned,\n parseDuration,\n} from './format';",
|
|
39
|
-
"formatInstant": "export {\n format,\n formatDuration,\n formatInstant,\n formatParts,\n formatRange,\n formatRangeParts,\n formatRelative,\n formatTimer,\n formatZoned,\n parseDuration,\n} from './format';",
|
|
40
|
-
"formatParts": "export {\n format,\n formatDuration,\n formatInstant,\n formatParts,\n formatRange,\n formatRangeParts,\n formatRelative,\n formatTimer,\n formatZoned,\n parseDuration,\n} from './format';",
|
|
41
|
-
"formatRange": "export {\n format,\n formatDuration,\n formatInstant,\n formatParts,\n formatRange,\n formatRangeParts,\n formatRelative,\n formatTimer,\n formatZoned,\n parseDuration,\n} from './format';",
|
|
42
|
-
"formatRangeParts": "export {\n format,\n formatDuration,\n formatInstant,\n formatParts,\n formatRange,\n formatRangeParts,\n formatRelative,\n formatTimer,\n formatZoned,\n parseDuration,\n} from './format';",
|
|
43
|
-
"formatRelative": "export {\n format,\n formatDuration,\n formatInstant,\n formatParts,\n formatRange,\n formatRangeParts,\n formatRelative,\n formatTimer,\n formatZoned,\n parseDuration,\n} from './format';",
|
|
44
|
-
"formatTimer": "export {\n format,\n formatDuration,\n formatInstant,\n formatParts,\n formatRange,\n formatRangeParts,\n formatRelative,\n formatTimer,\n formatZoned,\n parseDuration,\n} from './format';",
|
|
45
|
-
"formatZoned": "export {\n format,\n formatDuration,\n formatInstant,\n formatParts,\n formatRange,\n formatRangeParts,\n formatRelative,\n formatTimer,\n formatZoned,\n parseDuration,\n} from './format';",
|
|
46
|
-
"parseDuration": "export {\n format,\n formatDuration,\n formatInstant,\n formatParts,\n formatRange,\n formatRangeParts,\n formatRelative,\n formatTimer,\n formatZoned,\n parseDuration,\n} from './format';",
|
|
47
|
-
"AbsoluteTime": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
48
|
-
"BoundaryOptions": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
49
|
-
"BoundaryUnit": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
50
|
-
"CalendarUnit": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
51
|
-
"CompareOptions": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
52
|
-
"DifferenceInput": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
53
|
-
"Disambiguation": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
54
|
-
"DisambiguationOptions": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
55
|
-
"DurationFormatOptions": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
56
|
-
"FormatOptions": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
57
|
-
"FormatPattern": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
58
|
-
"ParseAs": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
59
|
-
"RelativeFormatOptions": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
60
|
-
"ShiftOptions": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
61
|
-
"TempoUnit": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
62
|
-
"TimeInput": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
63
|
-
"TimerFormatOptions": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
64
|
-
"TimeZoneOptions": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
65
|
-
"WallTime": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';",
|
|
66
|
-
"WeekStartDay": "export type {\n AbsoluteTime,\n BoundaryOptions,\n BoundaryUnit,\n CalendarUnit,\n CompareOptions,\n DifferenceInput,\n Disambiguation,\n DisambiguationOptions,\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n ParseAs,\n RelativeFormatOptions,\n ShiftOptions,\n TempoUnit,\n TimeInput,\n TimerFormatOptions,\n TimeZoneOptions,\n WallTime,\n WeekStartDay,\n} from './types';"
|
|
67
|
-
}
|
|
68
|
-
}
|
package/data/packages/vault.json
DELETED
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"apiSource": "export { VaultDisposedError, VaultError, VaultMigrationError, VaultQuotaError, VaultScopeError } from './errors';\nexport { ttl } from './ttl';\nexport type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';\nexport { table } from './types';\n",
|
|
3
|
-
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Vault: Typed storage'\ndescription: Typed browser storage and opt-in driver-neutral SQLite with portable keys, TTL, observation, and transactions.\npackage: vault\ncategory: Storage\nkeywords: [storage, indexeddb, localstorage, sessionstorage, sqlite, ttl, browser, node, deno]\nrelated: [courier, forge, ripple]\nexports: [table, ttl, createMemory, createLocalStorage, createSessionStorage, createIndexedDB, createSQLite]\nenvironments: [browser, node, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"vault\" />\n\n## Why Vault?\n\nVault gives browser and SQLite persistence one typed schema while keeping backend guarantees explicit. Use `KeyValueVaultStore` for portable CRUD and observation; choose IndexedDB or the opt-in SQLite subpath when you need atomic transactions or lazy iteration. Durable adapters require parsers so invalid stored data never enters typed code.\n\n```ts\n// Before\nlocalStorage.setItem('theme', JSON.stringify({ value: 'dark' }));\nconst theme = JSON.parse(localStorage.getItem('theme') ?? '{}').value;\n\n// After\nawait store.put('preferences', { id: 'theme', value: 'dark' });\nconst theme = await store.get('preferences', 'theme');\n```\n\n| Feature | Vault | Raw Web Storage | Dexie |\n| ---------------------------- | -------------------------------------------- | ----------------------------------------------------- | -------------------------------------------- |\n| Bundle size | <PackageInfo package=\"vault\" type=\"size\" /> | Browser built-in | Extra dependency |\n| Runtime 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| Typed schema and keys | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Application-defined | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Portable key-value store API | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> | IndexedDB only |\n| Explicit atomic transactions | IndexedDB + SQLite capability | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Required durable parsers | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Driver-neutral SQLite | Opt-in subpath | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Vault when** you need typed browser persistence or application-owned SQLite with honest storage capabilities and required durable parsers.\n\n**Consider raw Web Storage when** you only persist one or two unstructured values. **Consider Dexie when** you need a broader IndexedDB ecosystem.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/vault\n```\n\n```sh [npm]\nnpm install @vielzeug/vault\n```\n\n```sh [yarn]\nyarn add @vielzeug/vault\n```\n\n:::\n\n## Quick Start\n\nDefine a schema, create a key-value store with parsers, and dispose it with its owner.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createLocalStorage } from '@vielzeug/vault/local-storage';\n\nconst PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'light']) });\nconst store = createLocalStorage({\n name: 'app-v2',\n schema: { preferences: table<{ id: string; theme: 'dark' | 'light' }>('id') },\n parsers: { preferences: PreferenceSchema },\n});\n\ntry {\n await store.put('preferences', { id: 'theme', theme: 'dark' });\n console.log(await store.get('preferences', 'theme'));\n} finally {\n await store.dispose();\n}\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `table()` defines typed records with portable string or number keys.\n- Spell and other parser schemas work directly as per-table parsers.\n- `/memory` returns a portable `DocumentVaultStore` with `batch()` and `iterate()`: parsers optional (in-memory, no trust boundary).\n- `/local-storage` and `/session-storage` return `KeyValueVaultStore`: parsers required.\n- `observe()` emits current and changed table snapshots.\n- `ttl` creates validated expiration durations.\n- `/indexeddb` and `/sqlite` return `DocumentVaultStore` with `batch()` and `iterate()`: parsers required. `/memory` shares the same contract without parsers.\n- `/indexeddb` accepts a `migrate` hook for schema upgrades the table schema cannot express.\n- `pruneExpired()` removes stale TTL entries on demand.\n- Bound helpers (`has`, `count`, `update`, `upsert`, `getMany`, `keys`, `deleteMany`) are available on every store and transaction context.\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- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Forge](../forge/index.md) saves and restores form drafts through Vault stores.\n- [Ripple](../ripple/index.md) owns application state that can persist through Vault.\n- [Courier](../courier/index.md) can populate persistent cache data.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Vault: API Reference'\ndescription: Reference for Vault schemas, adapter entry points, storage capabilities, parsers, SQLite drivers, and errors.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------- |\n| `createMemory()` | In-memory document store | Async API | Import from `/memory`; parsers optional |\n| `createLocalStorage()` / `createSessionStorage()` | Web Storage-backed key-value stores | Async API | Parsers required; available only where the corresponding Web API exists |\n| `createIndexedDB()` | Browser document store with transactions and cursor iteration | Async API | Import from `/indexeddb`; parsers required |\n| `createSQLite()` | Driver-neutral SQLite document store | Async API over a synchronous driver | Import from `/sqlite`; parsers required |\n| `table()` | Typed record schema | Sync | The key field must be a string or finite number |\n| `ttl` | Valid expiration durations | Sync | Durations must be positive |\n\n## Package Entry Points\n\n| Import | Purpose |\n| --------------------------------- | ----------------------------------------------------------------------------- |\n| `@vielzeug/vault` | Adapter-free schemas, TTL, errors, parsers, derived helpers, and shared types |\n| `@vielzeug/vault/memory` | `createMemory` |\n| `@vielzeug/vault/local-storage` | `createLocalStorage` |\n| `@vielzeug/vault/session-storage` | `createSessionStorage` |\n| `@vielzeug/vault/indexeddb` | `createIndexedDB`, the `migrate` upgrade-hook types, and IndexedDB-only types |\n| `@vielzeug/vault/sqlite` | `createSQLite`, the SQLite driver protocol types, and `TransactionContext` |\n\n## Schemas, Parsers, and TTL\n\n### `table()`\n\n```ts\nfunction table<T extends object, Key extends keyof T & string = keyof T & string>(\n key: Key & (T[Key] extends VaultKey ? unknown : never),\n options?: { defaultTtl?: number; indexes?: readonly (keyof T & string)[] },\n): SchemaEntry<T, Key>;\n```\n\nDefines a typed table and its primary-key field.\n\n| Parameter | Description |\n| -------------------- | ---------------------------------------------------------------- |\n| `key` | A record field whose values are `string` or finite `number` keys |\n| `options.defaultTtl` | Per-table default TTL in milliseconds |\n| `options.indexes` | IndexedDB-only secondary index fields (`getAllByIndex()`) |\n\n**Returns:** A `SchemaEntry` describing the table.\n\n```ts\nimport { table, ttl } from '@vielzeug/vault';\n\nconst users = table<{ id: number; email: string }>('id', {\n indexes: ['email'],\n defaultTtl: ttl.days(7),\n});\n```\n\n---\n\n### `ttl`\n\n```ts\nconst ttl: {\n days(n: number): number;\n hours(n: number): number;\n minutes(n: number): number;\n ms(n: number): number;\n seconds(n: number): number;\n};\n```\n\nCreates a finite, positive duration in milliseconds for writes and table defaults.\n\n**Returns:** `number`.\n\n```ts\nimport { ttl } from '@vielzeug/vault';\n\nconst cacheLifetime = ttl.minutes(5);\n```\n\n## Factories\n\nDurable factories (LocalStorage, SessionStorage, IndexedDB, SQLite) require `parsers`. Memory may omit them.\n\n### `createMemory()`\n\n```ts\nfunction createMemory<S extends AnySchema>(options: MemoryStoreOptions<S>): DocumentVaultStore<S>;\n```\n\nCreates an in-memory document store with `batch()` and `iterate()`. `batch()` snapshots the declared tables and restores them when the callback throws. Parsers are optional because memory values never cross a trust boundary.\n\n| Parameter | Description |\n| --------- | --------------------------- |\n| `schema` | Tables created by `table()` |\n| `parsers` | Optional per-table parsers |\n\n**Returns:** `DocumentVaultStore<S>`.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createMemory } from '@vielzeug/vault/memory';\n\nconst store = createMemory({ schema: { users: table<{ id: number; name: string }>('id') } });\n```\n\n---\n\n### `createLocalStorage()`\n\n```ts\nfunction createLocalStorage<S extends AnySchema>(\n options: DurableStoreOptions<S> & {\n name: string;\n },\n): KeyValueVaultStore<S>;\n```\n\nCreates a namespaced `localStorage` store. Parsers are required.\n\n| Parameter | Description |\n| --------- | --------------------------- |\n| `schema` | Tables created by `table()` |\n| `parsers` | Required per-table parsers |\n| `name` | Required storage namespace |\n\nA write that exceeds the browser quota rejects with `VaultQuotaError`.\n\n**Returns:** `KeyValueVaultStore<S>`.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createLocalStorage } from '@vielzeug/vault/local-storage';\n\nconst store = createLocalStorage({\n name: 'app',\n schema: { settings: table<{ id: string }>('id') },\n parsers: { settings: SettingsSchema },\n});\n```\n\n---\n\n### `createSessionStorage()`\n\n```ts\nfunction createSessionStorage<S extends AnySchema>(\n options: DurableStoreOptions<S> & {\n name: string;\n },\n): KeyValueVaultStore<S>;\n```\n\nCreates a namespaced `sessionStorage` store. Its options and return type match `createLocalStorage()`.\n\n**Returns:** `KeyValueVaultStore<S>`.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createSessionStorage } from '@vielzeug/vault/session-storage';\n\nconst store = createSessionStorage({\n name: 'checkout',\n schema: { cart: table<{ id: string }>('id') },\n parsers: { cart: CartSchema },\n});\n```\n\n---\n\n### `createIndexedDB()`\n\n```ts\nfunction createIndexedDB<S extends AnySchema>(\n options: DurableStoreOptions<S> & {\n migrate?: MigrationFn;\n name: string;\n version?: number;\n },\n): IndexedDbVaultStore<S>;\n```\n\nCreates an IndexedDB document store with atomic batches, lazy cursor iteration, and optional schema migrations. Parsers are required.\n\n| Parameter | Description |\n| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `schema` | Tables and IndexedDB secondary indexes |\n| `parsers` | Required per-table parsers |\n| `name` | Required database name |\n| `version` | Positive schema version; defaults to `1` |\n| `migrate` | Synchronous `onupgradeneeded` callback. Object stores and schema-declared indexes are created automatically; use the hook only for deletes or record transforms |\n\n**Returns:** `IndexedDbVaultStore<S>`. Its `getAllByIndex(table, field, value)` method queries a declared IndexedDB index without scanning the full table.\n\n```ts\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb';\n\nconst store = createIndexedDB({\n name: 'app',\n schema: { users: table<{ id: number; role: string }>('id', { indexes: ['role'] }) },\n parsers: { users: UserSchema },\n});\n\nconst admins = await store.getAllByIndex('users', 'role', 'admin');\n```\n\n---\n\n### `createSQLite()`\n\n```ts\nfunction createSQLite<S extends AnySchema>(options: SQLiteVaultOptions<S>): DocumentVaultStore<S>;\n```\n\nCreates a namespaced SQLite document store with atomic batches and keyset-paginated iteration. Parsers are required. It accepts an application-provided positional-parameter driver and never opens or imports a runtime driver.\n\n| Parameter | Description |\n| ---------------- | ---------------------------------------------------------- |\n| `schema` | Tables created by `table()` |\n| `parsers` | Required per-table parsers |\n| `database` | Caller-provided `SQLiteDatabase` connection |\n| `name` | Namespace within the connection |\n| `closeOnDispose` | Closes the connection during disposal; defaults to `false` |\n\n**Returns:** `DocumentVaultStore<S>`.\n\n```ts\nimport { DatabaseSync } from 'node:sqlite';\n\nimport { table } from '@vielzeug/vault';\nimport { createSQLite } from '@vielzeug/vault/sqlite';\n\nconst store = createSQLite({\n database: new DatabaseSync(':memory:'),\n name: 'tests',\n schema: { users: table<{ id: number; name: string }>('id') },\n parsers: { users: UserSchema },\n});\n```\n\nNode `DatabaseSync`, Bun `Database`, and Deno `jsr:@db/sqlite` `Database` satisfy the protocol. Records must be JSON-compatible values. During a `batch()` callback, calls on every Vault store sharing that connection reject; use `tx.*` instead.\n\n## Store Capabilities\n\n### `KeyValueVaultStore`\n\n```ts\ninterface KeyValueVaultStore<S extends AnySchema> {\n clear(table): Promise<void>;\n count(table): Promise<number>;\n delete(table, key): Promise<boolean>;\n deleteMany(table, keys): Promise<number>;\n get(table, key): Promise<Record | undefined>;\n getAll(table): Promise<Record[]>;\n getMany(table, keys): Promise<(Record | undefined)[]>;\n has(table, key): Promise<boolean>;\n isEmpty(table): Promise<boolean>;\n keys(table, filter?): Promise<VaultKey[]>;\n update(table, key, changes, ttl?): Promise<Record | undefined>;\n upsert(table, key, update, ttl?): Promise<Record>;\n observe(table, listener, options?): Unsubscribe;\n pruneExpired(): Promise<Record<string, number>>;\n put<K extends keyof S & string>(table: K, value: RecordOf<S, K>, ttl?: number): Promise<RecordOf<S, K>>;\n putAll(table, values, ttl?): Promise<void>;\n readonly disposalSignal: AbortSignal;\n dispose(): Promise<void>;\n readonly disposed: boolean;\n [Symbol.asyncDispose](): Promise<void>;\n}\n```\n\nThe portable key-value store API is returned by Memory and Web Storage factories. `put()`, `update()`, and `upsert()` return the canonical value produced by the table parser. `observe()` emits the current table snapshot by default and then emits after mutations. Listener errors never break the snapshot stream; pass `onObserverError` to the factory to report them.\n\n---\n\n### `DocumentVaultStore`\n\n```ts\ninterface DocumentVaultStore<S extends AnySchema> extends KeyValueVaultStore<S> {\n batch<K extends keyof S & string, R>(\n tables: readonly K[],\n fn: (tx: TransactionContext<S, K>) => Promise<R>,\n ): Promise<R>;\n iterate<K extends keyof S & string>(table: K): AsyncIterable<RecordOf<S, K>>;\n}\n```\n\n`batch()` runs a scoped atomic callback. `iterate()` lazily yields table records: IndexedDB uses a cursor, SQLite uses keyset pagination. Both are provided by `createIndexedDB()` and `createSQLite()`.\n\n| Parameter | Description |\n| --------- | ------------------------------------------------------- |\n| `tables` | Tables the transaction may access |\n| `fn` | Async callback that uses only the supplied `tx` context |\n\n**Returns:** The callback result after commit.\n\n```ts\nawait store.batch(['users'], async (tx) => {\n await tx.put('users', { id: 1, name: 'Ada' });\n});\n\nfor await (const user of store.iterate('users')) console.log(user);\n```\n\n## Bound Helpers\n\nConvenience operations are bound to every store and transaction context. For filtering, ordering, and pagination, compose over `getAll()`: it returns a plain array, or use `iterate()` on document stores and `getAllByIndex()` on IndexedDB for declared equality indexes.\n\n| Helper | Signature | Description |\n| -------------- | -------------------------------------------------------- | ------------------------------------------------------ |\n| `has()` | `(table, key) => Promise<boolean>` | Check whether a record exists |\n| `count()` | `(table) => Promise<number>` | Count live records |\n| `isEmpty()` | `(table) => Promise<boolean>` | Check whether a table has no live records |\n| `getMany()` | `(table, keys) => Promise<(T \\| undefined)[]>` | Fetch multiple records by key |\n| `keys()` | `(table, filter?) => Promise<VaultKey[]>` | Fetch live primary keys, optionally filtered by record |\n| `deleteMany()` | `(table, keys) => Promise<number>` | Delete multiple records, return count |\n| `update()` | `(table, key, changes, ttl?) => Promise<T \\| undefined>` | Partially update an existing record |\n| `upsert()` | `(table, key, fn, ttl?) => Promise<T>` | Read-modify-write with callback |\n\n```ts\nconst exists = await store.has('users', 1);\nconst total = await store.count('users');\nconst [a, b] = await store.getMany('users', [1, 2]);\nconst updated = await store.update('users', 1, { name: 'Alice' });\nconst result = await store.upsert('users', 99, (existing) => ({ id: 99, name: existing?.name ?? 'Guest' }));\n\nconst all = await store.getAll('users');\nconst active = all\n .filter((user) => user.status === 'active')\n .sort((a, b) => a.name.localeCompare(b.name))\n .slice(0, 20);\n```\n\nBound `update()` and `upsert()` are atomic on document stores. Their key-value-store forms are non-atomic convenience operations.\n\n## Types\n\n```ts\ntype VaultKey = number | string;\ntype Unsubscribe = () => void;\ntype Observer<T> = (records: T[]) => void;\ntype AnySchema = Record<\n string,\n {\n defaultTtl?: number;\n indexes?: readonly string[];\n key: string;\n }\n>;\ntype SchemaEntry<T extends object, Key extends keyof T & string = keyof T & string> = {\n defaultTtl?: number;\n indexes?: readonly (keyof T & string)[];\n key: Key;\n};\ntype RecordOf<S extends AnySchema, K extends keyof S> = K extends unknown\n ? S[K] extends SchemaEntry<infer R, infer _Key>\n ? R\n : never\n : never;\ntype KeyOf<S extends AnySchema, K extends keyof S> = K extends unknown\n ? Extract<S[K] extends SchemaEntry<infer R, infer Key> ? R[Key] : never, VaultKey>\n : never;\n```\n\n```ts\ntype RecordParser<T> = { parse(value: unknown): T };\n\ntype TableParsers<S extends AnySchema> = {\n [K in keyof S]: RecordParser<RecordOf<S, K>>;\n};\n\ntype ObserverErrorHandler = (error: unknown) => void;\n\ntype MemoryStoreOptions<S extends AnySchema> = {\n schema: S;\n parsers?: TableParsers<S>;\n onObserverError?: ObserverErrorHandler;\n};\n\ntype DurableStoreOptions<S extends AnySchema> = {\n schema: S;\n parsers: TableParsers<S>;\n onObserverError?: ObserverErrorHandler;\n};\n```\n\nParsers validate writes and decode persisted values: `put()` stores the parser's canonical output, so a record that parses can always be read back. Records must be JSON-safe (use ISO strings for dates) to survive every adapter's serialization. Spell schemas satisfy `RecordParser` directly.\n\n```ts\ntype MigrationContext = {\n db: IDBDatabase;\n newVersion: number | null;\n oldVersion: number;\n tx: IDBTransaction;\n};\n\ntype MigrationFn = (ctx: MigrationContext) => void;\n```\n\nImport `MigrationContext` and `MigrationFn` from `@vielzeug/vault/indexeddb`.\n\n```ts\ntype SQLiteParameter = null | number | string;\n\ninterface SQLiteStatement {\n all(...parameters: SQLiteParameter[]): readonly Record<string, unknown>[];\n finalize?(): void;\n get(...parameters: SQLiteParameter[]): Record<string, unknown> | null | undefined;\n run(...parameters: SQLiteParameter[]): unknown;\n}\n\ninterface SQLiteDatabase {\n close?(): void;\n exec(sql: string): void;\n prepare(sql: string): SQLiteStatement;\n}\n\ntype SQLiteVaultOptions<S extends AnySchema> = DurableStoreOptions<S> & {\n closeOnDispose?: boolean;\n database: SQLiteDatabase;\n name: string;\n};\n```\n\n```ts\ninterface TransactionContext<S extends AnySchema, K extends keyof S & string = keyof S & string> {\n clear<T extends K>(table: T): Promise<void>;\n delete<T extends K>(table: T, key: KeyOf<S, T>): Promise<boolean>;\n get<T extends K>(table: T, key: KeyOf<S, T>): Promise<RecordOf<S, T> | undefined>;\n getAll<T extends K>(table: T): Promise<RecordOf<S, T>[]>;\n iterate<T extends K>(table: T): AsyncIterable<RecordOf<S, T>>;\n put<T extends K>(table: T, value: RecordOf<S, T>, ttl?: number): Promise<RecordOf<S, T>>;\n putAll<T extends K>(table: T, values: RecordOf<S, T>[], ttl?: number): Promise<void>;\n}\n```\n\n`TransactionContext` has core CRUD, `iterate()`, and TTL methods, narrowed to the tables declared in `batch()`. Import it from `@vielzeug/vault/indexeddb` or `@vielzeug/vault/sqlite`.\n\n## Errors\n\n| Error | Trigger |\n| --------------------- | ------------------------------------------------------------------------ |\n| `VaultError` | Any Vault-originated validation, serialization, storage, or parser error |\n| `VaultDisposedError` | An operation after the store or observer hub is disposed |\n| `VaultScopeError` | A `batch()` callback accesses a table outside its declared scope |\n| `VaultQuotaError` | A LocalStorage or SessionStorage write exceeds the browser quota |\n| `VaultMigrationError` | An IndexedDB migration callback throws |\n\nEvery listed error extends `VaultError`.\n",
|
|
6
|
-
"usage": "---\ntitle: 'Vault: Usage Guide'\ndescription: Persist typed browser or SQLite data, observe table snapshots, and use atomic transactions with required durable parsers.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate a key-value store with a schema and parsers, then write a typed row.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createLocalStorage } from '@vielzeug/vault/local-storage';\n\ninterface Preference {\n id: string;\n theme: 'dark' | 'light';\n}\n\nconst PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'light']) });\nconst store = createLocalStorage({\n name: 'app-v2',\n schema: { preferences: table<Preference>('id') },\n parsers: { preferences: PreferenceSchema },\n});\n\nawait store.put('preferences', { id: 'theme', theme: 'dark' });\nconsole.log(await store.get('preferences', 'theme'));\n```\n\n## Create a Key-Value Store\n\nLocalStorage and SessionStorage return `KeyValueVaultStore`; Memory returns a `DocumentVaultStore` (it adds `batch()` and `iterate()`). They share portable string/number keys, bound helpers, fluent queries, TTL, and `observe()`. Memory may omit parsers; Web Storage requires them. Malformed storage envelopes are evicted lazily, while parser validation failures are surfaced without deleting persisted data.\n\nThe root entry is adapter-free. Import `createMemory` from `@vielzeug/vault/memory`, `createLocalStorage` from `@vielzeug/vault/local-storage`, or `createSessionStorage` from `@vielzeug/vault/session-storage`. Import each adapter from its focused subpath so unused backends stay out of the bundle.\n\nUse a new storage name when upgrading from Vault 1. Old key and envelope formats are not read by Vault 2.\n\n```ts\nconst store = createLocalStorage({\n name: 'app-v2',\n schema: { preferences: table<Preference>('id') },\n parsers: { preferences: PreferenceSchema },\n});\n```\n\n## Read and Change Records\n\nUse bound `update()` and `upsert()` methods for read-modify-write operations; no helper imports are required.\n\n```ts\nconst updated = await store.update('preferences', 'theme', { theme: 'light' });\n\nawait store.upsert('preferences', 'locale', (current) => ({\n id: 'locale',\n theme: current?.theme ?? 'dark',\n}));\n\nconsole.log(updated);\n```\n\n`update()` returns `undefined` for a missing key. `upsert()` always writes the record returned by its callback. Document-store methods run atomically; key-value-store methods are non-atomic conveniences when multiple writers race.\n\n## Iterate and Filter Records\n\nFilter the plain array returned by `getAll()` for in-memory selection, sorting, and pagination. Use `iterate()` on a `DocumentVaultStore` for lazy cursor-based traversal, and `getAllByIndex()` on IndexedDB for declared equality indexes.\n\n```ts\n// In-memory selection over getAll()\nconst themed = (await store.getAll('preferences')).filter((preference) => preference.id.startsWith('theme'));\n\n// Document store: iterate lazily\nfor await (const pref of db.iterate('preferences')) {\n if (pref.id.startsWith('theme')) console.log(pref);\n}\n```\n\nFor large tables, prefer `iterate()` on IndexedDB or SQLite instead of materializing every record with `getAll()`.\n\n## Use TTL and Pruning\n\nUse `ttl.*` helpers for expiring rows. Call `pruneExpired()` to reclaim storage from stale rows that accumulate without reads; tables with removed rows publish fresh observer snapshots.\n\n```ts\nimport { ttl } from '@vielzeug/vault';\n\nawait store.put('preferences', { id: 'temporary', theme: 'dark' }, ttl.hours(1));\n\n// Reclaim expired rows on a schedule owned by the application.\nconst pruneInterval = setInterval(() => store.pruneExpired(), ttl.hours(6));\nstore.disposalSignal.addEventListener('abort', () => clearInterval(pruneInterval));\n```\n\n## Observe a Table\n\nUse `observe()` for current and future snapshots. Notifications are revision-ordered, and explicit TTL pruning publishes fresh snapshots for affected tables. Tie subscription lifetime to an `AbortSignal` when a component or request owns it.\n\n```ts\nconst controller = new AbortController();\n\nstore.observe(\n 'preferences',\n (preferences) => {\n console.log(preferences);\n },\n { signal: controller.signal },\n);\n\ncontroller.abort();\n```\n\n## Use IndexedDB for Browser Transactions\n\nChoose IndexedDB when browser storage needs multiple writes to commit together or cursor iteration.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb';\n\nconst EventSchema = s.object({ id: s.number(), type: s.string() });\nconst db = createIndexedDB({\n name: 'app-v2',\n schema: { events: table<{ id: number; type: string }>('id') },\n parsers: { events: EventSchema },\n});\n\nawait db.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened' });\n await tx.put('events', { id: 2, type: 'saved' });\n});\n```\n\nTransaction contexts expose the same bound helpers; `tx.update()`, `tx.upsert()`, and `tx.deleteMany()` run inside the enclosing transaction. Only await `tx.*` operations inside a batch callback. Do not retain the transaction context after the callback; later use throws `VaultScopeError`. Do not await timers, fetches, or other external asynchronous work because IndexedDB can commit an inactive transaction.\n\n## Use SQLite Outside the Browser\n\nImport SQLite from the opt-in subpath so the browser root stays free of runtime drivers. Vault never opens a connection or configures its SQLite process behavior for you.\n\n```ts\nimport { DatabaseSync } from 'node:sqlite';\n\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createSQLite } from '@vielzeug/vault/sqlite';\n\nconst EventSchema = s.object({ id: s.number(), type: s.string() });\nconst database = new DatabaseSync('app.db', { timeout: 5_000 });\nconst store = createSQLite({\n database,\n name: 'app-v2',\n schema: { events: table<{ id: number; type: string }>('id') },\n parsers: { events: EventSchema },\n});\n\nawait store.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened' });\n await tx.put('events', { id: 2, type: 'saved' });\n});\n```\n\nNode's `node:sqlite` API is experimental. Bun's `bun:sqlite` `Database` satisfies the same positional `exec()` and `prepare()` contract; configure WAL from your application when the deployment needs it. Deno does not include SQLite, but `jsr:@db/sqlite`'s `Database` satisfies the same contract when its FFI, filesystem, and environment permissions are granted.\n\nSQLite stores serialize all access through the injected connection. `batch()` starts `BEGIN IMMEDIATE` and rolls back callback failures. While its callback runs, calls on any store sharing that connection reject rather than waiting behind the transaction; use `tx.*` instead. The underlying drivers are synchronous, so move large scans and writes to a worker or isolate when event-loop latency matters.\n\n## Store SQLite Values and Observe Changes\n\nSQLite stores records as JSON, so records must be JSON-compatible: circular values, `bigint`, and functions fail serialization, and parsers should reject anything a schema cannot represent (use ISO strings for dates). Number and string primary keys remain distinct.\n\n`observe()` sees mutations written through Vault stores sharing the same injected connection after a commit. It cannot detect direct SQL changes, writes from another process, or writes through another connection. The connection belongs to the caller by default; use `closeOnDispose: true` only when the store owns it.\n\n## Handle IndexedDB Schema Migrations\n\nDeclare IndexedDB indexes in the schema; other adapters ignore them and `getAllByIndex()` is IndexedDB-only. Because writes store the parser's canonical output, indexed fields always match what readers see. Use `migrate` only for IndexedDB version upgrades and mirror Vault's fixed `value.<field>` index path.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB, type MigrationFn } from '@vielzeug/vault/indexeddb';\n\nconst UserSchema = s.object({ id: s.number(), name: s.string() });\nconst schema = { users: table<{ id: number; name: string }>('id', { indexes: ['name'] }) };\nconst migrate: MigrationFn = ({ db, oldVersion, tx }) => {\n if (oldVersion < 2 && db.objectStoreNames.contains('users')) {\n tx.objectStore('users').createIndex('name', 'value.name');\n }\n};\n\ncreateIndexedDB({\n name: 'app-v2',\n migrate,\n schema,\n version: 2,\n parsers: { users: UserSchema },\n});\n```\n\n## Framework Integration\n\n::: code-group\n\n```ts [React]\nimport { useEffect, useState } from 'react';\n\nimport type { AnySchema, KeyValueVaultStore, RecordOf } from '@vielzeug/vault';\n\nexport function useTable<S extends AnySchema, K extends keyof S & string>(store: KeyValueVaultStore<S>, table: K) {\n const [rows, setRows] = useState<RecordOf<S, K>[]>([]);\n\n useEffect(() => store.observe(table, setRows), [store, table]);\n return rows;\n}\n```\n\n```ts [Vue 3]\nimport { onUnmounted, shallowRef } from 'vue';\n\nimport type { AnySchema, KeyValueVaultStore, RecordOf } from '@vielzeug/vault';\n\nexport function useTable<S extends AnySchema, K extends keyof S & string>(store: KeyValueVaultStore<S>, table: K) {\n const rows = shallowRef<RecordOf<S, K>[]>([]);\n const stop = store.observe(table, (next) => (rows.value = next));\n\n onUnmounted(stop);\n return rows;\n}\n```\n\n```ts [Svelte]\nimport { readable } from 'svelte/store';\n\nimport type { AnySchema, KeyValueVaultStore, RecordOf } from '@vielzeug/vault';\n\nexport function tableStore<S extends AnySchema, K extends keyof S & string>(store: KeyValueVaultStore<S>, table: K) {\n return readable<RecordOf<S, K>[]>([], (set) => store.observe(table, set));\n}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nKeep Ripple signals as application state and persist selected changes through Vault writes.\n\n## Best Practices\n\n- Define one schema per storage namespace.\n- Use string or finite-number primary keys only.\n- Provide parsers for every durable adapter; pass a Spell schema directly for validation or a bare `{ parse }` for passthrough.\n- Use `observe()` for table snapshots.\n- Use IndexedDB or SQLite for atomic work.\n- Keep external asynchronous work outside `batch()` callbacks.\n- Use `ttl.*` instead of raw durations.\n- Keep SQLite scans and writes off latency-sensitive event loops.\n- Dispose stores when their owner ends.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Vault: Examples'\ndescription: Practical Vault examples for browser storage, SQLite, TTL, transactions, observation, and framework integration.\n---\n\n## Browser Key-Value Store with TTL\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table, ttl } from '@vielzeug/vault';\nimport { createLocalStorage } from '@vielzeug/vault/local-storage';\n\ninterface Session {\n id: string;\n token: string;\n}\n\nconst SessionSchema = s.object({ id: s.string(), token: s.string() });\nconst store = createLocalStorage({\n name: 'app-v2',\n schema: { sessions: table<Session>('id', { defaultTtl: ttl.hours(1) }) },\n parsers: { sessions: SessionSchema },\n});\n\nawait store.put('sessions', { id: 'current', token: 'FAKE-TOKEN-FOR-DOCS' });\nconsole.log(await store.get('sessions', 'current'));\n```\n\n## IndexedDB with Transactions and Iteration\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb';\n\ninterface Event {\n id: number;\n type: string;\n createdAt: number;\n}\n\nconst EventSchema = s.object({ createdAt: s.number(), id: s.number(), type: s.string() });\nconst db = createIndexedDB({\n name: 'events',\n schema: { events: table<Event>('id', { indexes: ['type'] }) },\n parsers: { events: EventSchema },\n});\n\nawait db.batch(['events'], async (tx) => {\n await tx.put('events', { id: 1, type: 'opened', createdAt: Date.now() });\n await tx.put('events', { id: 2, type: 'saved', createdAt: Date.now() });\n});\n\nfor await (const event of db.iterate('events')) {\n console.log(event.type);\n}\n```\n\n## SQLite Document Store\n\n```ts\nimport { DatabaseSync } from 'node:sqlite';\n\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createSQLite } from '@vielzeug/vault/sqlite';\n\ninterface Job {\n id: string;\n status: 'queued' | 'running' | 'done';\n}\n\nconst JobSchema = s.object({ id: s.string(), status: s.enum(['queued', 'running', 'done']) });\nconst database = new DatabaseSync(':memory:');\nconst store = createSQLite({\n database,\n name: 'app',\n schema: { jobs: table<Job>('id') },\n parsers: { jobs: JobSchema },\n});\n\nawait store.batch(['jobs'], async (tx) => {\n await tx.put('jobs', { id: 'job-1', status: 'queued' });\n await tx.put('jobs', { id: 'job-2', status: 'running' });\n});\n\nfor await (const job of store.iterate('jobs')) {\n console.log(job.id, job.status);\n}\n```\n\n## Observe Table Changes\n\n```ts\nconst stop = store.observe('sessions', (sessions) => {\n console.log(`Active sessions: ${sessions.length}`);\n});\n\nstore.disposalSignal.addEventListener('abort', stop);\n```\n\n## Bound Helpers\n\n```ts\nconsole.log(await store.has('sessions', 'current'));\nconsole.log(await store.count('sessions'));\nconsole.log(await store.isEmpty('sessions'));\n\nconst [a, b] = await store.getMany('sessions', ['current', 'old']);\nconsole.log(await store.keys('sessions'));\nconsole.log(await store.deleteMany('sessions', ['old', 'expired']));\n\nawait store.update('sessions', 'current', { token: 'FAKE-UPDATED-TOKEN' });\nawait store.upsert('sessions', 'temp', (existing) => ({\n id: 'temp',\n token: existing?.token ?? 'generated',\n}));\n\nconst current = (await store.getAll('sessions')).find((session) => session.id === 'current');\nvoid a, b, current;\n```\n\n## React Hook\n\n```tsx\nimport { useEffect, useState } from 'react';\n\nimport type { AnySchema, KeyValueVaultStore, RecordOf } from '@vielzeug/vault';\n\nexport function useTable<S extends AnySchema, K extends keyof S & string>(\n store: KeyValueVaultStore<S>,\n table: K,\n): RecordOf<S, K>[] {\n const [rows, setRows] = useState<RecordOf<S, K>[]>([]);\n\n useEffect(() => store.observe(table, setRows), [store, table]);\n return rows;\n}\n```\n\n## Migration Example\n\nObject stores and schema-declared indexes are created automatically on upgrade. The `migrate` hook covers only what the schema cannot express, such as deleting a removed store or transforming old records.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { table } from '@vielzeug/vault';\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb';\n\nconst UserSchema = s.object({ email: s.string().email(), id: s.number() });\n\nconst db = createIndexedDB({\n name: 'app-v2',\n version: 2,\n migrate({ db, oldVersion, tx }) {\n // The 'users' store and its 'email' index already exist; drop a retired store.\n if (oldVersion < 2 && db.objectStoreNames.contains('legacy_sessions')) {\n tx.deleteObjectStore('legacy_sessions');\n }\n },\n schema: { users: table<{ id: number; email: string }>('id', { indexes: ['email'] }) },\n parsers: { users: UserSchema },\n});\n```\n\n## Recipe Examples\n\n- [CRUD Operations](./examples/crud.md)\n- [TTL and Pruning](./examples/ttl.md)\n- [IndexedDB Batch Transactions](./examples/batch.md)\n- [IndexedDB Lazy Iteration](./examples/iterate.md)\n- [SQLite Transactions and Iteration](./examples/sqlite.md)\n- [Reactive Tables with observe()](./examples/reactive.md)\n- [Validators and Error Handling](./examples/plugins.md)\n"
|
|
8
|
-
},
|
|
9
|
-
"examples": [
|
|
10
|
-
{
|
|
11
|
-
"id": "basic-setup",
|
|
12
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst UserSchema = s.object({ email: s.string().email(), id: s.number(), name: s.string() })\nconst schema = {\n users: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'demo',\n schema,\n parsers: { users: UserSchema },\n})\n\nawait db.put('users', { id: 1, name: 'Alice', email: 'alice@example.com' })\nawait db.put('users', { id: 2, name: 'Bob', email: 'bob@example.com' })\n\nconsole.log('Get user 1:', await db.get('users', 1))\nconsole.log('All users:', await db.getAll('users'))\nconsole.log('Count:', await db.count('users'))",
|
|
13
|
-
"name": "Basic Setup - Initialize Vault"
|
|
14
|
-
},
|
|
15
|
-
{
|
|
16
|
-
"id": "bulk-operations",
|
|
17
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst ItemSchema = s.object({ id: s.number(), value: s.number() })\nconst schema = {\n items: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'bulk-demo',\n schema,\n parsers: { items: ItemSchema },\n})\n\nconst items = Array.from({ length: 10 }, (_, index) => ({\n id: index + 1,\n value: +(Math.random() * 1000).toFixed(2),\n}))\n\nawait db.putAll('items', items)\nconsole.log('Inserted', items.length, 'items')\n\n// getMany: fetch multiple by key in one call (missing keys return undefined)\nconst [first, missing, third] = await db.getMany('items', [1, 99, 3])\nconsole.log('getMany [1, 99, 3]:', first?.id, missing, third?.id)\n\n// deleteMany: remove multiple by key, returns count deleted\nconst deleted = await db.deleteMany('items', [1, 2, 3, 99])\nconsole.log('deleteMany [1,2,3,99] deleted:', deleted) // 3 (99 did not exist)\n\n// filter-driven removal: getAll + filter + deleteMany\nconst remaining = await db.getAll('items')\nconst toDelete = remaining.filter((item) => item.id <= 6).map((item) => item.id)\nconst queryDeleted = await db.deleteMany('items', toDelete)\nconsole.log('Deleted items with id ≤ 6:', queryDeleted)\n\nconsole.log('Remaining count:', await db.count('items'))\nconsole.log('First remaining item:', (await db.getAll('items')).sort((a, b) => a.id - b.id)[0])",
|
|
18
|
-
"name": "Bulk Operations"
|
|
19
|
-
},
|
|
20
|
-
{
|
|
21
|
-
"id": "cache-first",
|
|
22
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table, ttl } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst CacheSchema = s.object({ data: s.string(), fetchedAt: s.number(), id: s.string() })\nconst db = createLocalStorage({\n name: 'cache-demo',\n schema: { cache: table('id') },\n parsers: { cache: CacheSchema },\n})\n\nasync function getOrComputeConfig() {\n const existing = await db.get('cache', 'config')\n if (existing) return existing\n\n const record = {\n id: 'config',\n data: 'computed value',\n fetchedAt: Date.now(),\n }\n await db.put('cache', record, ttl.minutes(5))\n return record\n}\n\nconst first = await getOrComputeConfig()\nconst second = await getOrComputeConfig()\nconsole.log('Same cached record:', first.fetchedAt === second.fetchedAt)",
|
|
23
|
-
"name": "Cache-First with get + put"
|
|
24
|
-
},
|
|
25
|
-
{
|
|
26
|
-
"id": "crud-operations",
|
|
27
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst UserSchema = s.object({ age: s.number(), email: s.string().email(), id: s.number(), name: s.string() })\nconst schema = {\n users: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'demo',\n schema,\n parsers: { users: UserSchema },\n})\n\nawait db.put('users', { id: 1, name: 'Alice', email: 'alice@example.com', age: 25 })\nawait db.put('users', { id: 2, name: 'Bob', email: 'bob@example.com', age: 30 })\nconsole.log('Created 2 users')\n\nconsole.log('Get user 1:', await db.get('users', 1))\nconsole.log('Count:', await db.count('users'))\nconsole.log('isEmpty before clear:', await db.isEmpty('users')) // false\n\nawait db.update('users', 1, { age: 26, name: 'Alice Smith' })\nconsole.log('Updated user 1:', await db.get('users', 1))\n\nconsole.log('Deleted user 2:', await db.delete('users', 2))\nconsole.log('Remaining users:', await db.getAll('users'))\n\nawait db.clear('users')\nconsole.log('isEmpty after clear:', await db.isEmpty('users')) // true",
|
|
28
|
-
"name": "CRUD Operations"
|
|
29
|
-
},
|
|
30
|
-
{
|
|
31
|
-
"id": "filtering",
|
|
32
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst ProductSchema = s.object({ category: s.string(), id: s.number(), inStock: s.boolean(), name: s.string(), price: s.number() })\nconst schema = {\n products: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'shop',\n schema,\n parsers: { products: ProductSchema },\n})\n\nawait db.putAll('products', [\n { id: 1, name: 'Laptop', price: 999, category: 'electronics', inStock: true },\n { id: 2, name: 'Mouse', price: 29, category: 'electronics', inStock: true },\n { id: 3, name: 'Desk', price: 299, category: 'furniture', inStock: false },\n { id: 4, name: 'Chair', price: 199, category: 'furniture', inStock: true },\n { id: 5, name: 'Monitor', price: 399, category: 'electronics', inStock: true },\n])\n\n// getAll() returns a plain array: compose with standard array operations\nconst all = await db.getAll('products')\nconst electronics = all\n .filter((product) => product.category === 'electronics' && product.inStock)\n .sort((a, b) => a.price - b.price)\n\nconst pageSize = 2\nconst pageIndex = 0\nconst page = electronics.slice(pageIndex * pageSize, (pageIndex + 1) * pageSize)\n\nconsole.log('Page:', page.map((p) => p.name))\nconsole.log('Total matching:', electronics.length)\nconsole.log('Page 1 of', Math.ceil(electronics.length / pageSize))\n\n// prefix match\nconst mice = all.filter((product) => product.name.toLowerCase().startsWith('m'))\nconsole.log('Starts with m:', mice.map((p) => p.name))\n\n// deletion via deleteMany with the keys to remove\nconst outOfStock = all.filter((product) => !product.inStock).map((product) => product.id)\nconsole.log('Removed out-of-stock:', await db.deleteMany('products', outOfStock))\n\nconst cheapest = (await db.getAll('products')).sort((a, b) => a.price - b.price)[0]\nconsole.log('Cheapest:', cheapest?.name, cheapest?.price)\n\nconsole.log('Remaining count:', await db.count('products'))",
|
|
33
|
-
"name": "Filtering: getAll composition, pagination, and deletion"
|
|
34
|
-
},
|
|
35
|
-
{
|
|
36
|
-
"id": "indexed-db",
|
|
37
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table, ttl } from '@vielzeug/vault'\nimport { createIndexedDB } from '@vielzeug/vault/indexeddb'\n\nconst LogSchema = s.object({ id: s.number(), level: s.string(), message: s.string(), ts: s.number() })\nconst schema = {\n logs: table('id'),\n}\n\n// createIndexedDB returns DocumentVaultStore with transactions and cursor iteration\nconst db = createIndexedDB({\n name: 'app-logs',\n schema,\n parsers: { logs: LogSchema },\n version: 1,\n})\n\nawait db.putAll('logs', [\n { id: 1, level: 'info', message: 'App started', ts: Date.now() - 3000 },\n { id: 2, level: 'warn', message: 'Slow query detected', ts: Date.now() - 2000 },\n { id: 3, level: 'error', message: 'Request failed', ts: Date.now() - 1000 },\n { id: 4, level: 'info', message: 'Request succeeded', ts: Date.now() },\n], ttl.hours(1))\n\n// batch() is atomic on IndexedDB: all writes commit or none do\nawait db.batch(['logs'], async (tx) => {\n await tx.put('logs', { id: 5, level: 'info', message: 'Batch committed', ts: Date.now() })\n await tx.delete('logs', 1)\n await tx.delete('logs', 2)\n})\n\n// iterate(): cursor-based streaming, only on DocumentVaultStore\n// the full table is never loaded into memory at once\nconst messages = []\nfor await (const entry of db.iterate('logs')) {\n messages.push(entry.message)\n}\nconsole.log('Streamed via iterate():', messages)\n\nconst errors = (await db.getAll('logs')).filter((entry) => entry.level === 'error')\nconsole.log('Errors:', errors.map((e) => e.message))\nconsole.log('Total logs:', await db.count('logs'))\n\n// pruneExpired() reclaims storage from TTL-expired records that haven't been read\nconst pruned = await db.pruneExpired()\nconsole.log('Pruned:', pruned)\n\nawait db.dispose()",
|
|
38
|
-
"name": "IndexedDB: Atomic Batch & iterate()"
|
|
39
|
-
},
|
|
40
|
-
{
|
|
41
|
-
"id": "prune-schedule",
|
|
42
|
-
"code": "import { table, ttl } from '@vielzeug/vault'\nimport { createMemory } from '@vielzeug/vault/memory'\n\n// pruneExpired() sweeps all tables and removes expired records.\n// Schedule it with setInterval and cancel on disposalSignal.\n\nconst schema = { sessions: table('token') }\nconst db = createMemory({ schema })\n\nconst pruneInterval = setInterval(() => db.pruneExpired(), ttl.minutes(15))\ndb.disposalSignal.addEventListener('abort', () => clearInterval(pruneInterval))\n\n// Write a session that expires in 1 ms\nawait db.put('sessions', { token: 'FAKE-TOKEN-ONE', user: 1 }, ttl.ms(1))\nawait db.put('sessions', { token: 'FAKE-TOKEN-TWO', user: 2 }) // no TTL: permanent\n\nconsole.log('before prune:', await db.count('sessions')) // 2 (lazy eviction: both exist physically)\n\n// Manual prune to demonstrate the API\nawait new Promise((resolve) => setTimeout(resolve, 5))\nconst pruned = await db.pruneExpired()\nconsole.log('pruned:', pruned.sessions) // 1 (the expired session)\nconsole.log('after prune:', await db.count('sessions')) // 1\n\nawait db.dispose()",
|
|
43
|
-
"name": "TTL: pruneExpired with disposalSignal"
|
|
44
|
-
},
|
|
45
|
-
{
|
|
46
|
-
"id": "reactive-observe",
|
|
47
|
-
"code": "import { table } from '@vielzeug/vault'\nimport { createMemory } from '@vielzeug/vault/memory'\n\nconst db = createMemory({ schema: { users: table('id') } })\nconst snapshots = []\nconst stop = db.observe('users', (users) => snapshots.push(users.map((user) => user.name)))\n\nawait Promise.resolve()\nawait db.put('users', { id: 1, name: 'Ada' })\nawait Promise.resolve()\n\nconsole.log(snapshots) // [[], ['Ada']]\nstop()\nawait db.dispose()",
|
|
48
|
-
"name": "Reactive: observe()"
|
|
49
|
-
},
|
|
50
|
-
{
|
|
51
|
-
"id": "ttl-expiration",
|
|
52
|
-
"code": "import { s } from '@vielzeug/spell'\nimport { table, ttl } from '@vielzeug/vault'\nimport { createLocalStorage } from '@vielzeug/vault/local-storage'\n\nconst CacheSchema = s.object({ data: s.string(), id: s.string() })\nconst schema = {\n cache: table('id'),\n}\n\nconst db = createLocalStorage({\n name: 'cache-demo',\n schema,\n parsers: { cache: CacheSchema },\n})\n\n// ttl helpers produce finite, positive millisecond durations\nawait db.put('cache', { id: 'short', data: 'Expires in 1 second' }, ttl.seconds(1))\nawait db.put('cache', { id: 'long', data: 'Expires in 5 minutes' }, ttl.minutes(5))\nconsole.log('Stored records with TTL')\nconsole.log('Immediate read:', await db.get('cache', 'short'))\n\nawait new Promise((resolve) => setTimeout(resolve, 1500))\nconsole.log('After 1.5s:', await db.get('cache', 'short')) // expired: undefined\nconsole.log('Long-lived still here:', await db.get('cache', 'long'))\n\nconsole.log('ttl helpers:', {\n '100ms': ttl.ms(100),\n '5 minutes': ttl.minutes(5),\n '2 hours': ttl.hours(2),\n '7 days': ttl.days(7),\n})",
|
|
53
|
-
"name": "TTL & Expiration"
|
|
54
|
-
}
|
|
55
|
-
],
|
|
56
|
-
"typeSignatures": {
|
|
57
|
-
"VaultDisposedError": "export { VaultDisposedError, VaultError, VaultMigrationError, VaultQuotaError, VaultScopeError } from './errors';",
|
|
58
|
-
"VaultError": "export { VaultDisposedError, VaultError, VaultMigrationError, VaultQuotaError, VaultScopeError } from './errors';",
|
|
59
|
-
"VaultMigrationError": "export { VaultDisposedError, VaultError, VaultMigrationError, VaultQuotaError, VaultScopeError } from './errors';",
|
|
60
|
-
"VaultQuotaError": "export { VaultDisposedError, VaultError, VaultMigrationError, VaultQuotaError, VaultScopeError } from './errors';",
|
|
61
|
-
"VaultScopeError": "export { VaultDisposedError, VaultError, VaultMigrationError, VaultQuotaError, VaultScopeError } from './errors';",
|
|
62
|
-
"ttl": "export { ttl } from './ttl';",
|
|
63
|
-
"AnySchema": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
64
|
-
"DocumentVaultStore": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
65
|
-
"DurableStoreOptions": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
66
|
-
"KeyOf": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
67
|
-
"KeyValueVaultStore": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
68
|
-
"MemoryStoreOptions": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
69
|
-
"Observer": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
70
|
-
"ObserverErrorHandler": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
71
|
-
"RecordOf": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
72
|
-
"RecordParser": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
73
|
-
"SchemaEntry": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
74
|
-
"TableParsers": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
75
|
-
"TransactionContext": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
76
|
-
"Unsubscribe": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
77
|
-
"VaultConveniences": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
78
|
-
"VaultKey": "export type {\n AnySchema,\n DocumentVaultStore,\n DurableStoreOptions,\n KeyOf,\n KeyValueVaultStore,\n MemoryStoreOptions,\n Observer,\n ObserverErrorHandler,\n RecordOf,\n RecordParser,\n SchemaEntry,\n TableParsers,\n TransactionContext,\n Unsubscribe,\n VaultConveniences,\n VaultKey,\n} from './types';",
|
|
79
|
-
"table": "export { table } from './types';"
|
|
80
|
-
}
|
|
81
|
-
}
|