@vielzeug/codex 26.11.15 → 26.11.17

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.
@@ -1,9 +1,9 @@
1
1
  {
2
- "apiSource": "export { toFilterPredicate, toSearchMatcher } from './adapters';\nexport {\n dedupeEntries,\n escapeRegExp,\n type RankableEntry,\n rankEntries,\n type SplitSegment,\n splitPattern,\n} from './entries';\nexport { ScoutConfigError, ScoutDisposedError, ScoutError } from './errors';\nexport { findMatchRanges, highlight, highlightField } from './highlight';\nexport type { ReactiveSearch } from './reactive';\nexport { createReactiveSearch, createSearch } from './reactive';\nexport type { ScoutIndex } from './scout-index';\nexport { createIndex } from './scout-index';\nexport { segmentWords } from './segment';\nexport type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';\n",
2
+ "apiSource": "export { toFilterPredicate, toSearchMatcher } from './adapters';\nexport {\n dedupeEntries,\n escapeRegExp,\n type RankableEntry,\n rankEntries,\n type SplitSegment,\n splitPattern,\n} from './entries';\nexport { ScoutConfigError, ScoutDisposedError, ScoutError } from './errors';\nexport { findMatchRanges, highlight, highlightField } from './highlight';\nexport { createSearch } from './reactive';\nexport type { ScoutIndex } from './scout-index';\nexport { createIndex } from './scout-index';\nexport { segmentWords } from './segment';\nexport type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';\n",
3
3
  "docs": {
4
- "index": "---\ntitle: 'Scout: Fast fuzzy search for TypeScript'\ndescription: Trigram-indexed fuzzy search with per-field weights, match highlighting, and an optional reactive layer.\npackage: scout\ncategory: utilities\nkeywords: [fuzzy-search, search, trigram, full-text, filter, highlight, reactive, ripple]\nexports:\n [\n createIndex,\n createReactiveSearch,\n createSearch,\n ScoutConfigError,\n ScoutDisposedError,\n ScoutError,\n findMatchRanges,\n highlight,\n highlightField,\n segmentWords,\n toFilterPredicate,\n toSearchMatcher,\n ]\nrelated: [arsenal, sourcerer, vault, ripple]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"scout\" />\n\n## Why Scout?\n\nArsenal's `fuzzy` / `fuzzyFilter` helpers perform pairwise Levenshtein distance: O(n·m) per item per query. For ≤200 items they are fine. For 500–100k items with real-time keystrokes, you need an index.\n\nScout builds a **trigram inverted index** at construction time. Query time scores only items sharing a trigram with the query; broad queries can still approach O(n), while selective queries avoid scoring the whole corpus.\n\n```ts\n// Before\nconst matches = users.filter((user) => user.name.toLowerCase().includes(query.toLowerCase()));\n\n// After\nimport { createIndex } from '@vielzeug/scout';\n\nconst index = createIndex(users, { fields: ['name', 'email'] });\nconst matches = index.search(query);\n```\n\n| Feature | Arsenal `fuzzy*` | Scout `createIndex` | Fuse.js |\n| ------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | ~3 KB | <PackageInfo package=\"scout\" type=\"size\" /> | ~23 KB |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Algorithm | Levenshtein | Trigram + overlap coefficient | Bitap |\n| Query time | O(n·m) | O(candidates) | O(n·m) |\n| Stateful index | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Match highlighting | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Reactive layer | <ore-icon name=\"x\" size=\"16\"></ore-icon> | Atomic external-store snapshots + debounce | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Incremental updates | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial |\n\n<div class=\"decision-callout\">\n\n**Use Scout when** you need search over 500+ items, real-time UI search boxes (combobox, command palette), or framework-neutral subscribable search state.\n\n**Consider `arsenal.fuzzyFilter` when** you have fewer than 200 items and don't need a persistent index.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/scout\n```\n\n```sh [npm]\nnpm install @vielzeug/scout\n```\n\n```sh [yarn]\nyarn add @vielzeug/scout\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createIndex } from '@vielzeug/scout';\n\nconst users = [\n { email: 'ada@example.com', name: 'Ada Lovelace' },\n { email: 'grace@example.com', name: 'Grace Hopper' },\n];\n\nconst index = createIndex(users, {\n fields: [{ field: 'name', weight: 2 }, { field: 'email' }],\n});\n\nconst results = index.search('ada');\nconsole.log(results[0]?.item.name); // Ada Lovelace\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createIndex()`: Trigram inverted index; construction O(corpus × field_length), query O(candidates)\n- Per-field weights: Promote `name` matches over secondary fields; finite positive weights and custom `stringify` functions supported\n- `createReactiveSearch()`: Index + reactive `SearchState` in one call; `.index` for incremental mutations\n- `createSearch()`: Reactive search state backed by an existing `ScoutIndex`; share one index across many states\n- `highlight()` / `highlightField()`: Split field text into `HighlightPart[]` fragments for styled rendering\n- `findMatchRanges()`: Compute match ranges for custom display strings (truncated previews, formatted values)\n- `toSearchMatcher()`: Matcher adapter for filtering in-memory collections with a `ScoutIndex`\n- `toFilterPredicate()`: Snapshot `(item: T) => boolean` predicate for `Array.filter` or vault queries\n- `setItems()`: Reconcile a refreshed corpus by reference, preserve incoming order, and notify once\n- Incremental updates: `add()` / `remove()` / `reindex()` patch individual items in O(field_length)\n- `onMutate()`: Subscribe to index mutations; powers `createSearch()`'s reactivity and bulk reconciliation\n- `segmentWords()`: Split unsegmented-script text (CJK, Thai, ...) into words via native `Intl.Segmenter`\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- [Arsenal](/arsenal/): Use `fuzzyFilter` for ad-hoc filtering of small lists (< 200 items) without building an index\n- [Ripple](/ripple/): bridge a complete Scout `SearchState` with `fromSubscribable()` when composing a larger reactive graph\n- [Sourcerer](/sourcerer/): use a `ScoutIndex` matcher to filter in-memory collections alongside remote sources\n- [Vault](/vault/): `toFilterPredicate()` wraps a one-time Scout query as a vault-compatible `filter()` predicate\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Scout: API Reference'\ndescription: 'Complete API reference for @vielzeug/scout: createIndex, createReactiveSearch, createSearch, highlight, highlightField, toSearchMatcher, toFilterPredicate.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------ | --------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------- |\n| `createIndex()` | Build trigram index from an item array | Sync | Index is built at call time: pass all initial items |\n| `ScoutIndex.search()` | Query the index, returns scored + highlighted results | Sync | Empty query returns all items with `score = 1` |\n| `ScoutIndex.add()` | Add one item to the index | Sync | No-op if same reference already indexed |\n| `ScoutIndex.remove()` | Remove one item by reference | Sync | No-op for unknown references |\n| `ScoutIndex.reindex()` | Re-index a mutated item in-place; preserves order | Sync | Call after mutating item properties; no-op if not in index |\n| `ScoutIndex.setItems()` | Reconcile a refreshed corpus in one mutation | Sync | Uses reference identity; duplicate references collapse |\n| `ScoutIndex.items` | All indexed items in insertion order | Sync | Returns a new array snapshot each call |\n| `ScoutIndex.revision` | Monotonic counter incremented after each mutation | Sync | Use as a cache-busting token for external result caches |\n| `ScoutIndex.onMutate()` | Subscribe to changed index mutations | Sync | A changed `setItems()` reconciliation emits once; no-ops emit nothing |\n| `createSearch()` | Atomic search store backed by a `ScoutIndex` | Sync | Read one snapshot and dispose the store when done |\n| `createReactiveSearch()` | One-call index + reactive search state | Sync | Exposes `.index` for incremental mutations |\n| `findMatchRanges()` | Compute match ranges for a text + query pair | Sync | Returns sorted, non-overlapping `[start, end]` ranges |\n| `highlight()` | Split text into highlighted/unhighlighted fragments | Sync | Ranges must be sorted and non-overlapping |\n| `highlightField()` | Highlight a named field from a `SearchResult` | Sync | Shorthand for the `matches.find(…).ranges → highlight()` pattern |\n| `toSearchMatcher()` | Adapt `ScoutIndex` to Sourcerer's local `filter` callback | Sync | Recomputes cached query matches after index mutation |\n| `toFilterPredicate()` | Snapshot predicate from a one-time query | Sync | Re-call when query or corpus changes |\n| `segmentWords()` | Split unsegmented-script text (CJK, Thai, ...) into words | Sync | Uses native `Intl.Segmenter`: not applied inside `tokenize()` itself (see Pitfalls) |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ----------------- | ---------------------------------------------------------------------------------------------------------------------- |\n| `@vielzeug/scout` | All exports: index/search/highlighting/adapters, `ScoutConfigError`, `ScoutDisposedError`, `ScoutError`, and all types |\n\n---\n\n## `createIndex(items, options)`\n\nBuilds a trigram inverted index from `items`. Construction is O(corpus × field_length); subsequent `search()` calls are O(candidates).\n\n```ts\nfunction createIndex<T>(items: T[], options: ScoutIndexOptions<T>): ScoutIndex<T>;\n```\n\n**Parameters**\n\n| Param | Type | Description |\n| ------------------------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------ |\n| `items` | `T[]` | Initial corpus to index. |\n| `options.fields` | `ReadonlyArray<FieldDef<T>>` | Fields to index. Required; at least one entry. |\n| `options.threshold` | `number` | Finite overlap score in `0..1` (default `0.2`). |\n| `options.limit` | `number` | Finite non-negative integer max results (default `50`). |\n| `options.minQueryLength` | `number` | Finite positive integer min chars before trigram scoring; shorter queries use O(n) containment scan (default `3`). |\n\n**Example**\n\n```ts\nimport { createIndex } from '@vielzeug/scout';\n\nconst products = [\n { sku: 'WGT-001', title: 'Widget Pro' },\n { sku: 'GAD-002', title: 'Gadget Plus' },\n];\n\nconst index = createIndex(products, {\n fields: [{ field: 'title', weight: 2 }, { field: 'sku' }],\n threshold: 0.25,\n limit: 20,\n});\n```\n\n---\n\n## `ScoutIndex<T>`\n\nReturned by `createIndex()`.\n\n### `.search(query, options?)`\n\n```ts\nsearch(query: string, options?: SearchConstraints): SearchResult<T>[]\n```\n\nReturns results sorted by score descending. Empty query returns all items with `score = 1`. Results below `threshold` are excluded; at most `limit` results are returned.\n\n```ts\nconst results = index.search('alice');\n// [{ item, score, matches }]\n```\n\n### `.add(item)`\n\nAdds `item` to the index. No-op if the same reference is already indexed. O(field_length).\n\n### `.remove(item)`\n\nRemoves `item` by reference equality. No-op if not found. O(field_length).\n\n### `.reindex(item)`\n\nRe-reads the item's current field values and rebuilds its index entry in-place, updating only fields whose values changed. Preserves insertion order. No-op if the item is not in the index.\n\n```ts\nitem.name = 'new name';\nindex.reindex(item);\n```\n\n### `.setItems(items)`\n\n```ts\nsetItems(items: readonly T[]): void\n```\n\nReconciles the index to a refreshed corpus in one mutation. Existing references are reindexed, missing references are removed, added references are indexed, and incoming first-occurrence order becomes index order. Duplicate references collapse to one item. Calls `onMutate()` once when indexed values, membership, or order changes.\n\n```ts\nindex.setItems(latestUsers);\n```\n\n### `.size`\n\n`number`: current number of indexed items.\n\n### `.items`\n\n`readonly T[]`: all indexed items in insertion order. Returns a new array snapshot each call.\n\n```ts\nconst all = index.items;\n```\n\n### `.onMutate(listener)`\n\n```ts\nonMutate(listener: () => void): () => void\n```\n\nSubscribes `listener` to run after every changed `add()` / `remove()` / `reindex()` / `setItems()` operation. No-ops, including unchanged bulk reconciliation, do not fire it. A changed `setItems()` reconciliation fires once. `createSearch()` uses this internally to keep `results` in sync with index mutations; most callers building on `createIndex()` directly will not need it.\n\n```ts\nconst unsubscribe = index.onMutate(() => {\n console.log(`Index changed: now ${index.size} items`);\n});\n\nindex.add(newUser); // logs \"Index changed: now 6 items\"\nunsubscribe();\n```\n\n### `.revision`\n\n`number`: monotonically increasing counter, incremented after every changed `add()` / `remove()` / `reindex()` / `setItems()` operation. Use as a cache-busting token when caching search results outside the index: `toSearchMatcher()` uses it for this purpose.\n\n---\n\n## `createSearch(index, options?)`\n\nWraps a `ScoutIndex` in a zero-dependency external store. `getSnapshot()` returns the current query, loading flag, and results as one consistent snapshot; `subscribe()` notifies after the complete snapshot is committed.\n\n```ts\nfunction createSearch<T>(index: ScoutIndex<T>, options?: CreateSearchOptions): SearchState<T>;\n```\n\n**Parameters**\n\n| Param | Type | Description |\n| ------------------------ | -------- | ------------------------------------------------------------------------------------------------------------- |\n| `options.debounce` | `number` | Finite non-negative integer milliseconds before query commit (default `200`). Pass `0` for immediate updates. |\n| `options.limit` | `number` | Finite non-negative integer override of index-level limit. |\n| `options.threshold` | `number` | Finite `0..1` override of index-level threshold. |\n| `options.minQueryLength` | `number` | Finite positive integer override of index-level minimum query length. |\n\n**Returns `SearchState<T>`**\n\n| Member | Type | Description |\n| ------------------------------- | ------------------------------------ | ------------------------------------------------------------------------------------ |\n| `getSnapshot()` | `() => SearchSnapshot<T>` | Returns the stable current snapshot. Identity changes only after a state transition. |\n| `setQuery(query)` | `(query: string) => void` | Starts or immediately commits a query according to `debounce`. |\n| `subscribe(listener, options?)` | `(listener, options?) => () => void` | Notifies after an atomic snapshot commit. Supports `{ signal }` cleanup. |\n| `tap(handler, options?)` | `(handler, options?) => () => void` | Observes typed state and disposal events. Handler errors are swallowed. |\n| `disposalSignal` | `AbortSignal` | Aborted when `dispose()` is called. Use to tie other lifecycles to this search. |\n| `disposed` | `boolean` | `true` after `dispose()` has been called. |\n| `clear()` | `() => void` | Resets query, cancels debounce, and restores empty-query results synchronously. |\n| `dispose()` | `() => void` | Releases timers and subscriptions. |\n| `[Symbol.dispose]()` | `() => void` | `using`-compatible disposal. |\n\n**Example**\n\n```ts\nimport { createIndex, createSearch } from '@vielzeug/scout';\n\nconst users = [{ name: 'Ada Lovelace' }, { name: 'Grace Hopper' }];\nconst index = createIndex(users, { fields: ['name'] });\nconst search = createSearch(index, { debounce: 150 });\n\nsearch.subscribe(() => {\n console.log(search.getSnapshot().results.map((result) => result.item.name));\n});\n\nsearch.setQuery('ada');\n```\n\n---\n\n## `createReactiveSearch(items, options)`\n\nCreates a `ScoutIndex` and a reactive `SearchState` in one call: the shorthand for `createIndex` + `createSearch`. Returns a `ReactiveSearch<T>` which extends `SearchState<T>` with a `.index` property for incremental mutations.\n\n```ts\nfunction createReactiveSearch<T>(items: T[], options: ScoutIndexOptions<T> & { debounce?: number }): ReactiveSearch<T>;\n```\n\n**Parameters**\n\n| Param | Type | Description |\n| ------------------------ | ---------------------------- | ----------------------------------------------------------------------- |\n| `items` | `T[]` | Initial corpus to index. |\n| `options.fields` | `ReadonlyArray<FieldDef<T>>` | Fields to index. Required. |\n| `options.debounce` | `number` | Finite non-negative integer debounce milliseconds (default `200`). |\n| `options.threshold` | `number` | Finite overlap score in `0..1` (default `0.2`). |\n| `options.limit` | `number` | Finite non-negative integer max results (default `50`). |\n| `options.minQueryLength` | `number` | Finite positive integer min chars before trigram scoring (default `3`). |\n\n**Returns `ReactiveSearch<T>`**: all `SearchState<T>` members plus:\n\n| Member | Type | Description |\n| ------- | --------------- | ---------------------------------------------------- |\n| `index` | `ScoutIndex<T>` | The underlying index for `add`, `remove`, `reindex`. |\n\n**Example**\n\n```ts\nimport { createReactiveSearch } from '@vielzeug/scout';\n\nconst users = [{ email: 'ada@example.com', name: 'Ada Lovelace' }];\nconst search = createReactiveSearch(users, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n debounce: 150,\n});\n\nsearch.subscribe(() => console.log(search.getSnapshot().results.map((result) => result.item.name)));\n\nsearch.index.add({ email: 'grace@example.com', name: 'Grace Hopper' });\nsearch.dispose();\n```\n\n---\n\n## `findMatchRanges(text, query)`\n\nNormalizes raw `query` with Scout's tokenizer, then computes sorted, non-overlapping literal ranges for each normalized token within `text`. Useful when you need to apply highlighting to a different string than the indexed field value (e.g. a truncated preview or a differently formatted display string).\n\n```ts\nfunction findMatchRanges(text: string, query: string): [number, number][];\n```\n\n**Example**\n\n```ts\nimport { findMatchRanges, highlight } from '@vielzeug/scout';\n\nconst ranges = findMatchRanges('Alice Johnson', 'alice!');\n// [[0, 5]]\n\nconst parts = highlight('Alice Johnson', ranges);\n// [{ text: 'Alice', highlighted: true }, { text: ' Johnson', highlighted: false }]\n```\n\nReturns an empty array if either `text` or `query` is empty.\n\n---\n\n## `highlight(text, ranges)`\n\nSplits `text` into `HighlightPart[]` fragments based on `ranges` from `FieldMatch.ranges`.\n\n```ts\nfunction highlight(text: string, ranges: [number, number][]): HighlightPart[];\n```\n\n**Example**\n\n```ts\nimport { highlight } from '@vielzeug/scout';\n\nhighlight('Hello World', [[0, 5]]);\n// [{ text: 'Hello', highlighted: true }, { text: ' World', highlighted: false }]\n```\n\nReturns an empty array when `text` is empty. Returns a single unhighlighted part when `ranges` is empty.\n\n---\n\n## `highlightField(result, field, text)`\n\nConvenience shorthand that finds the match ranges for `field` in `result.matches` and calls `highlight()` in one step. Eliminates the manual `result.matches.find(m => m.field === …).ranges` lookup.\n\n```ts\nfunction highlightField<T>(result: SearchResult<T>, field: keyof T & string, text: string): HighlightPart[];\n```\n\n**Example**\n\n```ts\nimport { createIndex, highlightField } from '@vielzeug/scout';\n\nconst users = [{ name: 'Alice Johnson' }];\nconst index = createIndex(users, { fields: ['name'] });\n\nfor (const result of index.search('alice')) {\n const parts = highlightField(result, 'name', result.item.name);\n console.log(parts.map((part) => (part.highlighted ? `[${part.text}]` : part.text)).join(''));\n}\n```\n\nWhen the field has no match (e.g. the query matched via a different field), returns a single unhighlighted part.\n\n---\n\n## `toSearchMatcher(index, options?)`\n\nReturns an `(item, query) => boolean` matcher compatible with Sourcerer's local `filter` option.\n\n```ts\nfunction toSearchMatcher<T>(index: ScoutIndex<T>, options?: SearchConstraints): (item: T, query: string) => boolean;\n```\n\nOne matching-item set is cached per query and index revision, so filtering does not repeat index work per item and stays current after index mutation.\n\n```ts\nimport { createIndex, toSearchMatcher } from '@vielzeug/scout';\nimport { createLocalSource } from '@vielzeug/sourcerer';\n\nconst users = [{ email: 'ada@example.com', name: 'Ada Lovelace' }];\nconst index = createIndex(users, { fields: ['name', 'email'] });\nconst source = createLocalSource(users, { filter: toSearchMatcher(index), params: '' });\n\nsource.setParams('ada');\n```\n\n---\n\n## `toFilterPredicate(index, query, options?)`\n\nReturns a `(item: T) => boolean` predicate computed from a one-time query. Use with `Array.filter` or vault's `query.filter()`.\n\n```ts\nfunction toFilterPredicate<T>(index: ScoutIndex<T>, query: string, options?: SearchConstraints): (item: T) => boolean;\n```\n\nThe predicate is a snapshot: re-call `toFilterPredicate` if the query or corpus changes.\n\n```ts\nimport { createIndex, toFilterPredicate } from '@vielzeug/scout';\n\nconst products = [{ title: 'Widget Pro' }, { title: 'Gadget Plus' }];\nconst index = createIndex(products, { fields: ['title'] });\nconst results = products.filter(toFilterPredicate(index, 'widget'));\n\nconst top5 = products.filter(toFilterPredicate(index, 'widget', { limit: 5 }));\n```\n\n---\n\n## `segmentWords(text)`\n\nSplits `text` into whitespace-joined word segments using the runtime's native `Intl.Segmenter`: no dependency beyond the platform API. Falls back to returning `text` unchanged where `Intl.Segmenter` isn't available.\n\n```ts\nfunction segmentWords(text: string): string;\n```\n\n`tokenize()`'s trigram-based scoring already works on unsegmented scripts (Chinese, Japanese, Thai, ...) without this: trigrams are generated per-character, not per-word. `segmentWords()` is for `findMatchRanges()` / highlighting and the multi-word query semantics on `SearchConstraints`, which assume space-separated words. **Not applied inside `tokenize()` itself**: benchmarked at ~15x slower than the plain regex path for the common whitespace-delimited case, which would regress `createIndex()`'s construction cost for every caller, not just those indexing unsegmented scripts.\n\n**Example**\n\n```ts\nimport { createIndex, segmentWords } from '@vielzeug/scout';\n\nconst documents = [{ title: '日本語を勉強しています' }];\nconst index = createIndex(documents, {\n fields: [{ field: 'title', stringify: (value) => segmentWords(String(value)) }],\n});\n```\n\n---\n\n## Types\n\n### `SearchConstraints`\n\nShared search-tuning knobs used by `ScoutIndexOptions`, `CreateSearchOptions`, and all search functions.\n\n```ts\ntype SearchConstraints = {\n limit?: number; // finite non-negative integer; default 50\n minQueryLength?: number; // finite positive integer; default 3\n threshold?: number; // finite 0..1 value; default 0.2\n};\n```\n\n### `FieldDef<T>`\n\n```ts\ntype FieldDef<T> =\n | (keyof T & string)\n | {\n field: keyof T & string;\n weight?: number; // default 1\n stringify?: (value: unknown) => string;\n };\n```\n\n### `ScoutIndexOptions<T>`\n\n```ts\ntype ScoutIndexOptions<T> = SearchConstraints & {\n fields: ReadonlyArray<FieldDef<T>>;\n};\n```\n\n### `CreateSearchOptions`\n\n```ts\ntype CreateSearchOptions = SearchConstraints & {\n debounce?: number; // finite non-negative integer; default 200\n};\n```\n\n### `SearchResult<T>`\n\n```ts\ntype SearchResult<T> = {\n item: T;\n matches: FieldMatch<keyof T & string>[]; // literal normalized-token ranges; may be empty for fuzzy-only results\n score: number; // [0, 1]; 1 when query is empty\n};\n```\n\n### `FieldMatch<F>`\n\nGeneric over the union of field names: `match.field` is typed to the actual fields of `T`.\n\n```ts\ntype FieldMatch<F extends string = string> = {\n field: F;\n ranges: [number, number][]; // literal normalized-token [start, end] ranges in original field value\n};\n```\n\n### `HighlightPart`\n\n```ts\ntype HighlightPart = {\n highlighted: boolean;\n text: string;\n};\n```\n\n### `SearchSnapshot<T>`\n\n```ts\ntype SearchSnapshot<T> = Readonly<{\n isSearching: boolean;\n query: string;\n results: ReadonlyArray<SearchResult<T>>;\n}>;\n```\n\nSnapshots and their result arrays are frozen at runtime.\n\n### `ScoutEvent<T>`\n\n```ts\ntype ScoutEvent<T> = { readonly snapshot: SearchSnapshot<T>; readonly type: 'state-change' };\n```\n\n### `SearchState<T>`\n\n```ts\ntype SearchState<T> = {\n readonly disposalSignal: AbortSignal;\n readonly disposed: boolean;\n clear(): void;\n dispose(): void;\n getSnapshot(): SearchSnapshot<T>;\n setQuery(query: string): void;\n subscribe(listener: () => void, options?: { signal?: AbortSignal }): () => void;\n tap(handler: (event: ScoutEvent<T>) => void, options?: { signal?: AbortSignal }): () => void;\n [Symbol.dispose](): void;\n};\n```\n\n`subscribe()` observers are notified after the full snapshot commits. An observer error is reported asynchronously after the remaining observers run. `tap()` emits `state-change` only: disposal is observable through `disposed` and `disposalSignal`; tapper errors are swallowed.\n\n### `ReactiveSearch<T>`\n\n```ts\ntype ReactiveSearch<T> = SearchState<T> & {\n readonly index: ScoutIndex<T>;\n};\n```\n\nSee `createReactiveSearch()` above.\n\n---\n\n## Errors\n\n### `ScoutError`\n\nBase class for all scout errors. Use `instanceof ScoutError` to catch any scout-originated error.\n\n```ts\nclass ScoutError extends Error {}\n```\n\n**Named subclasses**\n\n| Class | Thrown when |\n| -------------------- | ------------------------------------------------------------------------------- |\n| `ScoutConfigError` | An index, search, or reactive search receives invalid fields or numeric options |\n| `ScoutDisposedError` | A method is called on a disposed `SearchState` instance |\n\n## Entry Ranking\n\nReference lists: glossaries, rule compendiums, profile directories: rank and render through the same helpers.\n\n### `rankEntries(entries, query, options?)`\n\nOrders `RankableEntry` items (`{ id, label, meta, text }`) by how directly they match the query: exact label, label prefix, label contains, meta contains, text contains, and finally `options.fuzzyIds` hits as last resort. Non-matching entries drop; ties break alphabetically. A blank query returns every entry.\n\n### `dedupeEntries(entries)`\n\nDrops entries whose label and body text are identical to an earlier entry (case-insensitive): alias rows in merged catalogs.\n\n### `splitPattern(text, pattern)`\n\nSplits text on a global regular expression, marking matched pieces (`SplitSegment`), for rendering keyword links over prose. A `null` pattern keeps the text whole.\n\n### `escapeRegExp(value)`\n\nEscapes a literal for embedding in a regular expression: build keyword patterns from display names.\n",
6
- "usage": "---\ntitle: 'Scout: Usage Guide'\ndescription: 'How-to guide for @vielzeug/scout: building indexes, reactive search, highlighting, and integrating with sourcerer and vault.'\n---\n\n[[toc]]\n\n## Basic Usage\n\n### Building an index\n\nPass your item array and field configuration to `createIndex`. All items are indexed immediately at construction time.\n\n```ts\nimport { createIndex } from '@vielzeug/scout';\n\nconst users = [\n { email: 'ada@example.com', name: 'Ada Lovelace' },\n { email: 'grace@example.com', name: 'Grace Hopper' },\n];\n\nconst index = createIndex(users, {\n fields: ['name', 'email'],\n});\n```\n\n### Searching\n\nCall `index.search(query)` with any string. Results are sorted by score descending.\n\n```ts\nconst results = index.search('alice');\n\nfor (const { item, score, matches } of results) {\n console.log(item.name, score);\n}\n```\n\nAn empty `query` returns all items with `score = 1`:\n\n```ts\nindex.search(''); // All items, score = 1 each\n```\n\n### Per-field weights\n\nGive fields different weights to control score ranking. A match on a high-weight field ranks the item higher than a match on a low-weight field.\n\n```ts\nconst index = createIndex(users, {\n fields: [\n { field: 'name', weight: 3 }, // name matches rank 3× higher\n { field: 'department', weight: 1 },\n { field: 'bio', weight: 0.5 },\n ],\n});\n```\n\n### Non-string fields\n\nUse `stringify` to convert numeric or boolean fields to searchable text.\n\n```ts\nconst index = createIndex(products, {\n fields: [\n 'title',\n { field: 'price', stringify: (v) => `$${v}` },\n { field: 'inStock', stringify: (v) => (v ? 'available in stock' : 'out of stock') },\n ],\n});\n```\n\n### Non-Latin scripts (CJK, Thai, ...)\n\n`tokenize()` indexes any script correctly: trigrams are generated per-character, so Chinese, Japanese, Cyrillic, and accented Latin text are all searchable out of the box. What it doesn't do is insert word boundaries for scripts that don't use spaces (Chinese, Japanese, Thai, ...), which affects `findMatchRanges()` / highlighting and multi-word query semantics. Pre-segment those fields with `segmentWords()`:\n\n```ts\nimport { createIndex, segmentWords } from '@vielzeug/scout';\n\nconst docs = [{ title: '日本語を勉強しています' }, { title: '我喜欢学习中文' }];\n\nconst index = createIndex(docs, {\n fields: [{ field: 'title', stringify: (v) => segmentWords(String(v)) }],\n});\n\nindex.search('日本語'); // matches the first document\n```\n\n`segmentWords()` uses the runtime's native `Intl.Segmenter`: no dependency. It's opt-in per field rather than built into `tokenize()` because it benchmarks ~15x slower than the default regex path for ordinary whitespace-delimited text.\n\n### Limiting results\n\nPass `limit`, `threshold`, and `minQueryLength` in options to control result count and quality. `limit` must be a finite non-negative integer, `threshold` a finite value in `0..1`, and `minQueryLength` a finite positive integer; invalid values throw `ScoutConfigError`.\n\n```ts\n// At most 10 results, minimum overlap score 0.3\nconst results = index.search('widget', { limit: 10, threshold: 0.3 });\n```\n\nPer-call options override the index-level defaults set in `createIndex`.\n\nScores come from the overlap (Szymkiewicz–Simpson) coefficient: the fraction of the _shorter_\ntrigram set (almost always the query) found in the longer one. This is deliberate for the\nautocomplete/command-palette use case `createIndex` targets: a short query that's a clean prefix\nof a much longer field value (e.g. `'fin'` against `'Finalize Q3 budget report'`) scores on how\nmuch of the query matched, not diluted by how much longer the target field happens to be.\n\n### Controlling short-query behaviour\n\nQueries shorter than `minQueryLength` (default `3`) fall back to an O(n) substring containment scan. Short-query matches return `score = 1.0`.\n\n```ts\n// Use trigram scoring even for 1-char queries (good for small corpora)\nconst index = createIndex(items, { fields: ['name'], minQueryLength: 1 });\n\n// Force containment scan for all queries up to 8 chars (good for autocomplete on large sets)\nconst results = index.search('alice', { minQueryLength: 8 });\n```\n\n## Reactive Search\n\n### `createReactiveSearch()`: recommended\n\nFor most use cases, `createReactiveSearch` builds the index and state together. It returns one external store whose snapshot contains `query`, `isSearching`, and `results`, plus `.index` for incremental mutations:\n\n```ts\nimport { createReactiveSearch } from '@vielzeug/scout';\n\nconst search = createReactiveSearch(users, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n debounce: 150,\n});\n\nsearch.subscribe(() => {\n const { isSearching, results } = search.getSnapshot();\n if (isSearching) showLoadingSpinner();\n else renderResults(results.map((result) => result.item));\n});\n\ninput.addEventListener('input', (event) => {\n search.setQuery((event.currentTarget as HTMLInputElement).value);\n});\n\nsearch.index.add(newUser);\nsearch.dispose();\n```\n\nEach notification observes a complete committed snapshot. During a debounce window, `query` contains the latest input, `isSearching` is `true`, and `results` remain the last committed results.\n\n### `createSearch()`: separate index and state\n\nUse `createSearch` when sharing one index across multiple search stores:\n\n```ts\nimport { createIndex, createSearch } from '@vielzeug/scout';\n\nconst index = createIndex(users, { fields: ['name', 'email'] });\nconst search = createSearch(index, { debounce: 150 });\n```\n\n### `using` declaration\n\n```ts\n{\n using search = createReactiveSearch(users, { fields: ['name'] });\n // search.dispose() called automatically at scope exit\n}\n```\n\n### Zero debounce for synchronous updates\n\nPass `debounce: 0` for synchronous commits with no searching transition:\n\n```ts\nconst search = createReactiveSearch(users, { fields: ['name'], debounce: 0 });\n\nsearch.setQuery('alice');\nconsole.log(search.getSnapshot().results); // Already updated\n```\n\n### Resetting search\n\n```ts\nsearch.clear(); // Resets query, results, and isSearching atomically\n```\n\n### Composing with Ripple\n\nA complete `SearchState` implements Ripple's structural subscribable contract:\n\n```ts\nimport { createRipple } from '@vielzeug/ripple';\n\nconst ripple = createRipple();\nconst state = ripple.fromSubscribable(search, { signal: search.disposalSignal });\nconst topResult = ripple.computed(() => state.value.results[0]?.item ?? null);\n```\n\n## Incremental Updates\n\nUse `add()`, `remove()`, and `reindex()` for individual reference-based mutations. Use `setItems()` when a refreshed collection replaces the current corpus; Scout reconciles membership, current field values, and source order in one notification.\n\n```ts\nconst index = createIndex(products, { fields: ['title'] });\n\n// Add a newly created item\nconst newProduct = { id: 99, title: 'New Widget' };\nindex.add(newProduct);\n\n// Remove a deleted item (by reference)\nindex.remove(products[0]);\n\n// Re-index a mutated item after in-place mutation\nproducts[1].title = 'Updated Title';\nindex.reindex(products[1]);\n```\n\n> `remove()`, `reindex()`, and `setItems()` use **reference equality** (`===`). Pass retained object references from the current corpus; `setItems()` collapses duplicate references.\n\n### Replacing a refreshed corpus\n\n```ts\nconst latestProducts = await loadProducts();\n\nindex.setItems(latestProducts);\n```\n\n`setItems()` removes references absent from `latestProducts`, adds new references, reindexes retained references, and adopts the incoming order. It calls `onMutate()` once only when index membership, field values, or order changes.\n\n### Inspecting the corpus\n\nUse `.items` to read all currently indexed items in insertion order, or `.size` for a count:\n\n```ts\nconsole.log(index.size); // 42\nconsole.log(index.items); // [{ id: 1, title: ... }, ...]\n```\n\n### Reacting to mutations directly\n\n`createSearch()` already keeps `results` in sync with `add()`/`remove()`/`reindex()`/`setItems()` internally. `toSearchMatcher()` also invalidates its query cache after index mutation. If you're building your own reactivity on top of a plain `ScoutIndex` (no `ripple` involved), subscribe with `onMutate()`:\n\n```ts\nconst unsubscribe = index.onMutate(() => {\n rerenderResultsList();\n});\n\nindex.add(newProduct); // triggers rerenderResultsList()\n\nunsubscribe(); // when done\n```\n\n`onMutate()` only fires for mutations that actually change the index: a duplicate `add()` or a `remove()` of an unindexed item is a no-op and doesn't notify listeners.\n\n## Match Highlighting\n\nEvery `SearchResult` carries `matches`: per-field literal normalized-token ranges. A fuzzy trigram candidate can have `matches: []` when no literal query token appears in its field text.\n\n### `highlightField()`: recommended\n\n`highlightField(result, field, text)` is the shorthand that does the field lookup and fragment split in one step:\n\n```ts\nimport { highlightField } from '@vielzeug/scout';\n\nfor (const result of index.search('alice')) {\n const parts = highlightField(result, 'name', result.item.name);\n // [{ text: 'Alice', highlighted: true }, { text: ' Johnson', highlighted: false }]\n renderHighlightedText(parts);\n}\n```\n\n::: warning `part.text` is unescaped\n`highlight()` / `highlightField()` return the **original, unescaped** field text split into\nfragments: never concatenate `part.text` into an HTML string for `innerHTML`. Render each\npart as text (`textContent`, a framework's text binding) and wrap `highlighted` parts in your\nown element:\n\n```ts\nfunction renderHighlightedText(parts: HighlightPart[]): DocumentFragment {\n const fragment = document.createDocumentFragment();\n\n for (const part of parts) {\n if (part.highlighted) {\n const mark = document.createElement('mark');\n\n mark.textContent = part.text; // textContent: never innerHTML\n fragment.appendChild(mark);\n } else {\n fragment.appendChild(document.createTextNode(part.text));\n }\n }\n\n return fragment;\n}\n```\n\n:::\n\n### `findMatchRanges()` + `highlight()`: manual\n\nUse `findMatchRanges()` when you need to apply match ranges to a different string than the indexed field value: for example a truncated preview or a differently formatted display string:\n\n```ts\nimport { findMatchRanges, highlight } from '@vielzeug/scout';\n\nconst [result] = index.search('alice');\nconst preview = result.item.bio.slice(0, 100);\nconst ranges = findMatchRanges(preview, 'alice');\nconst parts = highlight(preview, ranges);\n```\n\nOr use `highlight()` directly when you already have the ranges from `result.matches`:\n\n```ts\nconst [result] = index.search('alice');\nconst nameMatch = result.matches.find((m) => m.field === 'name');\nconst parts = highlight(result.item.name, nameMatch?.ranges ?? []);\n```\n\n## Searchable Reference Lists\n\nA glossary or compendium mixes entry kinds and needs direct-match ranking above fuzzy hits. Rank with `rankEntries`, render keyword links with `splitPattern`, and highlight the typed query with `findMatchRanges` + `highlight`.\n\n```ts\nimport { dedupeEntries, escapeRegExp, findMatchRanges, highlight, rankEntries, splitPattern } from '@vielzeug/scout';\n\nconst keywordPattern = new RegExp(`(${keywords.map((k) => escapeRegExp(k.name)).join('|')})`, 'g');\nconst results = rankEntries(entries, query, { fuzzyIds: fuzzyIndexIds });\n\nfor (const entry of results) {\n for (const segment of splitPattern(entry.text, keywordPattern)) {\n if (segment.matched) renderKeywordLink(segment.text);\n else for (const part of highlight(segment.text, findMatchRanges(segment.text, query))) renderMark(part);\n }\n}\n```\n\nDedupe merged catalogs with `dedupeEntries` before ranking so alias rows do not shadow their originals.\n\n## Debug Logging\n\nUse `tap()` for typed runtime observation without affecting search behavior:\n\n```ts\nimport { createIndex, createSearch } from '@vielzeug/scout';\n\nconst search = createSearch(index, { debounce: 150 });\nconst stop = search.tap((event) => {\n console.debug(event.snapshot.query, event.snapshot.isSearching, event.snapshot.results.length);\n});\n\nsearch.setQuery('alice');\nstop();\n```\n\n`tap()` emits only `state-change`; observe disposal through `disposed` or `disposalSignal`. Tapper errors are swallowed. Use `subscribe()` instead when application state must update after each snapshot commit.\n\n::: warning Development logging\n`query` carries the full, literal search query string: if your queries may carry PII (names, emails, medical/financial terms typed by end users), don't log them in production.\n:::\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { createReactiveSearch } from '@vielzeug/scout';\nimport { useEffect, useMemo, useSyncExternalStore } from 'react';\n\ntype User = { id: number; name: string; email: string };\n\nfunction useScoutSearch(items: User[]) {\n const search = useMemo(\n () =>\n createReactiveSearch(items, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n debounce: 150,\n }),\n [items],\n );\n const snapshot = useSyncExternalStore(search.subscribe, search.getSnapshot, search.getSnapshot);\n\n useEffect(() => () => search.dispose(), [search]);\n\n return { ...snapshot, setQuery: search.setQuery };\n}\n```\n\n```ts [Vue 3]\nimport { createReactiveSearch } from '@vielzeug/scout';\nimport { onScopeDispose, shallowRef } from 'vue';\n\ntype User = { id: number; name: string; email: string };\n\nfunction useScoutSearch(items: User[]) {\n const search = createReactiveSearch(items, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n debounce: 150,\n });\n const snapshot = shallowRef(search.getSnapshot());\n const stop = search.subscribe(() => {\n snapshot.value = search.getSnapshot();\n });\n\n onScopeDispose(() => {\n stop();\n search.dispose();\n });\n\n return { search, snapshot };\n}\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { createReactiveSearch } from '@vielzeug/scout';\n import { onDestroy } from 'svelte';\n\n type User = { id: number; name: string; email: string };\n\n export let items: User[];\n\n const search = createReactiveSearch(items, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n debounce: 150,\n });\n let snapshot = search.getSnapshot();\n const stop = search.subscribe(() => { snapshot = search.getSnapshot(); });\n\n onDestroy(() => { stop(); search.dispose(); });\n</script>\n\n<input value={snapshot.query} on:input={(event) => search.setQuery(event.currentTarget.value)} placeholder=\"Search…\" />\n{#each snapshot.results as { item }}\n <p>{item.name}</p>\n{/each}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### With Sourcerer\n\n`toSearchMatcher()` adapts a `ScoutIndex` into Sourcerer's local-source filter.\n\n```ts\nimport { createIndex, toSearchMatcher } from '@vielzeug/scout';\nimport { createLocalSource } from '@vielzeug/sourcerer';\n\nconst index = createIndex(users, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n});\nconst source = createLocalSource(users, { filter: toSearchMatcher(index), params: '' });\n\nsource.setParams('alice');\nconsole.log(source.state.items);\n```\n\n> Update the index and source from the same collection change. Use `index.setItems(items)` with `source.setItems(items)` for replacement collections.\n\n### With Vault\n\n`toFilterPredicate()` returns an `(item: T) => boolean` snapshot predicate: pass it to vault's `query.filter()` or plain `Array.filter`.\n\n```ts\nimport { createIndex, toFilterPredicate } from '@vielzeug/scout';\n\nconst index = createIndex(products, { fields: ['title', 'sku'] });\n\nconst matching = products.filter(toFilterPredicate(index, 'widget'));\n\nconst rows = await db.query('products').filter(toFilterPredicate(index, searchTerm)).toArray();\n```\n\nCall `toFilterPredicate` again whenever the query or corpus changes: the predicate is a snapshot, not reactive.\n\n## Best Practices\n\n- **Build the index once**: `createIndex()` runs in O(corpus × field_length). Create it at module level or in an effect, not inside render loops.\n- **Keep the index in sync**: call `index.add()` / `remove()` / `reindex()` when items mutate. Stale index entries return wrong scores.\n- **Tune threshold before limit**: set a meaningful `threshold` (e.g. `0.25–0.4`) to suppress noise, then use `limit` to cap the list length.\n- **Set `minQueryLength` for your corpus size**: the default `3` works well for most cases. Lower it for small corpora where single-char queries are expected; raise it for large corpora to avoid expensive O(n) scans.\n- **Dispose reactive state**: always call `search.dispose()` or use `using` when the component unmounts.\n- **Weight by importance**: name/title fields should have weight `2–3`; secondary fields (description, tags) stay at `1`.\n- **Segment CJK/Thai fields explicitly**: `segmentWords()` is opt-in per field, not automatic, to keep `createIndex()` fast for the common whitespace-delimited case.\n",
4
+ "index": "---\ntitle: 'Scout: Fast fuzzy search for TypeScript'\ndescription: Trigram-indexed fuzzy search with per-field weights, match highlighting, and an optional reactive layer.\npackage: scout\ncategory: utilities\nkeywords: [fuzzy-search, search, trigram, full-text, filter, highlight, reactive, ripple]\nexports:\n [\n createIndex,\n createSearch,\n ScoutConfigError,\n ScoutDisposedError,\n ScoutError,\n findMatchRanges,\n highlight,\n highlightField,\n segmentWords,\n toFilterPredicate,\n toSearchMatcher,\n ]\nrelated: [arsenal, sourcerer, vault, ripple]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"scout\" />\n\n## Why Scout?\n\nArsenal's `fuzzy` / `fuzzyFilter` helpers perform pairwise Levenshtein distance: O(n·m) per item per query. For ≤200 items they are fine. For 500–100k items with real-time keystrokes, you need an index.\n\nScout builds a **trigram inverted index** at construction time. Query time scores only items sharing a trigram with the query; broad queries can still approach O(n), while selective queries avoid scoring the whole corpus.\n\n```ts\n// Before\nconst matches = users.filter((user) => user.name.toLowerCase().includes(query.toLowerCase()));\n\n// After\nimport { createIndex } from '@vielzeug/scout';\n\nconst index = createIndex(users, { fields: ['name', 'email'] });\nconst matches = index.search(query);\n```\n\n| Feature | Arsenal `fuzzy*` | Scout `createIndex` | Fuse.js |\n| ------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | ~3 KB | <PackageInfo package=\"scout\" type=\"size\" /> | ~23 KB |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Algorithm | Levenshtein | Trigram + query coverage | Bitap |\n| Query time | O(n·m) | O(candidates) | O(n·m) |\n| Stateful index | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Match highlighting | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Reactive layer | <ore-icon name=\"x\" size=\"16\"></ore-icon> | Atomic external-store snapshots + debounce | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Incremental updates | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Partial |\n\n<div class=\"decision-callout\">\n\n**Use Scout when** you need search over 500+ items, real-time UI search boxes (combobox, command palette), or framework-neutral subscribable search state.\n\n**Consider `arsenal.fuzzyFilter` when** you have fewer than 200 items and don't need a persistent index.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/scout\n```\n\n```sh [npm]\nnpm install @vielzeug/scout\n```\n\n```sh [yarn]\nyarn add @vielzeug/scout\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createIndex } from '@vielzeug/scout';\n\nconst users = [\n { email: 'ada@example.com', name: 'Ada Lovelace' },\n { email: 'grace@example.com', name: 'Grace Hopper' },\n];\n\nconst index = createIndex(users, {\n fields: [{ field: 'name', weight: 2 }, { field: 'email' }],\n});\n\nconst results = index.search('ada');\nconsole.log(results[0]?.item.name); // Ada Lovelace\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createIndex()`: Trigram inverted index; construction O(corpus × field_length), query O(candidates)\n- Per-field weights: Promote `name` matches over secondary fields; finite positive weights and custom `stringify` functions supported\n- `createSearch()`: Reactive search state backed by a `ScoutIndex`; share one index across many states\n- `highlight()` / `highlightField()`: Split field text into `HighlightPart[]` fragments for styled rendering\n- `findMatchRanges()`: Compute match ranges for custom display strings (truncated previews, formatted values)\n- `toSearchMatcher()`: Matcher adapter for filtering in-memory collections with a `ScoutIndex`\n- `toFilterPredicate()`: Snapshot `(item: T) => boolean` predicate for `Array.filter` or vault queries\n- `setItems()`: Reconcile a refreshed corpus by key, preserve incoming order, and notify once\n- `key` option + `removeKey()`: Stable item identity for immutable data; skip unchanged work with fresh copies and delete by id\n- Incremental updates: `add()` / `remove()` / `reindex()` patch individual items in O(field_length)\n- `subscribe()`: Subscribe to index mutations; powers `createSearch()`'s reactivity and bulk reconciliation\n- `segmentWords()`: Split unsegmented-script text (CJK, Thai, ...) into words via native `Intl.Segmenter`\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- [Arsenal](/arsenal/): Use `fuzzyFilter` for ad-hoc filtering of small lists (< 200 items) without building an index\n- [Ripple](/ripple/): bridge a complete Scout `SearchState` with `fromSubscribable()` when composing a larger reactive graph\n- [Sourcerer](/sourcerer/): use a `ScoutIndex` matcher to filter in-memory collections alongside remote sources\n- [Vault](/vault/): `toFilterPredicate()` wraps a one-time Scout query as a vault-compatible `filter()` predicate\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
+ "api": "---\ntitle: 'Scout: API Reference'\ndescription: 'Complete API reference for @vielzeug/scout: createIndex, createSearch, highlight, highlightField, toSearchMatcher, toFilterPredicate.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------ | --------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------ |\n| `createIndex()` | Build trigram index from an item array | Sync | Index is built at call time: pass all initial items |\n| `ScoutIndex.search()` | Query the index, returns scored + highlighted results | Sync | Empty query returns all items with `score = 1` |\n| `ScoutIndex.add()` | Add one item to the index | Sync | An existing key adopts the new object; without a `key`, same reference is a no-op |\n| `ScoutIndex.remove()` | Remove the item stored under `key(item)` | Sync | No-op for unknown keys |\n| `ScoutIndex.removeKey()` | Remove the item stored under a raw key | Sync | Returns whether an item was removed |\n| `ScoutIndex.reindex()` | Store `item` under its key and reindex changed fields | Sync | With a `key`, a fresh copy of the item is enough; no-op for unknown keys |\n| `ScoutIndex.setItems()` | Reconcile a refreshed corpus in one mutation | Sync | Uses key identity (reference by default); equal fresh copies notify nothing |\n| `ScoutIndex.items` | All indexed items in insertion order | Sync | Returns a new array snapshot each call |\n| `ScoutIndex.revision` | Monotonic counter incremented after each mutation | Sync | Use as a cache-busting token for external result caches |\n| `ScoutIndex.subscribe()` | Subscribe to changed index mutations | Sync | A changed `setItems()` reconciliation emits once; no-ops emit nothing |\n| `createSearch()` | Atomic search store backed by a `ScoutIndex` | Sync | Read one snapshot and dispose the store when done |\n| `findMatchRanges()` | Compute match ranges for a text + query pair | Sync | Returns sorted, non-overlapping `[start, end)` ranges in the original text |\n| `highlight()` | Split text into highlighted/unhighlighted fragments | Sync | Ranges must be sorted and non-overlapping |\n| `highlightField()` | Highlight a named field from a `SearchResult` | Sync | Shorthand for the `matches.find(…).ranges → highlight()` pattern |\n| `toSearchMatcher()` | Adapt `ScoutIndex` to Sourcerer's local `filter` callback | Sync | Recomputes cached query matches after index mutation |\n| `toFilterPredicate()` | Snapshot predicate from a one-time query | Sync | Re-call when query or corpus changes |\n| `segmentWords()` | Split unsegmented-script text (CJK, Thai, ...) into words | Sync | Uses native `Intl.Segmenter`: not applied inside `normalize()` itself (see Pitfalls) |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ----------------- | ---------------------------------------------------------------------------------------------------------------------- |\n| `@vielzeug/scout` | All exports: index/search/highlighting/adapters, `ScoutConfigError`, `ScoutDisposedError`, `ScoutError`, and all types |\n\n---\n\n## `createIndex(items, options)`\n\nBuilds a trigram inverted index from `items`. Construction is O(corpus × field_length); subsequent `search()` calls are O(candidates). With a `key`, construction throws `ScoutConfigError` when two different items share one key, matching `setItems()`.\n\n```ts\nfunction createIndex<T>(items: readonly T[], options: ScoutIndexOptions<T>): ScoutIndex<T>;\n```\n\n**Parameters**\n\n| Param | Type | Description |\n| ------------------------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------ |\n| `items` | `readonly T[]` | Initial corpus to index. |\n| `options.fields` | `ReadonlyArray<FieldDef<T>>` | Fields to index. Required; at least one entry. |\n| `options.key` | `(item: T) => unknown` | Stable item identity for `add`/`remove`/`reindex`/`setItems` (default: object reference). |\n| `options.threshold` | `number` | Finite query-coverage score in `0..1` (default `0.2`). |\n| `options.limit` | `number` | Finite non-negative integer max results (default `50`). |\n| `options.minQueryLength` | `number` | Finite positive integer min chars before trigram scoring; shorter queries use O(n) containment scan (default `3`). |\n\n**Example**\n\n```ts\nimport { createIndex } from '@vielzeug/scout';\n\nconst products = [\n { sku: 'WGT-001', title: 'Widget Pro' },\n { sku: 'GAD-002', title: 'Gadget Plus' },\n];\n\nconst index = createIndex(products, {\n fields: [{ field: 'title', weight: 2 }, { field: 'sku' }],\n threshold: 0.25,\n limit: 20,\n});\n```\n\n---\n\n## `ScoutIndex<T>`\n\nReturned by `createIndex()`.\n\n### `.search(query, options?)`\n\n```ts\nsearch(query: string, options?: SearchConstraints): SearchResult<T>[]\n```\n\nReturns results sorted by score descending. Empty query returns all items with `score = 1`. Results below `threshold` are excluded; at most `limit` results are returned.\n\n```ts\nconst results = index.search('alice');\n// [{ item, score, matches }]\n```\n\n### `.add(item)`\n\nAdds `item` to the index. If another object is already stored under `key(item)`, that record adopts `item` and its changed fields are reindexed (no notification when nothing changed); without a custom `key`, re-adding the same reference is a no-op. O(field_length).\n\n### `.remove(item)`\n\nRemoves the item stored under `key(item)`. No-op if not found. O(field_length).\n\n### `.removeKey(key)`\n\n```ts\nremoveKey(key: unknown): boolean\n```\n\nRemoves the item stored under `key` and returns whether an item was removed. Use with a custom `key` to delete by id without fabricating a `T`.\n\n### `.reindex(item)`\n\nStores `item` under `key(item)`, re-reads its field values, and rebuilds its index entry in-place, updating only fields whose text changed. Preserves insertion order. With a custom `key`, passing a fresh copy of the item is enough. No-op if the key is not in the index.\n\n```ts\nitem.name = 'new name';\nindex.reindex(item);\n```\n\n### `.setItems(items)`\n\n```ts\nsetItems(items: readonly T[]): void\n```\n\nReconciles the index to a refreshed corpus in one mutation by key identity (reference identity by default). Retained items adopt their incoming object and are reindexed, missing keys are removed, added keys are indexed, and incoming first-occurrence order becomes index order. Duplicate references collapse to one item; two different objects sharing one key throw `ScoutConfigError`. Calls `subscribe()` listeners once when indexed field text, membership, or order changed — reconciling an equal corpus of fresh copies notifies nothing.\n\n```ts\nindex.setItems(latestUsers);\n```\n\n### `.size`\n\n`number`: current number of indexed items.\n\n### `.items`\n\n`readonly T[]`: all indexed items in insertion order — the latest object stored for each key. Returns a new array snapshot each call.\n\n```ts\nconst all = index.items;\n```\n\n### `.subscribe(listener)`\n\n```ts\nsubscribe(listener: () => void): () => void\n```\n\nSubscribes `listener` to run after every changed `add()` / `remove()` / `reindex()` / `setItems()` operation. No-ops, including unchanged bulk reconciliation, do not fire it. A changed `setItems()` reconciliation fires once. `createSearch()` uses this internally to keep `results` in sync with index mutations; most callers building on `createIndex()` directly will not need it.\n\n```ts\nconst unsubscribe = index.subscribe(() => {\n console.log(`Index changed: now ${index.size} items`);\n});\n\nindex.add(newUser); // logs \"Index changed: now 6 items\"\nunsubscribe();\n```\n\n### `.revision`\n\n`number`: monotonically increasing counter, incremented after every changed `add()` / `remove()` / `reindex()` / `setItems()` operation. Use as a cache-busting token when caching search results outside the index: `toSearchMatcher()` uses it for this purpose.\n\n---\n\n## `createSearch(index, options?)`\n\nWraps a `ScoutIndex` in a zero-dependency external store. `getSnapshot()` returns the current query, loading flag, and results as one consistent snapshot; `subscribe()` notifies after the complete snapshot is committed.\n\n```ts\nfunction createSearch<T>(index: ScoutIndex<T>, options?: CreateSearchOptions): SearchState<T>;\n```\n\n**Parameters**\n\n| Param | Type | Description |\n| ------------------------ | -------- | ------------------------------------------------------------------------------------------------------------- |\n| `options.debounce` | `number` | Finite non-negative integer milliseconds before query commit (default `200`). Pass `0` for immediate updates. |\n| `options.limit` | `number` | Finite non-negative integer override of index-level limit. |\n| `options.threshold` | `number` | Finite `0..1` override of index-level threshold. |\n| `options.minQueryLength` | `number` | Finite positive integer override of index-level minimum query length. |\n\n**Returns `SearchState<T>`**\n\n| Member | Type | Description |\n| ------------------------------- | ------------------------------------ | ------------------------------------------------------------------------------------ |\n| `getSnapshot()` | `() => SearchSnapshot<T>` | Returns the stable current snapshot. Identity changes only after a state transition. |\n| `setQuery(query)` | `(query: string) => void` | Starts or immediately commits a query according to `debounce`. |\n| `subscribe(listener, options?)` | `(listener, options?) => () => void` | Notifies after an atomic snapshot commit. Supports `{ signal }` cleanup. |\n| `disposalSignal` | `AbortSignal` | Aborted when `dispose()` is called. Use to tie other lifecycles to this search. |\n| `disposed` | `boolean` | `true` after `dispose()` has been called. |\n| `clear()` | `() => void` | Resets query, cancels debounce, and restores empty-query results synchronously. |\n| `dispose()` | `() => void` | Releases timers and subscriptions. |\n| `[Symbol.dispose]()` | `() => void` | `using`-compatible disposal. |\n\n**Example**\n\n```ts\nimport { createIndex, createSearch } from '@vielzeug/scout';\n\nconst users = [{ name: 'Ada Lovelace' }, { name: 'Grace Hopper' }];\nconst index = createIndex(users, { fields: ['name'] });\nconst search = createSearch(index, { debounce: 150 });\n\nsearch.subscribe(() => {\n console.log(search.getSnapshot().results.map((result) => result.item.name));\n});\n\nsearch.setQuery('ada');\n```\n\n---\n\n## `findMatchRanges(text, query)`\n\nNormalizes `text` and `query` with Scout's shared normalization (lowercase, punctuation to single spaces, Latin-only accent folding), matches the whole normalized query as a phrase first, then each word individually — a one-character word matches only at a word start — merges overlaps, and maps the ranges back to the original string. Useful when you need to apply highlighting to a different string than the indexed field value (e.g. a truncated preview or a differently formatted display string).\n\n```ts\nfunction findMatchRanges(text: string, query: string): [number, number][];\n```\n\n**Example**\n\n```ts\nimport { findMatchRanges, highlight } from '@vielzeug/scout';\n\nconst ranges = findMatchRanges('Alice Johnson', 'alice!');\n// [[0, 5]]\n\nconst parts = highlight('Alice Johnson', ranges);\n// [{ text: 'Alice', highlighted: true }, { text: ' Johnson', highlighted: false }]\n```\n\nReturns an empty array if either `text` or `query` is empty.\n\n---\n\n## `highlight(text, ranges)`\n\nSplits `text` into `HighlightPart[]` fragments based on `ranges` from `FieldMatch.ranges`.\n\n```ts\nfunction highlight(text: string, ranges: [number, number][]): HighlightPart[];\n```\n\n**Example**\n\n```ts\nimport { highlight } from '@vielzeug/scout';\n\nhighlight('Hello World', [[0, 5]]);\n// [{ text: 'Hello', highlighted: true }, { text: ' World', highlighted: false }]\n```\n\nReturns an empty array when `text` is empty. Returns a single unhighlighted part when `ranges` is empty.\n\n---\n\n## `highlightField(result, field, text)`\n\nConvenience shorthand that finds the match ranges for `field` in `result.matches` and calls `highlight()` in one step. Eliminates the manual `result.matches.find(m => m.field === …).ranges` lookup.\n\n```ts\nfunction highlightField<T>(result: SearchResult<T>, field: keyof T & string, text: string): HighlightPart[];\n```\n\n**Example**\n\n```ts\nimport { createIndex, highlightField } from '@vielzeug/scout';\n\nconst users = [{ name: 'Alice Johnson' }];\nconst index = createIndex(users, { fields: ['name'] });\n\nfor (const result of index.search('alice')) {\n const parts = highlightField(result, 'name', result.item.name);\n console.log(parts.map((part) => (part.highlighted ? `[${part.text}]` : part.text)).join(''));\n}\n```\n\nWhen the field has no match (e.g. the query matched via a different field), returns a single unhighlighted part.\n\n---\n\n## `toSearchMatcher(index, options?)`\n\nReturns an `(item, query) => boolean` matcher compatible with Sourcerer's local `filter` option.\n\n```ts\nfunction toSearchMatcher<T>(index: ScoutIndex<T>, options?: SearchConstraints): (item: T, query: string) => boolean;\n```\n\nOne matching-item set is cached per query and index revision, so filtering does not repeat index work per item and stays current after index mutation.\n\n```ts\nimport { createIndex, toSearchMatcher } from '@vielzeug/scout';\nimport { createLocalSource } from '@vielzeug/sourcerer';\n\nconst users = [{ email: 'ada@example.com', name: 'Ada Lovelace' }];\nconst index = createIndex(users, { fields: ['name', 'email'] });\nconst source = createLocalSource(users, { filter: toSearchMatcher(index), params: '' });\n\nsource.setParams('ada');\n```\n\n---\n\n## `toFilterPredicate(index, query, options?)`\n\nReturns a `(item: T) => boolean` predicate computed from a one-time query. Use with `Array.filter` or vault's `query.filter()`.\n\n```ts\nfunction toFilterPredicate<T>(index: ScoutIndex<T>, query: string, options?: SearchConstraints): (item: T) => boolean;\n```\n\nThe predicate is a snapshot: re-call `toFilterPredicate` if the query or corpus changes.\n\n```ts\nimport { createIndex, toFilterPredicate } from '@vielzeug/scout';\n\nconst products = [{ title: 'Widget Pro' }, { title: 'Gadget Plus' }];\nconst index = createIndex(products, { fields: ['title'] });\nconst results = products.filter(toFilterPredicate(index, 'widget'));\n\nconst top5 = products.filter(toFilterPredicate(index, 'widget', { limit: 5 }));\n```\n\n---\n\n## `segmentWords(text)`\n\nSplits `text` into whitespace-joined word segments using the runtime's native `Intl.Segmenter`: no dependency beyond the platform API. Falls back to returning `text` unchanged where `Intl.Segmenter` isn't available.\n\n```ts\nfunction segmentWords(text: string): string;\n```\n\n`normalize()`'s trigram-based scoring already works on unsegmented scripts (Chinese, Japanese, Thai, ...) without this: trigrams are generated per-character, not per-word. `segmentWords()` is for `findMatchRanges()` highlighting and its phrase matching, which assume space-separated words. **Not applied inside `normalize()` itself**: benchmarked at ~15x slower than the plain regex path for the common whitespace-delimited case, which would regress `createIndex()`'s construction cost for every caller, not just those indexing unsegmented scripts.\n\n**Example**\n\n```ts\nimport { createIndex, segmentWords } from '@vielzeug/scout';\n\nconst documents = [{ title: '日本語を勉強しています' }];\nconst index = createIndex(documents, {\n fields: [{ field: 'title', stringify: (value) => segmentWords(String(value)) }],\n});\n```\n\n---\n\n## Types\n\n### `SearchConstraints`\n\nShared search-tuning knobs used by `ScoutIndexOptions`, `CreateSearchOptions`, and all search functions.\n\n```ts\ntype SearchConstraints = {\n limit?: number; // finite non-negative integer; default 50\n minQueryLength?: number; // finite positive integer; default 3\n threshold?: number; // finite 0..1 value; default 0.2\n};\n```\n\n### `FieldDef<T>`\n\n```ts\ntype FieldDef<T> =\n | (keyof T & string)\n | {\n field: keyof T & string;\n weight?: number; // default 1\n stringify?: (value: unknown) => string;\n };\n```\n\n### `ScoutIndexOptions<T>`\n\n```ts\ntype ScoutIndexOptions<T> = SearchConstraints & {\n fields: ReadonlyArray<FieldDef<T>>;\n key?: (item: T) => unknown; // stable identity; default (item) => item\n};\n```\n\n### `CreateSearchOptions`\n\n```ts\ntype CreateSearchOptions = SearchConstraints & {\n debounce?: number; // finite non-negative integer; default 200\n};\n```\n\n### `SearchResult<T>`\n\n```ts\ntype SearchResult<T> = {\n item: T;\n matches: FieldMatch<keyof T & string>[]; // literal [start, end) ranges in original field values; empty for fuzzy-only results\n score: number; // weighted query coverage in [0, 1]; 1 when query is empty\n};\n```\n\n### `FieldMatch<F>`\n\nGeneric over the union of field names: `match.field` is typed to the actual fields of `T`.\n\n```ts\ntype FieldMatch<F extends string = string> = {\n field: F;\n ranges: [number, number][]; // literal [start, end) ranges in the original field value\n};\n```\n\n### `HighlightPart`\n\n```ts\ntype HighlightPart = {\n highlighted: boolean;\n text: string;\n};\n```\n\n### `SearchSnapshot<T>`\n\n```ts\ntype SearchSnapshot<T> = Readonly<{\n isSearching: boolean;\n query: string;\n results: ReadonlyArray<SearchResult<T>>;\n}>;\n```\n\nSnapshots and their result arrays are frozen at runtime.\n\n### `SearchState<T>`\n\n```ts\ntype SearchState<T> = {\n readonly disposalSignal: AbortSignal;\n readonly disposed: boolean;\n clear(): void;\n dispose(): void;\n getSnapshot(): SearchSnapshot<T>;\n setQuery(query: string): void;\n subscribe(listener: () => void, options?: { signal?: AbortSignal }): () => void;\n [Symbol.dispose](): void;\n};\n```\n\n`subscribe()` observers are notified after the full snapshot commits. An observer error is reported asynchronously after the remaining observers run.\n\n---\n\n## Errors\n\n### `ScoutError`\n\nBase class for all scout errors. Use `instanceof ScoutError` to catch any scout-originated error.\n\n```ts\nclass ScoutError extends Error {}\n```\n\n**Named subclasses**\n\n| Class | Thrown when |\n| -------------------- | ------------------------------------------------------------------------------ |\n| `ScoutConfigError` | An index or search receives invalid fields, numeric options, or duplicate keys |\n| `ScoutDisposedError` | A method is called on a disposed `SearchState` instance |\n\n## Entry Ranking\n\nReference lists: glossaries, rule compendiums, profile directories: rank and render through the same helpers.\n\n### `rankEntries(entries, query, options?)`\n\nOrders `RankableEntry` items (`{ id, label, meta, text }`) by how directly they match the query: exact label, label prefix, label contains, meta contains, text contains, and finally `options.fuzzyIds` hits as last resort. Non-matching entries drop; ties break alphabetically. A blank query returns every entry.\n\n### `dedupeEntries(entries)`\n\nDrops entries whose label and body text are identical to an earlier entry (case-insensitive): alias rows in merged catalogs.\n\n### `splitPattern(text, pattern)`\n\nSplits text on a global regular expression, marking matched pieces (`SplitSegment`), for rendering keyword links over prose. A `null` pattern keeps the text whole.\n\n### `escapeRegExp(value)`\n\nEscapes a literal for embedding in a regular expression: build keyword patterns from display names.\n",
6
+ "usage": "---\ntitle: 'Scout: Usage Guide'\ndescription: 'How-to guide for @vielzeug/scout: building indexes, reactive search, highlighting, and integrating with sourcerer and vault.'\n---\n\n[[toc]]\n\n## Basic Usage\n\n### Building an index\n\nPass your item array and field configuration to `createIndex`. All items are indexed immediately at construction time.\n\n```ts\nimport { createIndex } from '@vielzeug/scout';\n\nconst users = [\n { email: 'ada@example.com', name: 'Ada Lovelace' },\n { email: 'grace@example.com', name: 'Grace Hopper' },\n];\n\nconst index = createIndex(users, {\n fields: ['name', 'email'],\n});\n```\n\n### Searching\n\nCall `index.search(query)` with any string. Results are sorted by score descending.\n\n```ts\nconst results = index.search('alice');\n\nfor (const { item, score, matches } of results) {\n console.log(item.name, score);\n}\n```\n\nAn empty `query` returns all items with `score = 1`:\n\n```ts\nindex.search(''); // All items, score = 1 each\n```\n\n### Per-field weights\n\nGive fields different weights to control score ranking. A match on a high-weight field ranks the item higher than a match on a low-weight field.\n\n```ts\nconst index = createIndex(users, {\n fields: [\n { field: 'name', weight: 3 }, // name matches rank 3× higher\n { field: 'department', weight: 1 },\n { field: 'bio', weight: 0.5 },\n ],\n});\n```\n\n### Non-string fields\n\nUse `stringify` to convert numeric or boolean fields to searchable text.\n\n```ts\nconst index = createIndex(products, {\n fields: [\n 'title',\n { field: 'price', stringify: (v) => `$${v}` },\n { field: 'inStock', stringify: (v) => (v ? 'available in stock' : 'out of stock') },\n ],\n});\n```\n\n### Non-Latin scripts (CJK, Thai, ...)\n\nScout's normalization indexes any script correctly: trigrams are generated per-character, so Chinese, Japanese, Cyrillic, and accented Latin text are all searchable out of the box. What it doesn't do is insert word boundaries for scripts that don't use spaces (Chinese, Japanese, Thai, ...), which affects `findMatchRanges()` / highlighting and multi-word phrase matching. Pre-segment those fields with `segmentWords()`:\n\n```ts\nimport { createIndex, segmentWords } from '@vielzeug/scout';\n\nconst docs = [{ title: '日本語を勉強しています' }, { title: '我喜欢学习中文' }];\n\nconst index = createIndex(docs, {\n fields: [{ field: 'title', stringify: (v) => segmentWords(String(v)) }],\n});\n\nindex.search('日本語'); // matches the first document\n```\n\n`segmentWords()` uses the runtime's native `Intl.Segmenter`: no dependency. It's opt-in per field rather than built into the shared normalization because it benchmarks ~15x slower than the default regex path for ordinary whitespace-delimited text.\n\n### Limiting results\n\nPass `limit`, `threshold`, and `minQueryLength` in options to control result count and quality. `limit` must be a finite non-negative integer, `threshold` a finite value in `0..1`, and `minQueryLength` a finite positive integer; invalid values throw `ScoutConfigError`.\n\n```ts\n// At most 10 results, minimum query-coverage score 0.3\nconst results = index.search('widget', { limit: 10, threshold: 0.3 });\n```\n\nPer-call options override the index-level defaults set in `createIndex`.\n\nScores are query coverage: the fraction of the **query's** trigrams found in a field, scaled by\nthat field's relative weight. `'fin'` against `'Finalize Q3 roadmap'` scores how much of the\nquery was found (about `0.67`), independent of how long the field is; conversely, a long query\nlike `'tomato soup recipe'` does not reward a field that merely contains part of it. Each item\nis also scored against the union of all its fields' text at the smallest field weight, so a\ncross-field query like `'alice smith'` finds `{ first: 'Alice', last: 'Smith' }` as well as one\ncombined `Alice Smith` field.\n\n### Controlling short-query behaviour\n\nQueries shorter than `minQueryLength` (default `3`) fall back to an O(n) substring containment scan. Short-query matches return `score = 1.0`.\n\n```ts\n// Use trigram scoring even for 1-char queries (good for small corpora)\nconst index = createIndex(items, { fields: ['name'], minQueryLength: 1 });\n\n// Force containment scan for all queries up to 8 chars (good for autocomplete on large sets)\nconst results = index.search('alice', { minQueryLength: 8 });\n```\n\n## Reactive Search\n\n`createSearch()` wraps a `ScoutIndex` in one external store whose snapshot contains `query`, `isSearching`, and `results`. The index stays in your hands for incremental mutations, and one index can back several search stores:\n\n```ts\nimport { createIndex, createSearch } from '@vielzeug/scout';\n\nconst index = createIndex(users, { fields: [{ field: 'name', weight: 2 }, 'email'] });\nconst search = createSearch(index, { debounce: 150 });\n\nsearch.subscribe(() => {\n const { isSearching, results } = search.getSnapshot();\n if (isSearching) showLoadingSpinner();\n else renderResults(results.map((result) => result.item));\n});\n\ninput.addEventListener('input', (event) => {\n search.setQuery((event.currentTarget as HTMLInputElement).value);\n});\n\nindex.add(newUser); // the search state re-runs the committed query\nsearch.dispose();\n```\n\nEach notification observes a complete committed snapshot. During a debounce window, `query` contains the latest input, `isSearching` is `true`, and `results` remain the last committed results. Index mutations re-run the last committed query, so new items surface without another `setQuery()`.\n\n### `using` declaration\n\n```ts\n{\n using search = createSearch(index, { debounce: 150 });\n // search.dispose() called automatically at scope exit\n}\n```\n\n### Zero debounce for synchronous updates\n\nPass `debounce: 0` for synchronous commits with no searching transition:\n\n```ts\nconst search = createSearch(index, { debounce: 0 });\n\nsearch.setQuery('alice');\nconsole.log(search.getSnapshot().results); // Already updated\n```\n\n### Resetting search\n\n```ts\nsearch.clear(); // Resets query, results, and isSearching atomically\n```\n\n### Composing with Ripple\n\nA complete `SearchState` implements Ripple's structural subscribable contract:\n\n```ts\nimport { createRipple } from '@vielzeug/ripple';\n\nconst ripple = createRipple();\nconst state = ripple.fromSubscribable(search, { signal: search.disposalSignal });\nconst topResult = ripple.computed(() => state.value.results[0]?.item ?? null);\n```\n\n## Incremental Updates\n\nUse `add()`, `remove()`, and `reindex()` for individual mutations. Use `setItems()` when a refreshed collection replaces the current corpus; Scout reconciles membership, current field values, and source order in one notification.\n\n```ts\nconst index = createIndex(products, { fields: ['title'] });\n\n// Add a newly created item\nconst newProduct = { id: 99, title: 'New Widget' };\nindex.add(newProduct);\n\n// Remove a deleted item (by key; the default key is the reference)\nindex.remove(products[0]);\n\n// Re-index a mutated item after in-place mutation\nproducts[1].title = 'Updated Title';\nindex.reindex(products[1]);\n```\n\n> Without a `key`, `remove()`, `reindex()`, and `setItems()` identify items by **reference equality** (`===`): pass retained object references from the current corpus, and `setItems()` collapses duplicate references. With a `key`, any object carrying the same key works: see [Immutable data and stable keys](#immutable-data-and-stable-keys).\n\n### Immutable data and stable keys\n\nIf your pipeline creates fresh objects on every update (framework stores, immutable reducers, mapped projections), pass a `key` that identifies each item across generations:\n\n```ts\nconst index = createIndex(products, {\n fields: ['title'],\n key: (product) => product.id,\n});\n\n// setItems() with fresh copies of unchanged items: no reindex, no notification.\n// Changed keys reindex only their changed fields; missing keys drop out.\nindex.setItems(await loadProducts()); // [{ id: 7, title: 'New title' }, ...]\n\n// reindex() accepts any fresh object carrying the key:\nindex.reindex({ id: 7, title: 'Retitled' });\n\n// Or delete by key directly, without fabricating a Product:\nindex.removeKey(7);\n```\n\nTwo different objects that share one key — inside a single `setItems()` call or the initial `createIndex()` corpus — throw `ScoutConfigError`. Search results always return the latest object stored for each key.\n\n### Replacing a refreshed corpus\n\n```ts\nconst latestProducts = await loadProducts();\n\nindex.setItems(latestProducts);\n```\n\n`setItems()` removes keys absent from `latestProducts`, indexes new keys, reindexes retained keys against their incoming objects, and adopts the incoming order. It notifies `subscribe()` listeners once, only when index membership, field text, or order changed.\n\n### Inspecting the corpus\n\nUse `.items` to read all currently indexed items in insertion order, or `.size` for a count:\n\n```ts\nconsole.log(index.size); // 42\nconsole.log(index.items); // [{ id: 1, title: ... }, ...]\n```\n\n### Reacting to mutations directly\n\n`createSearch()` already keeps `results` in sync with `add()`/`remove()`/`reindex()`/`setItems()` internally. `toSearchMatcher()` also invalidates its query cache after index mutation. If you're building your own reactivity on top of a plain `ScoutIndex` (no `ripple` involved), subscribe with `subscribe()`:\n\n```ts\nconst unsubscribe = index.subscribe(() => {\n rerenderResultsList();\n});\n\nindex.add(newProduct); // triggers rerenderResultsList()\n\nunsubscribe(); // when done\n```\n\n`subscribe()` only fires for mutations that actually change the index: a duplicate `add()` or a `remove()` of an unindexed item is a no-op and doesn't notify listeners.\n\n## Match Highlighting\n\nEvery `SearchResult` carries `matches`: per-field literal `[start, end)` ranges into the original field value. A fuzzy trigram candidate can have `matches: []` when no literal query text appears in its field value.\n\n### `highlightField()`: recommended\n\n`highlightField(result, field, text)` is the shorthand that does the field lookup and fragment split in one step:\n\n```ts\nimport { highlightField } from '@vielzeug/scout';\n\nfor (const result of index.search('alice')) {\n const parts = highlightField(result, 'name', result.item.name);\n // [{ text: 'Alice', highlighted: true }, { text: ' Johnson', highlighted: false }]\n renderHighlightedText(parts);\n}\n```\n\n::: warning `part.text` is unescaped\n`highlight()` / `highlightField()` return the **original, unescaped** field text split into\nfragments: never concatenate `part.text` into an HTML string for `innerHTML`. Render each\npart as text (`textContent`, a framework's text binding) and wrap `highlighted` parts in your\nown element:\n\n```ts\nfunction renderHighlightedText(parts: HighlightPart[]): DocumentFragment {\n const fragment = document.createDocumentFragment();\n\n for (const part of parts) {\n if (part.highlighted) {\n const mark = document.createElement('mark');\n\n mark.textContent = part.text; // textContent: never innerHTML\n fragment.appendChild(mark);\n } else {\n fragment.appendChild(document.createTextNode(part.text));\n }\n }\n\n return fragment;\n}\n```\n\n:::\n\n### `findMatchRanges()` + `highlight()`: manual\n\nUse `findMatchRanges()` when you need to apply match ranges to a different string than the indexed field value: for example a truncated preview or a differently formatted display string:\n\n```ts\nimport { findMatchRanges, highlight } from '@vielzeug/scout';\n\nconst [result] = index.search('alice');\nconst preview = result.item.bio.slice(0, 100);\nconst ranges = findMatchRanges(preview, 'alice');\nconst parts = highlight(preview, ranges);\n```\n\nOr use `highlight()` directly when you already have the ranges from `result.matches`:\n\n```ts\nconst [result] = index.search('alice');\nconst nameMatch = result.matches.find((m) => m.field === 'name');\nconst parts = highlight(result.item.name, nameMatch?.ranges ?? []);\n```\n\n## Searchable Reference Lists\n\nA glossary or compendium mixes entry kinds and needs direct-match ranking above fuzzy hits. Rank with `rankEntries`, render keyword links with `splitPattern`, and highlight the typed query with `findMatchRanges` + `highlight`.\n\n```ts\nimport { dedupeEntries, escapeRegExp, findMatchRanges, highlight, rankEntries, splitPattern } from '@vielzeug/scout';\n\nconst keywordPattern = new RegExp(`(${keywords.map((k) => escapeRegExp(k.name)).join('|')})`, 'g');\nconst results = rankEntries(entries, query, { fuzzyIds: fuzzyIndexIds });\n\nfor (const entry of results) {\n for (const segment of splitPattern(entry.text, keywordPattern)) {\n if (segment.matched) renderKeywordLink(segment.text);\n else for (const part of highlight(segment.text, findMatchRanges(segment.text, query))) renderMark(part);\n }\n}\n```\n\nDedupe merged catalogs with `dedupeEntries` before ranking so alias rows do not shadow their originals.\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { createIndex, createSearch } from '@vielzeug/scout';\nimport { useEffect, useMemo, useSyncExternalStore } from 'react';\n\ntype User = { id: number; name: string; email: string };\n\nfunction useScoutSearch(items: User[]) {\n const search = useMemo(() => {\n const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });\n\n return createSearch(index, { debounce: 150 });\n }, [items]);\n const snapshot = useSyncExternalStore(search.subscribe, search.getSnapshot, search.getSnapshot);\n\n useEffect(() => () => search.dispose(), [search]);\n\n return { ...snapshot, setQuery: search.setQuery };\n}\n```\n\n```ts [Vue 3]\nimport { createIndex, createSearch } from '@vielzeug/scout';\nimport { onScopeDispose, shallowRef } from 'vue';\n\ntype User = { id: number; name: string; email: string };\n\nfunction useScoutSearch(items: User[]) {\n const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });\n const search = createSearch(index, { debounce: 150 });\n const snapshot = shallowRef(search.getSnapshot());\n const stop = search.subscribe(() => {\n snapshot.value = search.getSnapshot();\n });\n\n onScopeDispose(() => {\n stop();\n search.dispose();\n });\n\n return { search, snapshot };\n}\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { createIndex, createSearch } from '@vielzeug/scout';\n import { onDestroy } from 'svelte';\n\n type User = { id: number; name: string; email: string };\n\n export let items: User[];\n\n const index = createIndex(items, { fields: [{ field: 'name', weight: 2 }, 'email'] });\n const search = createSearch(index, { debounce: 150 });\n let snapshot = search.getSnapshot();\n const stop = search.subscribe(() => { snapshot = search.getSnapshot(); });\n\n onDestroy(() => { stop(); search.dispose(); });\n</script>\n\n<input value={snapshot.query} on:input={(event) => search.setQuery(event.currentTarget.value)} placeholder=\"Search…\" />\n{#each snapshot.results as { item }}\n <p>{item.name}</p>\n{/each}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### With Sourcerer\n\n`toSearchMatcher()` adapts a `ScoutIndex` into Sourcerer's local-source filter.\n\n```ts\nimport { createIndex, toSearchMatcher } from '@vielzeug/scout';\nimport { createLocalSource } from '@vielzeug/sourcerer';\n\nconst index = createIndex(users, {\n fields: [{ field: 'name', weight: 2 }, 'email'],\n});\nconst source = createLocalSource(users, { filter: toSearchMatcher(index), params: '' });\n\nsource.setParams('alice');\nconsole.log(source.state.items);\n```\n\n> Update the index and source from the same collection change. Use `index.setItems(items)` with `source.setItems(items)` for replacement collections.\n\n### With Vault\n\n`toFilterPredicate()` returns an `(item: T) => boolean` snapshot predicate: pass it to vault's `query.filter()` or plain `Array.filter`.\n\n```ts\nimport { createIndex, toFilterPredicate } from '@vielzeug/scout';\n\nconst index = createIndex(products, { fields: ['title', 'sku'] });\n\nconst matching = products.filter(toFilterPredicate(index, 'widget'));\n\nconst rows = await db.query('products').filter(toFilterPredicate(index, searchTerm)).toArray();\n```\n\nCall `toFilterPredicate` again whenever the query or corpus changes: the predicate is a snapshot, not reactive.\n\n## Best Practices\n\n- **Build the index once**: `createIndex()` runs in O(corpus × field_length). Create it at module level or in an effect, not inside render loops.\n- **Keep the index in sync**: call `index.add()` / `remove()` / `reindex()` when items mutate, or `index.setItems()` with the refreshed collection. Stale index entries return wrong scores.\n- **Set a `key` for immutable data**: when updates create fresh objects, `key: (item) => item.id` lets `setItems()` skip unchanged items and `removeKey()` delete by id.\n- **Tune threshold before limit**: set a meaningful `threshold` (e.g. `0.25–0.4`) to suppress noise, then use `limit` to cap the list length.\n- **Set `minQueryLength` for your corpus size**: the default `3` works well for most cases. Lower it for small corpora where single-char queries are expected; raise it for large corpora to avoid expensive O(n) scans.\n- **Dispose reactive state**: always call `search.dispose()` or use `using` when the component unmounts.\n- **Weight by importance**: name/title fields should have weight `2–3`; secondary fields (description, tags) stay at `1`.\n- **Segment CJK/Thai fields explicitly**: `segmentWords()` is opt-in per field, not automatic, to keep `createIndex()` fast for the common whitespace-delimited case.\n",
7
7
  "examples": "---\ntitle: 'Scout: Examples'\ndescription: 'Practical examples for @vielzeug/scout: basic search, reactive combobox, and sourcerer integration.'\n---\n\n## Examples\n\n- [Basic Search](./examples/basic-search)\n- [Reactive Combobox](./examples/reactive-combobox)\n- [Sourcerer Integration](./examples/sourcerer-integration)\n"
8
8
  },
9
9
  "examples": [
@@ -19,12 +19,12 @@
19
19
  },
20
20
  {
21
21
  "id": "incremental-updates",
22
- "code": "import { createIndex } from '@vielzeug/scout'\n\nconst products = [\n { id: 1, title: 'Wireless Mouse', price: 25 },\n { id: 2, title: 'Mechanical Keyboard', price: 80 },\n { id: 3, title: 'USB-C Hub', price: 35 },\n]\n\nconst index = createIndex(products, { fields: ['title'] })\n\n// onMutate() fires after changed add()/remove()/reindex()/setItems() operations :\n// not on no-ops like removing an item that isn't indexed\nconst unsubscribe = index.onMutate(() => {\n console.log(` (index changed: now ${index.size} items)`)\n})\n\nconsole.log('Search \"keyboard\":', index.search('keyboard').map(r => r.item.title))\n\n// Add a newly created item\nindex.add({ id: 4, title: 'Gaming Keyboard', price: 120 })\nconsole.log('After add():', index.search('keyboard').map(r => r.item.title))\n\n// Re-index a mutated item: reference equality, so mutate in place first\nproducts[0].title = 'Wireless Trackball'\nindex.reindex(products[0])\nconsole.log('After reindex():', index.search('trackball').map(r => r.item.title))\n\n// Reconcile a refreshed corpus in one mutation: removes missing references,\n// adds new ones, reindexes retained values, and preserves this incoming order\nindex.setItems([products[0], { id: 4, title: 'Portable SSD', price: 95 }])\nconsole.log('After setItems():', index.items.map(item => item.title))\n\nunsubscribe()",
22
+ "code": "import { createIndex } from '@vielzeug/scout'\n\nconst products = [\n { id: 1, title: 'Wireless Mouse', price: 25 },\n { id: 2, title: 'Mechanical Keyboard', price: 80 },\n { id: 3, title: 'USB-C Hub', price: 35 },\n]\n\nconst index = createIndex(products, { fields: ['title'] })\n\n// subscribe() fires after changed add()/remove()/reindex()/setItems() operations :\n// not on no-ops like removing an item that isn't indexed\nconst unsubscribe = index.subscribe(() => {\n console.log(` (index changed: now ${index.size} items)`)\n})\n\nconsole.log('Search \"keyboard\":', index.search('keyboard').map(r => r.item.title))\n\n// Add a newly created item\nindex.add({ id: 4, title: 'Gaming Keyboard', price: 120 })\nconsole.log('After add():', index.search('keyboard').map(r => r.item.title))\n\n// Re-index a mutated item: items default to reference identity, so mutate in place first\n// (with a key option, a fresh copy with the same key works too)\nproducts[0].title = 'Wireless Trackball'\nindex.reindex(products[0])\nconsole.log('After reindex():', index.search('trackball').map(r => r.item.title))\n\n// Reconcile a refreshed corpus in one mutation: removes missing references,\n// adds new ones, reindexes retained values, and preserves this incoming order\nindex.setItems([products[0], { id: 4, title: 'Portable SSD', price: 95 }])\nconsole.log('After setItems():', index.items.map(item => item.title))\n\nunsubscribe()",
23
23
  "name": "Incremental Updates"
24
24
  },
25
25
  {
26
26
  "id": "reactive-search",
27
- "code": "import { createReactiveSearch } from '@vielzeug/scout'\n\nconst users = [\n { name: 'Alice Johnson', email: 'alice@example.com' },\n { name: 'Bob Smith', email: 'bob@example.com' },\n { name: 'Charlie Brown', email: 'charlie@example.com' },\n { name: 'Alicia Keys', email: 'alicia@example.com' },\n]\n\n// One call creates the index and the reactive search state together\nconst search = createReactiveSearch(users, { fields: ['name', 'email'], debounce: 0 })\n\nconst show = (label) => {\n console.log(label, '\\u2192', search.getSnapshot().results.map(r => r.item.name).join(', ') || '(none)')\n}\n\nshow('Empty query') // all 4 users\n\nsearch.setQuery('ali')\nshow('Query: \"ali\"') // Alice Johnson, Alicia Keys, Dave Alison\n\nsearch.setQuery('alice')\nshow('Query: \"alice\"') // Alice Johnson\n\n// Add a new user at runtime via the exposed index\nsearch.index.add({ name: 'Alice Cooper', email: 'cooper@example.com' })\nshow('After add()') // now includes Alice Cooper\n\nsearch.clear()\nshow('After clear()') // all 5 users\n\nsearch.dispose()\nconsole.log('Disposed:', search.disposed)",
27
+ "code": "import { createIndex, createSearch } from '@vielzeug/scout'\n\nconst users = [\n { name: 'Alice Johnson', email: 'alice@example.com' },\n { name: 'Bob Smith', email: 'bob@example.com' },\n { name: 'Charlie Brown', email: 'charlie@example.com' },\n { name: 'Alicia Keys', email: 'alicia@example.com' },\n]\n\n// The index holds the corpus; the search store keeps one snapshot in sync with it\nconst index = createIndex(users, { fields: ['name', 'email'] })\nconst search = createSearch(index, { debounce: 0 })\n\nconst show = (label) => {\n console.log(label, '\\u2192', search.getSnapshot().results.map(r => r.item.name).join(', ') || '(none)')\n}\n\nshow('Empty query') // all 4 users\n\nsearch.setQuery('ali')\nshow('Query: \"ali\"') // Alice Johnson, Alicia Keys, Dave Alison\n\nsearch.setQuery('alice')\nshow('Query: \"alice\"') // Alice Johnson\n\n// Add a new user at runtime: the search state re-runs the committed query\nindex.add({ name: 'Alice Cooper', email: 'cooper@example.com' })\nshow('After add()') // now includes Alice Cooper\n\nsearch.clear()\nshow('After clear()') // all 5 users\n\nsearch.dispose()\nconsole.log('Disposed:', search.disposed)",
28
28
  "name": "Reactive Search"
29
29
  },
30
30
  {
@@ -48,22 +48,19 @@
48
48
  "findMatchRanges": "export { findMatchRanges, highlight, highlightField } from './highlight';",
49
49
  "highlight": "export { findMatchRanges, highlight, highlightField } from './highlight';",
50
50
  "highlightField": "export { findMatchRanges, highlight, highlightField } from './highlight';",
51
- "ReactiveSearch": "export type { ReactiveSearch } from './reactive';",
52
- "createReactiveSearch": "export { createReactiveSearch, createSearch } from './reactive';",
53
- "createSearch": "export { createReactiveSearch, createSearch } from './reactive';",
51
+ "createSearch": "export { createSearch } from './reactive';",
54
52
  "ScoutIndex": "export type { ScoutIndex } from './scout-index';",
55
53
  "createIndex": "export { createIndex } from './scout-index';",
56
54
  "segmentWords": "export { segmentWords } from './segment';",
57
- "CreateSearchOptions": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
58
- "FieldDef": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
59
- "FieldMatch": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
60
- "HighlightPart": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
61
- "ScoutEvent": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
62
- "ScoutIndexOptions": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
63
- "SearchConstraints": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
64
- "SearchResult": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
65
- "SearchSnapshot": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
66
- "SearchState": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
67
- "SearchSubscribeOptions": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutEvent,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';"
55
+ "CreateSearchOptions": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
56
+ "FieldDef": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
57
+ "FieldMatch": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
58
+ "HighlightPart": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
59
+ "ScoutIndexOptions": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
60
+ "SearchConstraints": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
61
+ "SearchResult": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
62
+ "SearchSnapshot": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
63
+ "SearchState": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';",
64
+ "SearchSubscribeOptions": "export type {\n CreateSearchOptions,\n FieldDef,\n FieldMatch,\n HighlightPart,\n ScoutIndexOptions,\n SearchConstraints,\n SearchResult,\n SearchSnapshot,\n SearchState,\n SearchSubscribeOptions,\n} from './types';"
68
65
  }
69
66
  }
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "apiSource": "// Public root surface of @vielzeug/tandem. Every public export goes through this file.\n\nexport { TandemDisposedError, TandemError } from './errors';\nexport { createSync } from './tandem';\nexport type {\n SyncDeletion,\n SyncEnvelope,\n SyncGateway,\n SyncHandle,\n SyncOptions,\n SyncPort,\n SyncPullResult,\n SyncRecordBase,\n SyncState,\n TandemEvent,\n} from './types';\n",
3
3
  "docs": {
4
- "index": "---\ntitle: 'Tandem: Offline-first sync engine'\ndescription: Offline-first sync engine with rev baselines, tombstoned deletions, and idle-batched pushes for browser applications.\npackage: tandem\ncategory: sync\nkeywords: [sync, offline, conflict, tombstone, rev, replication, last-write-wins]\nrelated: [vault, postmaster, sentinel, ripple]\nexports: [createSync, SyncPort, SyncGateway, SyncHandle, TandemEvent, TandemError, TandemDisposedError]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tandem\" />\n\n## Why Tandem?\n\nA local-first app keeps its records in IndexedDB but must still reach a server: batch bursts of edits into one upload, propagate deletions that a plain pull would resurrect, and reconcile two devices that edited the same record while offline. Tandem drives that round trip against any backend, tracking a per-record write counter so a push carries only what actually changed.\n\n```ts\n// Before\n// Hand-rolled: debounce each save, POST the whole table, hope deletions survive.\nlet timer;\nfunction onSave(record) {\n clearTimeout(timer);\n timer = setTimeout(() => fetch('/sync', { method: 'POST', body: JSON.stringify(allRecords()) }), 3000);\n}\n\n// After\nimport { createSync } from '@vielzeug/tandem';\n\nconst sync = createSync({ gateway, port, idleDelayMs: 3000 });\nsync.changed(); // a local edit happened: the engine batches and pushes dirty records\n```\n\n| Feature | Tandem | RxSync | PowerSync |\n| --------------------------------------- | -------------------------------------------- | ----------------------------------- | ----------------------------------- |\n| Bundle size | <PackageInfo package=\"tandem\" type=\"size\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Zero runtime dependencies | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Backend-agnostic (bring your `port`) | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Storage-agnostic (bring your `gateway`) | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> |\n| Tombstoned deletions + rev conflicts | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> |\n\n<div class=\"decision-callout\">\n\n**Use `tandem` when** you already own a local store and a backend and want the sync scheduler: dirty tracking, batching, hide-flows, and conflict reconcile: without adopting a database or a server.\n\n**Consider `PowerSync` when** you want a managed sync service with its own SQLite client and server component rather than a scheduler over your existing storage.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/tandem\n```\n\n```sh [npm]\nnpm install @vielzeug/tandem\n```\n\n```sh [yarn]\nyarn add @vielzeug/tandem\n```\n\n:::\n\n## Quick Start\n\nImplement the two seams: a `SyncPort` for the server and a `SyncGateway` for local storage: then start the scheduler. Records are opaque to Tandem; it reads only `id` and `rev`, and every rev comparison is the engine's: the gateway upserts, validates, and tombstones.\n\n```ts\nimport { createSync, type SyncGateway, type SyncPort } from '@vielzeug/tandem';\n\nconst port: SyncPort = {\n pull: (since) => fetch(`/sync?since=${since ?? ''}`).then((r) => r.json()),\n push: async (records, deletions) => {\n const response = await fetch('/sync', { method: 'POST', body: JSON.stringify({ records, deletions }) });\n if (!response.ok) throw new Error(await response.text()); // divergence → the engine pulls to reconcile\n },\n};\n\nconst gateway: SyncGateway = {\n records: () => localRecords.map((record) => ({ entity: 'docs', record })),\n pendingDeletions: () => readTombstones(),\n applyRecords: (pulled) => upsert(pulled), // the engine pre-filters; you validate untrusted records\n applyDeletions: (deletions) => removeLocal(deletions),\n clearDeletions: (deletions) => dropTombstones(deletions),\n loadState: () => readSyncState(),\n saveState: (state) => writeSyncState(state),\n};\n\nconst sync = createSync({ gateway, port });\nsync.tap((event) => console.debug('sync', event)); // observe pushes, pulls, warnings\nmyStore.subscribe(() => sync.changed()); // a local write happened\n\n// On account switch or teardown: after flushing this account's work:\nawait sync.flush();\nsync.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createSync()`**: drives a port against a gateway with a serialized push queue.\n- **`SyncPort`**: the server seam: `pull(since)` and `push(records, deletions)`.\n- **`SyncGateway`**: the storage seam: upserts, tombstones, and the persisted baseline: the engine owns every rev comparison.\n- **`rev` baselines**: a record is dirty exactly when its rev is above the last-synced one, across reloads.\n- **`changed()`**: wire it to your write path; the engine debounces a burst into one push.\n- **`flush()`**: a full cycle on demand: pull remote changes, then push dirty records; rejects on failure.\n- **Hide-flows**: flushes with `keepalive` on `pagehide`/`hidden`, runs a full cycle on return to the foreground.\n- **`tap()`**: typed `TandemEvent`s for pushes, pulls, invalid records, and warnings.\n- **Lifecycle-owned**: `dispose()`, `disposed`, `disposalSignal`, and `[Symbol.dispose]`; post-dispose `changed()`/`flush()` fail with `TandemDisposedError`.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Vault](/vault/): the typed storage core most gateways wrap; its IndexedDB adapter is a natural `records()`/`applyRecords()` backend.\n- [Postmaster](/postmaster/): the durable outbox half of offline sync; pair it with Tandem for at-least-once mutations alongside state sync.\n- [Sentinel](/sentinel/): subscribable browser state; its network signal can gate when you call `flush()`.\n- [Ripple](/ripple/): signals and effects; `store.subscribe(() => sync.changed())` is the usual wiring.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
- "api": "---\ntitle: 'Tandem: API Reference'\ndescription: Factory, port and gateway contracts, events, and types for Tandem.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| -------------- | ------------------------------------------ | ------------------------ | ----------------------------------------------------------- |\n| `createSync()` | Scheduler driving a port against a gateway | Sync (queues async work) | Boot runs pull-then-push; dispose before switching accounts |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | --------------------------------------------------------------------------------------------- |\n| `@vielzeug/tandem` | `createSync`, `TandemError`, `TandemDisposedError`, port/gateway contracts, events, and types |\n\n## Factories\n\n### `createSync()`\n\n```ts\nfunction createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle;\n```\n\nStarts a sync scheduler: it loads the persisted baseline, pulls remote changes, pushes anything dirty, then flushes on `changed()`, on tab hide, and on foreground return.\n\n| Parameter | Type | Description |\n| --------------------- | ---------------------- | -------------------------------------------- |\n| `options.gateway` | `SyncGateway<TRecord>` | The device's storage seam |\n| `options.idleDelayMs` | `number \\| undefined` | Quiet period before a flush (default `3000`) |\n| `options.port` | `SyncPort<TRecord>` | The server seam |\n\n**Returns** a `SyncHandle`. Ambient flushes never reject: they surface failures as `warning` events through `tap()`. An explicit `flush()` rejects when its cycle fails.\n\n**Example**\n\n```ts\nimport { createSync } from '@vielzeug/tandem';\n\nconst sync = createSync({ gateway, idleDelayMs: 1500, port });\nsync.changed();\nawait sync.flush();\nsync.dispose();\n```\n\n#### `SyncHandle` methods\n\n| Member | Description |\n| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |\n| `changed()` | Notes a local change and (re)starts the idle flush timer; throws `TandemDisposedError` after `dispose` |\n| `dispose()` | Stops the scheduler, clears the timer, removes document/window listeners |\n| `disposed` | `true` once disposed |\n| `disposalSignal` | `AbortSignal` aborted on dispose |\n| `flush()` | Runs a full cycle: pull, then push; resolves when it completes, rejects when it fails, and rejects with `TandemDisposedError` after `dispose` |\n| `tap(handler, options?)` | Observes `TandemEvent`s; returns an unsubscribe function |\n| `[Symbol.dispose]()` | Calls `dispose()` for `using` scopes |\n\n## Contracts\n\n### `SyncPort`\n\nThe server seam. `pull(since)` returns remote records, remote deletions, and the next cursor. `push(records, deletions, options)` sends local changes; reject it when the server diverged so the engine pulls to reconcile. `options.keepalive` marks a flush that must survive the tab closing.\n\n### `SyncGateway`\n\nThe storage seam. The engine owns every rev comparison: it calls your gateway with the decisions already made.\n\n| Member | Contract |\n| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |\n| `records()` | This device's own records, remote mirrors excluded; sync or async, so a disk-backed gateway can read from storage instead of holding a mirror |\n| `pendingDeletions()` | Tombstones the server has not acknowledged |\n| `applyRecords(records)` | Upsert the given records: already filtered to what the server is ahead on; return the ids that failed validation |\n| `applyDeletions(deletions)` | Remove records deleted remotely |\n| `clearDeletions(deletions)` | Drop the given tombstones a successful push carried |\n| `loadState()` | The persisted `SyncState`, or `null` on a fresh device |\n| `saveState(state)` | Persist the baseline after a completed pull or push |\n\n## Events\n\n### `TandemEvent`\n\n```ts\ntype TandemEvent =\n | { readonly records: number; readonly type: 'pull' }\n | { readonly records: number; readonly type: 'push' }\n | { readonly message: string; readonly skipped: readonly string[]; readonly type: 'invalid' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' }\n | { readonly type: 'dispose' };\n```\n\n`invalid` reports record ids `applyRecords` refused; `warning` reports a rejected push or transport failure and carries the original cause in `error` beside its `message`; `pull` and `push` report the record counts applied and pushed. `dispose` fires once, before tappers are cleared.\n\n## Types\n\n### `SyncRecordBase`\n\n```ts\ninterface SyncRecordBase {\n readonly id: string;\n readonly rev: number;\n}\n```\n\nThe only shape Tandem reads from a record: identity and a write counter. `rev` is required: the dirty model is a rev comparison, so every synced record carries one from birth.\n\n### `SyncEnvelope`\n\n```ts\ninterface SyncEnvelope<TRecord extends SyncRecordBase = SyncRecordBase> {\n readonly entity: string;\n readonly record: TRecord;\n}\n```\n\nA record paired with the entity (table or kind) it belongs to.\n\n### `SyncDeletion`\n\n```ts\ninterface SyncDeletion {\n readonly deletedAt?: string;\n readonly entity: string;\n readonly id: string;\n}\n```\n\nA tombstone: a deletion that travels to the server on the next push. `deletedAt` is set by whoever recorded the deletion and the engine never reads it: include it when your server wants the timestamp, omit it otherwise.\n\n### `SyncState`\n\n```ts\ninterface SyncState {\n cursor: string | null;\n revs: Record<string, number>;\n}\n```\n\nThe persisted baseline. `revs` maps `\"${entity}:${id}\"` to the newest rev the server has seen.\n\n### `SyncPullResult`\n\n```ts\ninterface SyncPullResult<TRecord extends SyncRecordBase = SyncRecordBase> {\n readonly cursor: string | null;\n readonly deletions: readonly SyncDeletion[];\n readonly records: readonly SyncEnvelope<TRecord>[];\n}\n```\n\n### `SyncOptions`\n\n```ts\ninterface SyncOptions<TRecord extends SyncRecordBase = SyncRecordBase> {\n gateway: SyncGateway<TRecord>;\n idleDelayMs?: number;\n port: SyncPort<TRecord>;\n}\n```\n\n## Errors\n\n### `TandemError`\n\n```ts\nclass TandemError extends Error {}\n```\n\nBase class for every error Tandem throws; `instanceof TandemError` catches them all in one branch.\n\n### `TandemDisposedError`\n\n```ts\nclass TandemDisposedError extends TandemError {}\n```\n\nThrown by `changed()` and rejected by `flush()` after `dispose()`. A scheduler that stops silently is a sync engine's worst failure: the device keeps editing while nothing uploads, so a leaked handle fails loudly instead.\n\nBeyond disposal, Tandem defines no error classes. A rejected `push` is expected input, not a failure: the engine pulls to reconcile and reports it as a `warning` event. `flush()` additionally rejects with the underlying port or gateway error; dirty records survive the failure and retry on the next cycle.\n",
6
- "usage": "---\ntitle: 'Tandem: Usage Guide'\ndescription: 'How to drive offline sync with @vielzeug/tandem: ports, gateways, rev baselines, tombstones, and reconciliation.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nTandem sits between your storage and your server. You implement two interfaces and call `createSync`; the engine handles batching, dirty tracking, hide-flows, and conflict reconcile.\n\n```ts\nimport { createSync, type SyncGateway, type SyncPort } from '@vielzeug/tandem';\n\ninterface Doc {\n id: string;\n rev: number;\n title: string;\n}\n\nconst port: SyncPort<Doc> = {\n async pull(since) {\n return fetch(`/sync/pull?since=${since ?? ''}`).then((response) => response.json());\n },\n async push(records, deletions, options) {\n const response = await fetch('/sync/push', {\n body: JSON.stringify({ records, deletions }),\n headers: { 'Content-Type': 'application/json' },\n keepalive: options?.keepalive,\n method: 'POST',\n });\n if (!response.ok) throw new Error(`server diverged: ${await response.text()}`);\n },\n};\n\nconst gateway: SyncGateway<Doc> = {\n records: () => docs.map((record) => ({ entity: 'docs', record })),\n pendingDeletions: () => readTombstones(),\n async applyRecords(pulled) {\n // The engine already filtered these to records the server is ahead on;\n // validate the untrusted remotes and upsert the rest.\n const skipped: string[] = [];\n for (const { record } of pulled) {\n if (!isValid(record)) skipped.push(record.id);\n else upsert(record);\n }\n return skipped;\n },\n applyDeletions: (deletions) => Promise.all(deletions.map((d) => remove(d.id))),\n clearDeletions: (deletions) => Promise.all(deletions.map((d) => dropTombstone(d.id))),\n loadState: () => readRow('syncState'),\n saveState: (state) => writeRow('syncState', state),\n};\n\nconst sync = createSync<Doc>({ gateway, port });\n```\n\n## Track Dirty Records with Revs\n\nTandem never diffs record contents. Each record carries a `rev` counting its committed writes, and the gateway persists a baseline of the newest rev the server has seen. A record is dirty exactly when its current rev is above that baseline.\n\n```ts\n// Your write path bumps the rev on every committed change.\nfunction saveDoc(id: string, patch: Partial<Doc>): void {\n const current = docs.find((doc) => doc.id === id)!;\n upsert({ ...current, ...patch, rev: current.rev + 1 });\n sync.changed(); // schedule a flush\n}\n```\n\nBecause the baseline is persisted, dirtiness survives a reload: a record edited while offline is still above the baseline when the app restarts, and the boot sequence pushes it. The engine never asks your gateway to compare revs: ahead, dirty, and deletion precedence are all its decisions.\n\n## Propagate Deletions with Tombstones\n\nA plain pull cannot carry a deletion: the record is gone. Record a tombstone when you delete locally; Tandem pushes it and clears it only once the server acknowledges.\n\n```ts\nfunction deleteDoc(id: string): void {\n remove(id);\n writeTombstone({ deletedAt: new Date().toISOString(), entity: 'docs', id });\n sync.changed();\n}\n```\n\nA remote deletion loses to a local record with unpushed changes: if your local rev is above the baseline, Tandem keeps your edit and pushes it instead of applying the deletion. The guard runs both ways: a pulled record whose id is locally tombstoned, or deleted in the same pull, never applies, so a backend without an incremental cursor cannot resurrect your deletions.\n\n## Batch Changes and Flush\n\nCall `changed()` on every local write. The engine debounces a burst into one push after `idleDelayMs` (default 3000), and serializes pushes so two never overlap.\n\n```ts\nconst sync = createSync({ gateway, idleDelayMs: 1500, port });\n\n// Force a full cycle now: on a save button, or before navigating away.\ntry {\n await sync.flush();\n} catch {\n // the cycle failed: edits stay local and dirty; the next cycle retries them\n}\n```\n\n`flush()` pulls remote changes and then pushes dirty records, so it is also the wiring point for a returning network connection. It rejects when either half fails; the records stay dirty and the next cycle retries them. After `dispose()`, `flush()` rejects with `TandemDisposedError` and `changed()` throws it: a leaked scheduler fails loudly instead of silently stopping. If your reactive wiring can fire after disposal, unsubscribe from your store before disposing the handle, or guard with `sync.disposed`.\n\nTandem also flushes on its own: it pushes with `keepalive: true` when the tab hides or closes, and runs a full cycle when the tab returns to the foreground. Serve the keepalive push with `navigator.sendBeacon` or a `keepalive` fetch so it survives the tab closing.\n\n## Reconcile a Rejected Push\n\nWhen the server is ahead of the lineage you pushed, reject the push. Tandem immediately pulls to reconcile, then the next flush retries with the merged state. Ambient flushes (debounce, hide) report the failure as a `warning` event; `flush()` additionally rejects with the port's error.\n\n```ts\nasync push(records, deletions) {\n const response = await fetch('/sync/push', { body: JSON.stringify({ records, deletions }), method: 'POST' });\n if (response.status === 409) throw new Error('server ahead'); // triggers a reconcile pull\n}\n```\n\n## Observe with tap()\n\n`tap()` is the observation seam: pushes, pulls, refused records, and warnings. Handler errors are swallowed, so an observer never breaks sync.\n\n```ts\nconst unsubscribe = sync.tap((event) => {\n switch (event.type) {\n case 'push':\n case 'pull':\n console.debug(`sync ${event.type}: ${event.records} records`);\n break;\n case 'invalid':\n console.warn(event.message, event.skipped);\n break;\n case 'warning':\n console.warn(event.message, event.error); // push rejected, network failure, etc.\n break;\n }\n});\n```\n\n## Lifecycle and Disposal\n\nDispose before switching accounts: the baseline is per-account state and a running scheduler would push into the wrong port.\n\n```ts\nconst sync = createSync({ gateway, port });\n// ...\nsync.dispose(); // stops the scheduler, clears the timer, removes document/window listeners\n```\n\n`disposed` and `disposalSignal` report the state; `[Symbol.dispose]` lets you scope it with `using`.\n\n```ts\n{\n using sync = createSync({ gateway, port });\n sync.changed();\n} // disposed here\n```\n\n## Testing\n\nDrive the engine against in-memory doubles. A `SyncPort` double records pushes and returns scripted pulls; a `SyncGateway` double is a record array plus a tombstone list plus a state row.\n\n```ts\nimport { createSync } from '@vielzeug/tandem';\n\nconst pushes: unknown[][] = [];\nconst port: SyncPort = {\n pull: async () => ({ cursor: null, deletions: [], records: [] }),\n push: async (records, deletions) => void pushes.push([records, deletions]),\n};\n\nconst sync = createSync({ gateway: fakeGateway, idleDelayMs: 10, port });\nawait vi.waitFor(() => expect(pushes.length).toBe(1)); // startup push\nsync.dispose();\n```\n\n## Framework Integration\n\nTandem is framework-neutral. Wire `changed()` to your reactive layer and `dispose()` to the component or scope lifecycle.\n\n::: code-group\n\n```ts [Vue 3]\nimport { onScopeDispose, watch } from 'vue';\n\nconst sync = createSync({ gateway, port });\nwatch(store.records, () => sync.changed(), { deep: true });\nonScopeDispose(() => sync.dispose());\n```\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\n\nconst syncRef = useRef(createSync({ gateway, port }));\nuseEffect(() => {\n const sync = syncRef.current;\n return () => sync.dispose();\n}, []);\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onDestroy } from 'svelte';\n const sync = createSync({ gateway, port });\n $effect(() => { $records; sync.changed(); });\n onDestroy(() => sync.dispose());\n</script>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n- **Vault**: the usual `gateway` backend. Its IndexedDB adapter stores records and the sync-state row; `records()` reads them from storage (it may be async), `applyRecords()` writes through the codec.\n- **Postmaster**: complementary, not overlapping. Postmaster guarantees at-least-once delivery of discrete mutations; Tandem keeps whole-record state in step. Apps that need both run them side by side.\n- **Sentinel**: subscribe to `createNetwork()` and call `sync.flush()` when the connection returns; the cycle pulls and pushes, so remote changes land without waiting for the next foreground return.\n- **Ripple**: `store.subscribe(() => sync.changed())` is the idiomatic wiring for a signal-backed store.\n\n## Best Practices\n\n- Bump `rev` on every committed write: the whole dirty model depends on it.\n- Validate remote records in `applyRecords()` and return the ids you refuse; never trust a pulled record.\n- Keep `records()` free of remote session mirrors: it must return only this device's own records.\n- Dispose on account switch; a stale scheduler pushes into the wrong port.\n- Serve `keepalive` pushes with `sendBeacon` or a `keepalive` fetch so they survive tab close.\n- Reject a push on divergence instead of silently overwriting; let the reconcile pull merge.\n- Persist the sync-state row per account, alongside the records it describes.\n- Call `flush()` before actions that assume both sides are current, such as a share or export, and handle its rejection.\n",
4
+ "index": "---\ntitle: 'Tandem: Offline-first sync engine'\ndescription: Offline-first sync engine with rev baselines, tombstoned deletions, and idle-batched pushes for browser applications.\npackage: tandem\ncategory: sync\nkeywords: [sync, offline, conflict, tombstone, rev, replication, last-write-wins]\nrelated: [vault, postmaster, sentinel, ripple]\nexports: [createSync, SyncPort, SyncGateway, SyncHandle, TandemEvent, TandemError, TandemDisposedError]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tandem\" />\n\n## Why Tandem?\n\nA local-first app keeps its records in IndexedDB but must still reach a server: batch bursts of edits into one upload, propagate deletions that a plain pull would resurrect, and reconcile two devices that edited the same record while offline. Tandem drives that round trip against any backend, tracking a per-record write counter so a push carries only what actually changed.\n\n```ts\n// Before\n// Hand-rolled: debounce each save, POST the whole table, hope deletions survive.\nlet timer;\nfunction onSave(record) {\n clearTimeout(timer);\n timer = setTimeout(() => fetch('/sync', { method: 'POST', body: JSON.stringify(allRecords()) }), 3000);\n}\n\n// After\nimport { createSync } from '@vielzeug/tandem';\n\nconst sync = createSync({ gateway, port, idleDelayMs: 3000 });\nsync.changed(); // a local edit happened: the engine batches and pushes dirty records\n```\n\n| Feature | Tandem | RxSync | PowerSync |\n| --------------------------------------- | -------------------------------------------- | ----------------------------------- | ----------------------------------- |\n| Bundle size | <PackageInfo package=\"tandem\" type=\"size\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Zero runtime dependencies | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Backend-agnostic (bring your `port`) | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> |\n| Storage-agnostic (bring your `gateway`) | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"x\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> |\n| Tombstoned deletions + rev conflicts | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> | <ore-icon name=\"check\" size=\"16\" /> |\n\n<div class=\"decision-callout\">\n\n**Use `tandem` when** you already own a local store and a backend and want the sync scheduler: dirty tracking, batching, hide-flows, and conflict reconcile: without adopting a database or a server.\n\n**Consider `PowerSync` when** you want a managed sync service with its own SQLite client and server component rather than a scheduler over your existing storage.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/tandem\n```\n\n```sh [npm]\nnpm install @vielzeug/tandem\n```\n\n```sh [yarn]\nyarn add @vielzeug/tandem\n```\n\n:::\n\n## Quick Start\n\nImplement the two seams: a `SyncPort` for the server and a `SyncGateway` for local storage: then start the scheduler. Records are opaque to Tandem; it reads only `id` and `rev`, and every rev comparison is the engine's: the gateway upserts, validates, and tombstones.\n\n```ts\nimport { createSync, type SyncGateway, type SyncPort } from '@vielzeug/tandem';\n\nconst port: SyncPort = {\n pull: (since) => fetch(`/sync?since=${since ?? ''}`).then((r) => r.json()),\n push: async (records, deletions) => {\n const response = await fetch('/sync', { method: 'POST', body: JSON.stringify({ records, deletions }) });\n if (!response.ok) throw new Error(await response.text()); // divergence → the engine pulls to reconcile\n },\n};\n\nconst gateway: SyncGateway = {\n records: () => localRecords.map((record) => ({ entity: 'docs', record })),\n pendingDeletions: () => readTombstones(),\n applyRecords: (pulled) => upsert(pulled), // the engine pre-filters; you validate untrusted records\n applyDeletions: (deletions) => removeLocal(deletions),\n clearDeletions: (deletions) => dropTombstones(deletions),\n loadState: () => readSyncState(),\n saveState: (state) => writeSyncState(state),\n};\n\nconst sync = createSync({ gateway, port });\nsync.tap((event) => console.debug('sync', event)); // observe pushes, pulls, warnings\nmyStore.subscribe(() => sync.changed()); // a local write happened\n\n// On account switch or teardown: after flushing this account's work:\nawait sync.flush();\nsync.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createSync()`**: drives a port against a gateway with a serialized push queue.\n- **`SyncPort`**: the server seam: `pull(since)` and `push(records, deletions)`.\n- **`SyncGateway`**: the storage seam: upserts, tombstones, and the persisted baseline: the engine owns every rev comparison.\n- **`rev` baselines**: a record is dirty exactly when its rev is above the last-synced one, across reloads.\n- **`changed()`**: wire it to your write path; the engine debounces a burst into one push.\n- **`flush()`**: a full cycle on demand: pull remote changes, then push dirty records; rejects on failure.\n- **Hide-flows**: flushes with `keepalive` on `pagehide`/`hidden`, runs a full cycle on return to the foreground; `ambient: false` plus `autoStart: false` turn the scheduler into a pull-when-told engine for short-lived connections.\n- **`tap()`**: typed `TandemEvent`s for pushes, pulls, invalid records, and warnings.\n- **Lifecycle-owned**: `dispose()`, `disposed`, `disposalSignal`, and `[Symbol.dispose]`; post-dispose `changed()`/`flush()` fail with `TandemDisposedError`.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Vault](/vault/): the typed storage core most gateways wrap; its IndexedDB adapter is a natural `records()`/`applyRecords()` backend.\n- [Postmaster](/postmaster/): the durable outbox half of offline sync; pair it with Tandem for at-least-once mutations alongside state sync.\n- [Sentinel](/sentinel/): subscribable browser state; its network signal can gate when you call `flush()`.\n- [Ripple](/ripple/): signals and effects; `store.subscribe(() => sync.changed())` is the usual wiring.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
+ "api": "---\ntitle: 'Tandem: API Reference'\ndescription: Factory, port and gateway contracts, events, and types for Tandem.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| -------------- | ------------------------------------------ | ------------------------ | ----------------------------------------------------------- |\n| `createSync()` | Scheduler driving a port against a gateway | Sync (queues async work) | Boot runs pull-then-push; dispose before switching accounts |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | --------------------------------------------------------------------------------------------- |\n| `@vielzeug/tandem` | `createSync`, `TandemError`, `TandemDisposedError`, port/gateway contracts, events, and types |\n\n## Factories\n\n### `createSync()`\n\n```ts\nfunction createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle;\n```\n\nStarts a sync scheduler: it loads the persisted baseline, pulls remote changes, pushes anything dirty, then flushes on `changed()`, on tab hide, and on foreground return. `autoStart: false` defers the opening cycle to the first explicit `flush()`; `ambient: false` drops the tab-lifecycle hooks.\n\n| Parameter | Type | Description |\n| --------------------- | ---------------------- | ------------------------------------------------------------------ |\n| `options.ambient` | `boolean \\| undefined` | Wire tab hide/close and foreground return to sync (default `true`) |\n| `options.autoStart` | `boolean \\| undefined` | Run a full cycle on creation (default `true`) |\n| `options.gateway` | `SyncGateway<TRecord>` | The device's storage seam |\n| `options.idleDelayMs` | `number \\| undefined` | Quiet period before a flush (default `3000`) |\n| `options.port` | `SyncPort<TRecord>` | The server seam |\n\n**Returns** a `SyncHandle`. Ambient flushes never reject: they surface failures as `warning` events through `tap()`. An explicit `flush()` rejects when its cycle fails.\n\n**Example**\n\n```ts\nimport { createSync } from '@vielzeug/tandem';\n\nconst sync = createSync({ gateway, idleDelayMs: 1500, port });\nsync.changed();\nawait sync.flush();\nsync.dispose();\n```\n\n#### `SyncHandle` methods\n\n| Member | Description |\n| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |\n| `changed()` | Notes a local change and (re)starts the idle flush timer; throws `TandemDisposedError` after `dispose` |\n| `dispose()` | Stops the scheduler, clears the timer, removes document/window listeners |\n| `disposed` | `true` once disposed |\n| `disposalSignal` | `AbortSignal` aborted on dispose |\n| `flush()` | Runs a full cycle: pull, then push; resolves when it completes, rejects when it fails, and rejects with `TandemDisposedError` after `dispose` |\n| `tap(handler, options?)` | Observes `TandemEvent`s; returns an unsubscribe function |\n| `[Symbol.dispose]()` | Calls `dispose()` for `using` scopes |\n\n## Contracts\n\n### `SyncPort`\n\nThe server seam. `pull(since)` returns remote records, remote deletions, and the next cursor. `push(records, deletions, options)` sends local changes; reject it when the server diverged so the engine pulls to reconcile. `options.keepalive` marks a flush that must survive the tab closing.\n\n### `SyncGateway`\n\nThe storage seam. The engine owns every rev comparison: it calls your gateway with the decisions already made.\n\n| Member | Contract |\n| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |\n| `records()` | This device's own records, remote mirrors excluded; sync or async, so a disk-backed gateway can read from storage instead of holding a mirror |\n| `pendingDeletions()` | Tombstones the server has not acknowledged |\n| `applyRecords(records)` | Upsert the given records: already filtered to what the server is ahead on; return the ids that failed validation |\n| `applyDeletions(deletions)` | Remove records deleted remotely |\n| `clearDeletions(deletions)` | Drop the given tombstones a successful push carried |\n| `loadState()` | The persisted `SyncState`, or `null` on a fresh device |\n| `saveState(state)` | Persist the baseline after a completed pull or push |\n\n## Events\n\n### `TandemEvent`\n\n```ts\ntype TandemEvent =\n | { readonly records: number; readonly type: 'pull' }\n | { readonly records: number; readonly type: 'push' }\n | { readonly message: string; readonly skipped: readonly string[]; readonly type: 'invalid' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' }\n | { readonly type: 'dispose' };\n```\n\n`invalid` reports record ids `applyRecords` refused; `warning` reports a rejected push or transport failure and carries the original cause in `error` beside its `message`; `pull` and `push` report the record counts applied and pushed. `dispose` fires once, before tappers are cleared.\n\n## Types\n\n### `SyncRecordBase`\n\n```ts\ninterface SyncRecordBase {\n readonly id: string;\n readonly rev: number;\n}\n```\n\nThe only shape Tandem reads from a record: identity and a write counter. `rev` is required: the dirty model is a rev comparison, so every synced record carries one from birth.\n\n### `SyncEnvelope`\n\n```ts\ninterface SyncEnvelope<TRecord extends SyncRecordBase = SyncRecordBase> {\n readonly entity: string;\n readonly record: TRecord;\n}\n```\n\nA record paired with the entity (table or kind) it belongs to.\n\n### `SyncDeletion`\n\n```ts\ninterface SyncDeletion {\n readonly deletedAt?: string;\n readonly entity: string;\n readonly id: string;\n}\n```\n\nA tombstone: a deletion that travels to the server on the next push. `deletedAt` is set by whoever recorded the deletion and the engine never reads it: include it when your server wants the timestamp, omit it otherwise.\n\n### `SyncState`\n\n```ts\ninterface SyncState {\n cursor: string | null;\n revs: Record<string, number>;\n}\n```\n\nThe persisted baseline. `revs` maps `\"${entity}:${id}\"` to the newest rev the server has seen.\n\n### `SyncPullResult`\n\n```ts\ninterface SyncPullResult<TRecord extends SyncRecordBase = SyncRecordBase> {\n readonly cursor: string | null;\n readonly deletions: readonly SyncDeletion[];\n readonly records: readonly SyncEnvelope<TRecord>[];\n}\n```\n\n### `SyncOptions`\n\n```ts\ninterface SyncOptions<TRecord extends SyncRecordBase = SyncRecordBase> {\n ambient?: boolean;\n autoStart?: boolean;\n gateway: SyncGateway<TRecord>;\n idleDelayMs?: number;\n port: SyncPort<TRecord>;\n}\n```\n\n## Errors\n\n### `TandemError`\n\n```ts\nclass TandemError extends Error {}\n```\n\nBase class for every error Tandem throws; `instanceof TandemError` catches them all in one branch.\n\n### `TandemDisposedError`\n\n```ts\nclass TandemDisposedError extends TandemError {}\n```\n\nThrown by `changed()` and rejected by `flush()` after `dispose()`. A scheduler that stops silently is a sync engine's worst failure: the device keeps editing while nothing uploads, so a leaked handle fails loudly instead.\n\nBeyond disposal, Tandem defines no error classes. A rejected `push` is expected input, not a failure: the engine pulls to reconcile and reports it as a `warning` event. `flush()` additionally rejects with the underlying port or gateway error; dirty records survive the failure and retry on the next cycle.\n",
6
+ "usage": "---\ntitle: 'Tandem: Usage Guide'\ndescription: 'How to drive offline sync with @vielzeug/tandem: ports, gateways, rev baselines, tombstones, and reconciliation.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nTandem sits between your storage and your server. You implement two interfaces and call `createSync`; the engine handles batching, dirty tracking, hide-flows, and conflict reconcile.\n\n```ts\nimport { createSync, type SyncGateway, type SyncPort } from '@vielzeug/tandem';\n\ninterface Doc {\n id: string;\n rev: number;\n title: string;\n}\n\nconst port: SyncPort<Doc> = {\n async pull(since) {\n return fetch(`/sync/pull?since=${since ?? ''}`).then((response) => response.json());\n },\n async push(records, deletions, options) {\n const response = await fetch('/sync/push', {\n body: JSON.stringify({ records, deletions }),\n headers: { 'Content-Type': 'application/json' },\n keepalive: options?.keepalive,\n method: 'POST',\n });\n if (!response.ok) throw new Error(`server diverged: ${await response.text()}`);\n },\n};\n\nconst gateway: SyncGateway<Doc> = {\n records: () => docs.map((record) => ({ entity: 'docs', record })),\n pendingDeletions: () => readTombstones(),\n async applyRecords(pulled) {\n // The engine already filtered these to records the server is ahead on;\n // validate the untrusted remotes and upsert the rest.\n const skipped: string[] = [];\n for (const { record } of pulled) {\n if (!isValid(record)) skipped.push(record.id);\n else upsert(record);\n }\n return skipped;\n },\n applyDeletions: (deletions) => Promise.all(deletions.map((d) => remove(d.id))),\n clearDeletions: (deletions) => Promise.all(deletions.map((d) => dropTombstone(d.id))),\n loadState: () => readRow('syncState'),\n saveState: (state) => writeRow('syncState', state),\n};\n\nconst sync = createSync<Doc>({ gateway, port });\n```\n\n## Track Dirty Records with Revs\n\nTandem never diffs record contents. Each record carries a `rev` counting its committed writes, and the gateway persists a baseline of the newest rev the server has seen. A record is dirty exactly when its current rev is above that baseline.\n\n```ts\n// Your write path bumps the rev on every committed change.\nfunction saveDoc(id: string, patch: Partial<Doc>): void {\n const current = docs.find((doc) => doc.id === id)!;\n upsert({ ...current, ...patch, rev: current.rev + 1 });\n sync.changed(); // schedule a flush\n}\n```\n\nBecause the baseline is persisted, dirtiness survives a reload: a record edited while offline is still above the baseline when the app restarts, and the boot sequence pushes it. The engine never asks your gateway to compare revs: ahead, dirty, and deletion precedence are all its decisions.\n\n## Propagate Deletions with Tombstones\n\nA plain pull cannot carry a deletion: the record is gone. Record a tombstone when you delete locally; Tandem pushes it and clears it only once the server acknowledges.\n\n```ts\nfunction deleteDoc(id: string): void {\n remove(id);\n writeTombstone({ deletedAt: new Date().toISOString(), entity: 'docs', id });\n sync.changed();\n}\n```\n\nA remote deletion loses to a local record with unpushed changes: if your local rev is above the baseline, Tandem keeps your edit and pushes it instead of applying the deletion. The guard runs both ways: a pulled record whose id is locally tombstoned, or deleted in the same pull, never applies, so a backend without an incremental cursor cannot resurrect your deletions.\n\n## Batch Changes and Flush\n\nCall `changed()` on every local write. The engine debounces a burst into one push after `idleDelayMs` (default 3000), and serializes pushes so two never overlap.\n\n```ts\nconst sync = createSync({ gateway, idleDelayMs: 1500, port });\n\n// Force a full cycle now: on a save button, or before navigating away.\ntry {\n await sync.flush();\n} catch {\n // the cycle failed: edits stay local and dirty; the next cycle retries them\n}\n```\n\n`flush()` pulls remote changes and then pushes dirty records, so it is also the wiring point for a returning network connection. It rejects when either half fails; the records stay dirty and the next cycle retries them. After `dispose()`, `flush()` rejects with `TandemDisposedError` and `changed()` throws it: a leaked scheduler fails loudly instead of silently stopping. If your reactive wiring can fire after disposal, unsubscribe from your store before disposing the handle, or guard with `sync.disposed`.\n\nTandem also flushes on its own: it pushes with `keepalive: true` when the tab hides or closes, and runs a full cycle when the tab returns to the foreground. Serve the keepalive push with `navigator.sendBeacon` or a `keepalive` fetch so it survives the tab closing.\n\nFor a connection that cannot survive an ambient flush, both behaviors are options: `ambient: false` drops the tab-lifecycle hooks, and `autoStart: false` defers the opening cycle to your first `flush()` call. The boot job still loads the persisted baseline, so dirt detection works from the first tick:\n\n```ts\nconst sync = createSync({ ambient: false, autoStart: false, gateway, port });\n\n// Pull and push only when the app says the connection is ready:\nawait sync.flush();\n```\n\n## Reconcile a Rejected Push\n\nWhen the server is ahead of the lineage you pushed, reject the push. Tandem immediately pulls to reconcile, then the next flush retries with the merged state. Ambient flushes (debounce, hide) report the failure as a `warning` event; `flush()` additionally rejects with the port's error.\n\n```ts\nasync push(records, deletions) {\n const response = await fetch('/sync/push', { body: JSON.stringify({ records, deletions }), method: 'POST' });\n if (response.status === 409) throw new Error('server ahead'); // triggers a reconcile pull\n}\n```\n\n## Observe with tap()\n\n`tap()` is the observation seam: pushes, pulls, refused records, and warnings. Handler errors are swallowed, so an observer never breaks sync.\n\n```ts\nconst unsubscribe = sync.tap((event) => {\n switch (event.type) {\n case 'push':\n case 'pull':\n console.debug(`sync ${event.type}: ${event.records} records`);\n break;\n case 'invalid':\n console.warn(event.message, event.skipped);\n break;\n case 'warning':\n console.warn(event.message, event.error); // push rejected, network failure, etc.\n break;\n }\n});\n```\n\n## Lifecycle and Disposal\n\nDispose before switching accounts: the baseline is per-account state and a running scheduler would push into the wrong port.\n\n```ts\nconst sync = createSync({ gateway, port });\n// ...\nsync.dispose(); // stops the scheduler, clears the timer, removes document/window listeners\n```\n\n`disposed` and `disposalSignal` report the state; `[Symbol.dispose]` lets you scope it with `using`.\n\n```ts\n{\n using sync = createSync({ gateway, port });\n sync.changed();\n} // disposed here\n```\n\n## Testing\n\nDrive the engine against in-memory doubles. A `SyncPort` double records pushes and returns scripted pulls; a `SyncGateway` double is a record array plus a tombstone list plus a state row.\n\n```ts\nimport { createSync } from '@vielzeug/tandem';\n\nconst pushes: unknown[][] = [];\nconst port: SyncPort = {\n pull: async () => ({ cursor: null, deletions: [], records: [] }),\n push: async (records, deletions) => void pushes.push([records, deletions]),\n};\n\nconst sync = createSync({ gateway: fakeGateway, idleDelayMs: 10, port });\nawait vi.waitFor(() => expect(pushes.length).toBe(1)); // startup push\nsync.dispose();\n```\n\n## Framework Integration\n\nTandem is framework-neutral. Wire `changed()` to your reactive layer and `dispose()` to the component or scope lifecycle.\n\n::: code-group\n\n```ts [Vue 3]\nimport { onScopeDispose, watch } from 'vue';\n\nconst sync = createSync({ gateway, port });\nwatch(store.records, () => sync.changed(), { deep: true });\nonScopeDispose(() => sync.dispose());\n```\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\n\nconst syncRef = useRef(createSync({ gateway, port }));\nuseEffect(() => {\n const sync = syncRef.current;\n return () => sync.dispose();\n}, []);\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onDestroy } from 'svelte';\n const sync = createSync({ gateway, port });\n $effect(() => { $records; sync.changed(); });\n onDestroy(() => sync.dispose());\n</script>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n- **Vault**: the usual `gateway` backend. Its IndexedDB adapter stores records and the sync-state row; `records()` reads them from storage (it may be async), `applyRecords()` writes through the codec.\n- **Postmaster**: complementary, not overlapping. Postmaster guarantees at-least-once delivery of discrete mutations; Tandem keeps whole-record state in step. Apps that need both run them side by side.\n- **Sentinel**: subscribe to `createNetwork()` and call `sync.flush()` when the connection returns; the cycle pulls and pushes, so remote changes land without waiting for the next foreground return.\n- **Ripple**: `store.subscribe(() => sync.changed())` is the idiomatic wiring for a signal-backed store.\n\n## Best Practices\n\n- Bump `rev` on every committed write: the whole dirty model depends on it.\n- Validate remote records in `applyRecords()` and return the ids you refuse; never trust a pulled record.\n- Keep `records()` free of remote session mirrors: it must return only this device's own records.\n- Dispose on account switch; a stale scheduler pushes into the wrong port.\n- Serve `keepalive` pushes with `sendBeacon` or a `keepalive` fetch so they survive tab close.\n- Reject a push on divergence instead of silently overwriting; let the reconcile pull merge.\n- Persist the sync-state row per account, alongside the records it describes.\n- Call `flush()` before actions that assume both sides are current, such as a share or export, and handle its rejection.\n",
7
7
  "examples": "---\ntitle: 'Tandem: Examples'\ndescription: Offline sync recipes for two-device editing, deletions, and account switching.\n---\n\n## Examples\n\n- [Sync a Vault Store](./examples/sync-a-vault-store.md)\n- [Make Store Commands Undoable](./examples/make-store-commands-undoable.md)\n- [Keep Deletions from Resurrecting](./examples/keep-deletions-from-resurrecting.md)\n- [Switch Accounts Safely](./examples/switch-accounts-safely.md)\n"
8
8
  },
9
9
  "examples": [
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "apiSource": "// Public root surface of @vielzeug/tavern. Every public export goes through this file.\n\n// The mesh peer rides tavern's own event payloads; re-exported so the tavern import\n// alone types them.\nexport type { MeshPeer } from '@vielzeug/mesh';\nexport { TavernDisposedError, TavernError, TavernPairingError } from './errors';\nexport { joinTavern } from './guest';\nexport { hostTavern } from './host';\nexport type {\n TavernCommand,\n TavernCommands,\n TavernGuest,\n TavernGuestEvent,\n TavernGuestOptions,\n TavernHost,\n TavernHostEvent,\n TavernHostOptions,\n TavernJoinResult,\n TavernSubject,\n} from './types';\n",
3
3
  "docs": {
4
- "index": "---\ntitle: Tavern\ndescription: 'Table sessions over mesh: host-owned state replication with guest command forwarding'\npackage: tavern\ncategory: utilities\nkeywords: [session, host, guest, replication, mesh, commands, snapshots, collaboration, peer-to-peer]\nexports:\n [\n hostTavern,\n joinTavern,\n TavernCommand,\n TavernCommands,\n TavernSubject,\n TavernHost,\n TavernHostOptions,\n TavernHostEvent,\n TavernGuest,\n TavernGuestOptions,\n TavernGuestEvent,\n TavernJoinResult,\n TavernError,\n TavernPairingError,\n TavernDisposedError,\n ]\nrelated: [mesh, ledger, herald]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tavern\" />\n\n## Why Tavern?\n\nPeer-to-peer apps share one arrangement problem: the canonical state of something: a document, a dashboard, a record: lives on exactly one device, while every other participant should see it and be able to change it from their own. Tavern turns that arrangement into a session: **one host owns the canonical state, guests mirror it, and every guest command is forwarded through the host's own command table**, so remote actions follow exactly the same code path as local ones.\n\n```ts\n// Before: hand-rolled session orchestration: pairing, protocol validation,\n// command routing, snapshot broadcasting, notice relaying, presence tracking.\nconst host = createMeshHost({\n /* ... */\n});\nhost.on('command', ({ peerId, payload }) => {\n const command = mySchema.safeParse(payload);\n if (!command.success) {\n host.send(peerId, 'rejected', {\n /* ... */\n });\n return;\n }\n try {\n applySubjectCommand(command.data.name, subject, command.data.args);\n } catch (error) {\n host.send(peerId, 'rejected', {\n /* ... */\n });\n }\n});\nbus.on('subject:updated', () => {\n host.broadcast('snapshot', snapshotFor(subject));\n});\n// ... 40+ more lines of plumbing\n\n// After: tavern owns the protocol, the validation, the broadcasting.\nconst host = hostTavern({\n commands: { rename: (args) => store.rename(docId, args[0] as string) },\n subject: {\n onChanged: (listener) => store.onUpdated(docId, listener),\n onRemoved: (listener) => store.onRemoved(docId, listener),\n snapshot: () => store.read(docId),\n },\n});\n```\n\n| Feature | Tavern | Raw mesh | Socket.io rooms |\n| ------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"tavern\" type=\"size\" /> | <PackageInfo package=\"mesh\" type=\"size\" /> | N/A |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Host-authoritative commands | <ore-icon name=\"check\" size=\"16\"></ore-icon>: same table as local UI | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: wire it yourself | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: wire it yourself |\n| Snapshot replication | <ore-icon name=\"check\" size=\"16\"></ore-icon>: microtask-coalesced | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Out-of-band pairing (QR / copy-paste) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon>: needs a server |\n| Notice relaying | <ore-icon name=\"check\" size=\"16\"></ore-icon>: consumer-defined wire shape | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: server-mediated |\n\n<div class=\"decision-callout\">\n\n**Use Tavern when** one device should own the canonical state of something: a shared document, a live dashboard, a record under review, and every other device should mirror it and send commands back through the host's own command table, which stays the single validation path.\n\n**Consider raw `@vielzeug/mesh` when** you need P2P messaging without the host-authoritative replication model: chat, whiteboards, file transfer, or custom topologies.\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",
4
+ "index": "---\ntitle: Tavern\ndescription: 'Table sessions over mesh: host-owned state replication with guest command forwarding'\npackage: tavern\ncategory: utilities\nkeywords: [session, host, guest, replication, mesh, commands, snapshots, collaboration, peer-to-peer]\nexports:\n [\n hostTavern,\n joinTavern,\n TavernCommand,\n TavernCommands,\n TavernSubject,\n TavernHost,\n TavernHostOptions,\n TavernHostEvent,\n TavernGuest,\n TavernGuestOptions,\n TavernGuestEvent,\n TavernJoinResult,\n TavernError,\n TavernPairingError,\n TavernDisposedError,\n ]\nrelated: [mesh, ledger, herald]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tavern\" />\n\n## Why Tavern?\n\nPeer-to-peer apps share one arrangement problem: the canonical state of something: a document, a dashboard, a record: lives on exactly one device, while every other participant should see it and be able to change it from their own. Tavern turns that arrangement into a session: **one host owns the canonical state, guests mirror it, and every guest command is forwarded through the host's own command table**, so remote actions follow exactly the same code path as local ones.\n\n```ts\n// Before: hand-rolled session orchestration: pairing, protocol validation,\n// command routing, snapshot broadcasting, notice relaying, presence tracking.\nconst host = createMeshHost({\n /* ... */\n});\nhost.on('command', ({ peerId, payload }) => {\n const command = mySchema.safeParse(payload);\n if (!command.success) {\n host.send(peerId, 'rejected', {\n /* ... */\n });\n return;\n }\n try {\n applySubjectCommand(command.data.name, subject, command.data.args);\n } catch (error) {\n host.send(peerId, 'rejected', {\n /* ... */\n });\n }\n});\nbus.on('subject:updated', () => {\n host.broadcast('snapshot', snapshotFor(subject));\n});\n// ... 40+ more lines of plumbing\n\n// After: tavern owns the protocol, the validation, the broadcasting.\nconst host = hostTavern({\n commands: { rename: (args) => store.rename(docId, args[0] as string) },\n subject: {\n onChanged: (listener) => store.onUpdated(docId, listener),\n onRemoved: (listener) => store.onRemoved(docId, listener),\n snapshot: () => store.read(docId),\n },\n});\n```\n\n| Feature | Tavern | Raw mesh | Socket.io rooms |\n| ------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"tavern\" type=\"size\" /> | <PackageInfo package=\"mesh\" type=\"size\" /> | N/A |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Host-authoritative commands | <ore-icon name=\"check\" size=\"16\"></ore-icon>: same table as local UI | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: wire it yourself | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: wire it yourself |\n| Snapshot replication | <ore-icon name=\"check\" size=\"16\"></ore-icon>: microtask-coalesced | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Out-of-band pairing (QR / copy-paste) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon>: needs a server |\n| Notice relaying | <ore-icon name=\"check\" size=\"16\"></ore-icon>: consumer-defined wire shape | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon>: server-mediated |\n\n<div class=\"decision-callout\">\n\n**Use Tavern when** one device should own the canonical state of something: a shared document, a live dashboard, a record under review, and every other device should mirror it and send commands back through the host's own command table, which stays the single validation path.\n\n**Consider raw `@vielzeug/mesh` when** you need P2P messaging without the host-authoritative replication model: chat, whiteboards, or custom topologies. Mesh carries bounded typed messages (capped by `maxMessageBytes`, 65 536 by default) with no chunking or acknowledgements: file transfer needs app-level chunking and acknowledgements built on top.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/tavern\n```\n\n```sh [npm]\nnpm install @vielzeug/tavern\n```\n\n```sh [yarn]\nyarn add @vielzeug/tavern\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { hostTavern, joinTavern } from '@vielzeug/tavern';\n\n// Host: wire the command table and snapshot access for the shared subject.\nconst host = hostTavern({\n commands: {\n rename: (args) => myStore.rename(docId, args[0] as string),\n append: (args) => myStore.append(docId, args[0] as string),\n },\n subject: {\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\n\n// Produce a single-use invitation code; deliver it out-of-band (QR, copy/paste).\nconst invitationCode = await host.createInvitationCode();\n\n// Guest: consume the invitation code, produce an answer code for the host.\nconst { answerCode, guest, ready } = await joinTavern({\n invitationCode,\n mount: (snapshot) => parseAndMount(snapshot),\n name: 'Alex',\n});\nawait host.acceptAnswerCode(answerCode);\n\n// `ready` settles once the first snapshot arrives and mounts: the mirror is live.\nawait ready;\n\n// The guest's commands run through the host's own table; their effect\n// arrives with the next snapshot, so a successful command needs no ack.\nguest.sendCommand('rename', ['Quarterly report']);\n\n// Cleanup: hosting ends for every guest; onEnded fires exactly once on both sides.\nhost.dispose();\nguest.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`hostTavern`**: host one subject: pairing, protocol validation, command application, coalesced snapshot broadcasts\n- **`joinTavern`**: join as a guest: consume the invitation code, produce the answer code, mirror the host's snapshots\n- **`TavernCommands`**: the host's command table as a plain record of handlers: the same functions the host's own UI calls, so remote actions cannot bypass validation\n- **`ready` promise**: the join lifecycle is awaitable: `ready` resolves with the mounted mirror or rejects with why the session never came up\n- **Coalesced snapshots**: bursts of local changes ship one snapshot per microtask, not one per change\n- **`onEnded` fires exactly once**: on both handles: channel drops, subject removal, and explicit disposal share a single idempotent cleanup path\n- **Typed errors**: `TavernPairingError` covers every unusable pasted code with the mesh failure chained as `cause`\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Mesh](/mesh/): the P2P transport underneath: WebRTC pairing, data channels, QR-optimized codecs.\n- [Ledger](/ledger/): undo/redo history for the commands the host applies.\n- [Herald](/herald/): typed event bus for the local notice stream tavern relays.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
5
  "api": "---\ntitle: 'Tavern: API Reference'\ndescription: Public API of @vielzeug/tavern.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --------------------- | ---------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------- |\n| `hostTavern()` | Host a subject: pairing, command validation, snapshot broadcast | Sync factory | Disposing ends hosting for every guest |\n| `joinTavern()` | Join a session: consume invitation code, produce answer code | Async | The session lives only after the host accepts and the first snapshot mounts |\n| `TavernHost` | Host handle: invitation, answer acceptance, kick, notice relay, presence tap | N/A | `dispose()` is idempotent; control-plane methods throw `TavernDisposedError` after |\n| `TavernGuest` | Guest handle: command forwarding, rejection tap, disposal | N/A | `dispose()` fires `onEnded` exactly once |\n| `TavernJoinResult` | Join outcome: answer code, guest handle, and the `ready` promise | N/A | A `ready` nobody awaits never surfaces as an unhandled rejection |\n| `TavernHostEvent` | Host observability union for `tap()`: presence, warnings, dispose | N/A | Lifecycle transitions are `onEnded`, not events |\n| `TavernGuestEvent` | Guest observability union for `tap()`: rejections, warnings, dispose | N/A | The opening transition is `ready`, not an event |\n| `TavernCommands` | The host's command table: a record of handlers keyed by command name | N/A | A name the record does not hold rejects without applying |\n| `TavernSubject` | Snapshot reading, change and removal subscriptions | N/A | `snapshot` returning `null` skips the broadcast |\n| `TavernError` | Base error for every Tavern failure | N/A | N/A |\n| `TavernPairingError` | The consumer pasted the wrong kind of pairing code | N/A | N/A |\n| `TavernDisposedError` | A stopped host or ended guest was used again | N/A | N/A |\n\n## Package Entry Point\n\n| Import | Purpose |\n| -------------------------- | ----------------------------------------------- |\n| `@vielzeug/tavern` | Complete public Tavern API |\n| `@vielzeug/tavern/testing` | Test seam: the fake WebRTC factory for sessions |\n\nThe `MeshPeer` type carried by host events and the `peers` getter is re-exported here, so a single import types everything.\n\n## `hostTavern(options)`\n\nCreates a mesh host for one subject. Guest commands are validated against the wire shape (Tavern's own protocol) and checked against `commands`: a name the table does not hold rejects without applying, and a handler that throws rejects the guest with the error's message. Declaring `subject.id` makes the session _named_: every guest command must name that id as `sendCommand`'s `target`, and a command that omits or misses it rejects before the table runs. Local changes (via `subject.onChanged`) re-broadcast `subject.snapshot()`: coalesced on a microtask; `subject.onRemoved` ends hosting. Presence and transport warnings are reported through `tap()` as `TavernHostEvent`s, and the live peer list is the `peers` getter; hosting ending: from removal or `dispose()`: fires `onEnded` exactly once. `relayNotice` serializes through `serializeNotice` and broadcasts to every guest.\n\n**Returns:** `TavernHost`: the host handle.\n\n| Option | Type | Description |\n| ------------------ | ----------------------------- | ----------------------------------------------------------------------------- |\n| `commands?` | `TavernCommands` | The command table guest actions run through; omit for a read-only session |\n| `onEnded?` | `() => void` | Hosting ended: the subject was removed or `dispose()` ran. Fires exactly once |\n| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |\n| `serializeNotice?` | `(notice) => unknown \\| null` | Serializes a local notice for `relayNotice`; null skips that notice |\n| `subject` | `TavernSubject` | Snapshot reading, change and removal subscriptions for the hosted subject |\n\n**Example**\n\n```ts\nimport { hostTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n commands: {\n rename: (args) => myStore.rename(docId, args[0] as string),\n append: (args) => myStore.append(docId, args[0] as string),\n },\n subject: {\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\n```\n\n### `TavernHost` members\n\n| Member | Type | Behavior |\n| ------------------------ | -------------------------------- | ---------------------------------------------------------------------------------------- |\n| `acceptAnswerCode()` | `(code) => Promise<MeshPeer>` | Consumes a guest's answer code; resolves with the peer once the channel is open |\n| `createInvitationCode()` | `() => Promise<string>` | Produces a single-use invitation code, QR-compact when the environment allows |\n| `disposalSignal` | `AbortSignal` | Aborted when hosting ends |\n| `dispose()` | `() => void` | Stops hosting: closes every channel and detaches all subscriptions; idempotent |\n| `disposed` | `boolean` | Whether hosting has ended |\n| `kick()` | `(peerId) => void` | Disconnects one guest; the guest observes it and fires `onEnded` |\n| `peers` | `readonly MeshPeer[]` | The guests currently connected |\n| `relayNotice()` | `(notice) => void` | Broadcasts `serializeNotice(notice)` to every guest. Dropped after hosting ended |\n| `tap()` | `(handler, opts?) => () => void` | Subscribes to `TavernHostEvent`s; handler errors are swallowed; detaches on abort or end |\n| `[Symbol.dispose]()` | `() => void` | Delegates to `dispose()`; enables `using` declarations |\n\n## `joinTavern(options)`\n\nJoins a session as a guest: decodes the invitation code, opens the mesh guest, and returns the answer code to show back. Snapshots mount through `mount` as they arrive; the first non-null mount settles `ready`. The session ends exactly once: from the channel dropping (`TavernError`), an early exit before mounting (`TavernDisposedError`), or disposal.\n\n**Returns:** `Promise<TavernJoinResult<Mounted>>`: the answer code, the guest handle, and the `ready` promise. Rejects with `TavernPairingError` when the invitation code cannot be used.\n\n| Option | Type | Description |\n| ---------------- | ------------------------------- | --------------------------------------------------------------------------------------- |\n| `invitationCode` | `string` | The invitation code the host produced |\n| `mount` | `(snapshot) => Mounted \\| null` | Turns a received snapshot into the mounted mirror; null ignores it. Called per snapshot |\n| `name` | `string` | The guest's display name on the channel |\n| `onEnded?` | `(subject: Mounted) => void` | The channel ended after joining; receives the mounted subject for unmounting |\n| `onNotice?` | `(wire: unknown) => void` | Receives a notice the host relayed: re-emit it in the local UI |\n| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |\n\n**Example**\n\n```ts\nimport { joinTavern } from '@vielzeug/tavern';\n\nconst { answerCode, guest, ready } = await joinTavern({\n invitationCode,\n mount: (snapshot) => mySchema.parse(snapshot),\n name: 'Alex',\n onEnded: (subject) => unmountMirror(subject),\n});\nawait host.acceptAnswerCode(answerCode);\nawait ready; // the mirror is live\n```\n\n### `TavernJoinResult<Mounted>` members\n\n| Member | Type | Behavior |\n| ------------ | ------------------ | ------------------------------------------------------------------------------------------------ |\n| `answerCode` | `string` | The answer code to show back to the host, QR-compact when the environment allows |\n| `guest` | `TavernGuest` | The guest handle |\n| `ready` | `Promise<Mounted>` | Resolves with the mounted subject on the first mount; rejects with why the session never came up |\n\n### `TavernGuest` members\n\n| Member | Type | Behavior |\n| -------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |\n| `disposalSignal` | `AbortSignal` | Aborted when the session ends |\n| `dispose()` | `() => void` | Leaves the session; `onEnded` fires exactly once |\n| `disposed` | `boolean` | Whether the session has ended |\n| `sendCommand()` | `(name, args?, target?) => void` | Forwards a command to the host's table; `target` is required on a named session; throws `TavernDisposedError` after the session ended |\n| `tap()` | `(handler, opts?) => () => void` | Subscribes to `TavernGuestEvent`s; handler errors are swallowed; detaches on abort or end |\n| `[Symbol.dispose]()` | `() => void` | Delegates to `dispose()`; enables `using` declarations |\n\n## Types\n\n### `TavernCommands`\n\n```ts\ntype TavernCommand = (args: readonly unknown[]) => void;\ntype TavernCommands = Record<string, TavernCommand>;\n```\n\nThe host's command table, keyed by name: the same functions the host's own UI calls, so guest actions follow exactly the same validation path as local ones. A missing key rejects the guest with `The host has no command named \"...\"`; a throwing handler rejects with its message. Omit the table entirely for a read-only session.\n\n### `TavernSubject`\n\n```ts\ninterface TavernSubject {\n readonly id?: string;\n onChanged(listener: () => void): () => void;\n onRemoved(listener: () => void): () => void;\n snapshot(): unknown;\n}\n```\n\nHow the host reads and watches the single subject it shares. `onChanged` is the re-broadcast trigger; `onRemoved` ends hosting; `snapshot()` returns the JSON-serializable state to broadcast, or `null` while the subject is missing (the broadcast skips). A throwing `snapshot` is reported as a `warning` tap event instead of crashing the host. `id` is the subject's stable identity: declaring it puts every command under target verification: guests must pass the id as `sendCommand`'s `target`, and a missing or mismatched target rejects with `That command does not target the hosted subject.` before the command table runs. The target is a guest claim, not a proof: the guard catches misrouted commands, while handlers and the command table stay the authorization boundary. Omit `id` for anonymous sessions, where targets carry no meaning.\n\n### `TavernHostEvent`\n\n| Variant | Fires when |\n| -------------------------------------- | ---------------------------------------------------------- |\n| `{ type: 'peer-joined'; peer }` | A guest's channel opened |\n| `{ type: 'peer-left'; peer; reason? }` | A guest's channel closed |\n| `{ type: 'warning'; message; error }` | A transport error or a throwing snapshot read was survived |\n| `{ type: 'dispose' }` | Hosting ended and the tap stream is about to clear |\n\n### `TavernGuestEvent`\n\n| Variant | Fires when |\n| ------------------------------------------ | ------------------------------------------------------ |\n| `{ type: 'rejected'; commandId; message }` | The host rejected a forwarded command |\n| `{ type: 'warning'; message; error }` | A transport error was survived |\n| `{ type: 'dispose' }` | The session ended and the tap stream is about to clear |\n\n## Errors\n\n### `TavernError`\n\nBase class for every Tavern failure; `instanceof TavernError` narrows the whole hierarchy. Channel failures before the first snapshot reject `ready` with this class.\n\n### `TavernPairingError`\n\nThe code the consumer pasted could not be used: garbage, the wrong kind, an expired invitation, or an answer the host refuses. The underlying `@vielzeug/mesh` failure is chained as `cause`.\n\n### `TavernDisposedError`\n\nA stopped host or ended guest was used again: control-plane calls throw it so leaked handles surface, and it rejects `ready` when the guest leaves before the first snapshot.\n\n## Testing\n\n`@vielzeug/tavern/testing` re-exports `createFakeRtc()` (and the `FakeRtc` type): an in-process fake WebRTC factory you pass as the `rtc` option of `hostTavern` and `joinTavern` to drive a real host/guest pair inside one test process, with no browser or network. Consuming this subpath keeps mesh, tavern's transport, out of your dev dependencies.\n\n```ts\nimport { hostTavern, joinTavern } from '@vielzeug/tavern';\nimport { createFakeRtc } from '@vielzeug/tavern/testing';\n\nconst { rtc } = createFakeRtc();\nconst host = hostTavern({ rtc, subject });\nconst guest = await joinTavern({ invitationCode: await host.createInvitationCode(), mount, name, rtc });\n```\n",
6
6
  "usage": "---\ntitle: 'Tavern: Usage Guide'\ndescription: How to use @vielzeug/tavern.\n---\n\n[[toc]]\n\n## Basic Usage\n\nHost one subject per session; guests join through the invitation/answer code pair. A session always carries exactly one subject: the guest handle needs no routing keys, and the host's command table is the single validation path for local and remote actions alike.\n\n```ts\nimport { hostTavern, joinTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n commands: { rename: (args) => myStore.rename(docId, args[0] as string) },\n subject: {\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\nconst invitationCode = await host.createInvitationCode();\n\nconst { answerCode, guest, ready } = await joinTavern({\n invitationCode,\n mount: (snapshot) => parseAndMount(snapshot),\n name: 'Alex',\n});\nawait host.acceptAnswerCode(answerCode);\nawait ready;\n\nguest.sendCommand('rename', ['Quarterly report']);\n```\n\n## Host a Subject\n\nThe host validates every guest command against its command table: a name the table does not hold rejects without applying, and a handler that throws rejects the guest with its message. The snapshot re-broadcasts on every local change: coalesced on a microtask, so bursts of changes ship one snapshot, not many. `onEnded` fires exactly once when hosting ends, whether the subject was removed or the host was disposed: reset your session UI there instead of intercepting your own `onRemoved` seam.\n\n```ts\nimport { hostTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n commands: {\n rename: (args) => myStore.rename(docId, args[0] as string),\n append: (args) => myStore.append(docId, args[0] as string),\n },\n onEnded: () => updateSessionUi(), // hosting ended: subject removed or disposed\n subject: {\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\n\n// Presence and transport warnings arrive through tap(); the peer list is a getter.\nhost.tap((event) => {\n if (event.type === 'peer-joined') toast(`${event.peer.name ?? 'A guest'} joined`);\n if (event.type === 'peer-left') toast(`${event.peer.name ?? 'A guest'} left`);\n if (event.type === 'warning') log.warn(event.message, event.error);\n updatePeerList(host.peers); // always current inside a presence event\n});\n\nconst invitationCode = await host.createInvitationCode();\n// Show the invitation code (QR or copy/paste); the guest returns an answer code.\nawait host.acceptAnswerCode(answerCode);\n\n// Kick a peer; the guest observes a disconnect and fires onEnded.\nhost.kick(peerId);\n\nhost.dispose(); // stop hosting: every guest disconnects\n```\n\nOmit `commands` for a read-only session: guests mirror the subject, and every command rejects with `The host has no command named \"...\"`.\n\n## Name the Subject to Guard Command Targets\n\nA guest tab can mirror more than one subject, so a command alone does not say enough: it must name what it acts on. Declaring `subject.id` makes tavern verify that: every command needs the hosted subject's id as `sendCommand`'s third argument, and a missing or mismatched `target` rejects with a `rejected` tap event before the command table ever runs. Without `id`, the session stays anonymous and targets carry no meaning.\n\n```ts\nconst host = hostTavern({\n commands: { rename: (args) => myStore.rename(docId, args[0] as string) },\n subject: {\n id: docId, // named session: guests must target this id\n onChanged: (listener) => myStore.onUpdated(docId, listener),\n onRemoved: (listener) => myStore.onRemoved(docId, listener),\n snapshot: () => myStore.read(docId),\n },\n});\n\n// Guest side: the mirror knows which subject it is mirroring.\nguest.sendCommand('rename', ['Quarterly report'], docId);\n```\n\nThe guard stops honest misrouting: a stray command meant for another subject in a guest tab fails loudly instead of silently mutating the hosted one. It cannot make a paired guest honest: the target is a claim, not a proof, so handlers must keep acting on their own subject and the command table remains the authorization boundary for what guests may do.\n\n## Join as a Guest\n\nJoining consumes the invitation code and produces the answer code to show back. The session goes live once the host accepts the answer and the first snapshot mounts: that transition settles the `ready` promise, so there is no race between the handshake and your code attaching handlers.\n\n```ts\nimport { joinTavern } from '@vielzeug/tavern';\n\nconst { answerCode, guest, ready } = await joinTavern({\n invitationCode,\n mount: (snapshot) => sanitizeAndMount(snapshot),\n name: 'Alex',\n onEnded: (subject) => unmountMirror(subject.id),\n});\nguest.tap((event) => {\n if (event.type === 'rejected') showToast(event.message); // event.commandId names the command it answers\n if (event.type === 'warning') log.warn(event.message, event.error);\n});\n\ntry {\n await ready; // resolves with the mounted mirror once the first snapshot arrives\n} catch (error) {\n showError(error.message); // the channel failed, the host closed it, or the guest left early\n}\n\nguest.sendCommand('rename', ['New name']);\nguest.dispose(); // leave; onEnded fires with the mounted subject exactly once\n```\n\nThe snapshot arrives as parsed JSON: `mount` receives `unknown` and should validate before trusting it. It is called for every snapshot the host broadcasts. Returning `null` ignores one; the first non-null return becomes the mounted subject: it settles `ready` and is passed to `onEnded` when the session ends. A `ready` you never await is safe: its rejection is pre-handled and never surfaces as an unhandled rejection.\n\n## Relay Notices\n\nNotices are ephemeral out-of-band UI signals: a toast fired elsewhere, a comment added. Catalog keys rather than prose cross the wire, so each client translates locally. The host serializes its own notices with `serializeNotice` and relays them with `relayNotice`; guests receive them through `onNotice`.\n\n```ts\n// Host side: forward local notices through the session.\nconst host = hostTavern({\n /* ... */\n serializeNotice: (notice) => (isLocalNotice(notice) ? toWireShape(notice) : null),\n});\nhost.relayNotice(localNotice); // null from serializeNotice skips this one\n\n// Guest side: re-emit received notices in the local UI.\nconst { guest } = await joinTavern({\n /* ... */\n onNotice: (wire) => bus.emit('notify', wire),\n});\n```\n\n**Echo guard**: a tab that both hosts and guests must prevent re-broadcasting a wire-originated notice back to its own guests: `onNotice` emits locally, the host's local subscription picks it up, and without a guard it would loop. One boolean set during `onNotice` and checked in `serializeNotice` is sufficient: the consumer owns this because only they know their local event system.\n\n## Observe with tap()\n\nBoth handles expose `tap()` for observability: presence and warnings on the host, rejections and warnings on the guest. Handler errors are swallowed, and the subscription detaches when its signal aborts or the session ends. Lifecycle stays out of the observability stream: `ready` covers the opening transition on the guest, and `onEnded` covers the closing transition on both handles.\n\n```ts\nimport type { TavernGuestEvent, TavernHostEvent } from '@vielzeug/tavern';\n\nhost.tap((event: TavernHostEvent) => {\n if (event.type === 'warning') log.warn(event.message, event.error); // the original error, not just text\n if (event.type === 'dispose') log.info('hosting ended');\n});\nguest.tap((event: TavernGuestEvent) => {\n if (event.type === 'rejected') log.info(`command ${event.commandId} rejected: ${event.message}`);\n});\n```\n\n## Handle Pairing Mistakes\n\nEvery user-input pairing failure surfaces as `TavernPairingError` from both `acceptAnswerCode` and `joinTavern`: a garbage code, the wrong code kind, an expired invitation, or an answer the host refuses. Catch it to show a helpful message instead of a raw error; the underlying mesh failure is chained as `cause` when you need it.\n\n```ts\nimport { hostTavern, TavernPairingError } from '@vielzeug/tavern';\n\ntry {\n await host.acceptAnswerCode(pastedCode);\n} catch (error) {\n if (error instanceof TavernPairingError) {\n showToast(error.message); // \"That code is an invitation, not a guest answer.\"\n } else {\n throw error;\n }\n}\n```\n\n## Working with Other Vielzeug Libraries\n\nTavern builds on `@vielzeug/mesh` for the WebRTC transport, pairing codes, and QR-optimized codecs. You do not interact with mesh directly: tavern owns the protocol, but the `rtc` option accepts a `MeshRtcFactory` for testing or non-browser runtimes. The peers carried by tap events and the {@link TavernHost.peers} getter are mesh types, re-exported by tavern so one import types everything.\n\n```ts\nimport type { MeshRtcFactory } from '@vielzeug/mesh';\nimport { hostTavern } from '@vielzeug/tavern';\n\nconst host = hostTavern({\n // ... commands, subject\n rtc: myTestRtcFactory, // inject an in-memory WebRTC fake\n});\n```\n\nPair `@vielzeug/ledger` on the host to give the commands tavern applies an undo history: commands applied through the table land in the ledger like local ones.\n\n## Best Practices\n\n- Keep the command table the same functions the host's own UI calls, so guest actions cannot bypass local validation.\n- Return `null` from `snapshot` while the subject is missing: the broadcast simply skips.\n- Reset host-side session UI in `onEnded`: it fires exactly once for subject removal and explicit disposal alike, so you never need to double-wire your own `onRemoved` seam.\n- Await `ready` before trusting the mirror: it names the exact reason a session never came up, and its rejection is safe to ignore when you do not care.\n- Treat notices as catalog keys, not prose: each client translates locally.\n- Guard against notice echo if a tab can both host and guest: one boolean in `serializeNotice` is sufficient.\n- Dispose guests and hosts when their screen unmounts; channels also clean up on disconnect through `onEnded`, which fires exactly once on both sides.\n- Catch `TavernPairingError` separately from other errors: it means the pasted code could not be used, not that something is broken.\n",
7
7
  "examples": "---\ntitle: 'Tavern: Examples'\ndescription: Practical examples and recipes for @vielzeug/tavern.\n---\n\n## Examples\n\n- [Share State Across Devices](./examples/share-state-across-devices.md)\n"