@vielzeug/codex 26.11.13 → 26.11.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/catalog.json +58 -52
- package/data/llms-full.txt +233 -71
- package/data/llms.txt +1 -1
- package/data/manifest.json +1 -1
- package/data/packages/codex.json +1 -1
- package/data/packages/ledger.json +1 -1
- package/data/packages/lingua.json +1 -1
- package/data/packages/patchwork.json +8 -3
- package/data/packages/scribe.json +2 -2
- package/data/packages/tabula.json +11 -12
- package/data/packages/tavern.json +2 -2
- package/data/packages/wayfinder.json +12 -4
- package/dist/consumer.d.ts +17 -0
- package/dist/consumer.js +114 -0
- package/dist/consumer.js.map +1 -0
- package/dist/tools/packages.js +50 -0
- package/dist/tools/packages.js.map +1 -1
- package/package.json +2 -2
- package/skills/vielzeug/SKILL.md +1 -1
package/data/packages/codex.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"docs": {
|
|
4
4
|
"index": "---\ntitle: Codex\ndescription: Local MCP access to Vielzeug documentation and package metadata.\npackage: codex\ncategory: AI\nkeywords: [mcp, docs, ai]\nrelated: [refine]\nexports: [loadSnapshot, SnapshotCatalog, createMcpServer, startHttpHost, StdioServerTransport, CatalogError, CodexError]\nenvironments: [node]\n---\n\n<PackageHero package=\"codex\" />\n\n## Why Codex?\n\nCodex exposes current Vielzeug catalog data through MCP without scanning source at request time.\n\n## Installation\n\n```sh\npnpm add @vielzeug/codex\n```\n\n## Quick Start\n\n```sh\nnpx -y @vielzeug/codex\n```\n\n## Features\n\n- `loadSnapshot` validates chunked snapshot metadata.\n- `SnapshotCatalog` loads package content only when requested.\n- `createMcpServer` registers package tools, plus Refine component tools whenever the snapshot carries them.\n- The single entry point publishes TypeScript declarations.\n- `startHttpHost` enforces loopback binding plus localhost Host and Origin validation.\n\n## Documentation\n\n- [Usage](./usage.md)\n- [API](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n## See Also\n\n- [Refine](../refine/) provides component metadata bundled by Codex.\n",
|
|
5
5
|
"api": "---\ntitle: Codex API\ndescription: Snapshot, catalog, MCP server, and local HTTP host APIs.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------ | ------------------------------------------ | -------------- | ------------------------------------- |\n| `loadSnapshot` | Read validated snapshot metadata | Sync | Content chunks load lazily |\n| `validateSnapshot` | Full artifact verification (all chunks) | Sync | Generation/CI use, not normal startup |\n| `SnapshotCatalog` | Query package corpus and Refine components | Sync | Construct from loaded snapshot |\n| `createMcpServer` | MCP adapter factory | Sync | Requires catalog and version |\n| `startHttpHost` | Loopback Streamable HTTP host | Async | HTTP remains local-only |\n\n## Package Entry Point\n\n`@vielzeug/codex` is the single entry point: catalog (package docs plus bundled Refine component\nmetadata), snapshot loader, errors, the MCP server factory, the loopback HTTP host, and a\nre-export of `StdioServerTransport`. There is one `Catalog` surface and one server factory.\n\n## Snapshot\n\n### `loadSnapshot`\n\n```ts\nloadSnapshot(directory?: string, options?: { validateContents?: boolean }): LoadedSnapshot;\n```\n\nLoads one snapshot directory: `manifest.json` plus `catalog.json` (eager metadata), an optional\n`refine.json`, and lazily read `packages/<slug>.json` content chunks. `directory` defaults to the\nbundled `data/`. The snapshot layout is fixed by code; the manifest carries `{ schemaVersion, version }`\nonly. `validateContents: true` turns the lazy chunks into an eager cross-checked read.\n\n### `validateSnapshot`\n\n```ts\nvalidateSnapshot(snapshotRoot?: string): void;\n```\n\nRuns `loadSnapshot` with `validateContents: true`. Used by snapshot generation, integration tests,\nand artifact verification; normal startup keeps package chunks lazy.\n\n### `SnapshotCatalog`\n\n```ts\nnew SnapshotCatalog(snapshot: LoadedSnapshot)\n```\n\nProvides package lookup, docs/source/example/signature access, deterministic search, and the\nRefine component lookup (`listComponents()`, `getComponent(tagName)`). Component methods return an\nempty list (and `NOT_FOUND` per tag) when the snapshot carries no Refine metadata. `search()`\nreads content chunks through the same lazy cache as the content getters; there is no separate\nsearch index.\n\n---\n\n## MCP\n\n### `createMcpServer`\n\n```ts\ncreateMcpServer(catalog: Catalog, options: { version: string; debug?: boolean }): Server;\n```\n\nRegisters the generic package tools over `Catalog`, plus the `refine-*` component tools when the\ncatalog actually carries Refine metadata; tools that could only answer \"unavailable\" are never\noffered. The root also re-exports `StdioServerTransport` for connecting the server without a\nsecond package import.\n\n## HTTP\n\n### `startHttpHost`\n\n```ts\nstartHttpHost(options: HttpHostOptions): Promise<HttpHost>;\n```\n\nStarts Streamable HTTP on `127.0.0.1` by default. Runtime validation accepts only `127.0.0.1` or\n`::1`; every request must also pass localhost Host and Origin checks. `createServer` must return a\nfresh, unconnected server with its request handlers registered.\n\n## Types\n\n```ts\ninterface SnapshotManifest {\n readonly schemaVersion: typeof SNAPSHOT_SCHEMA_VERSION;\n readonly version: string;\n}\n\ninterface LoadedSnapshot {\n readonly catalog: CatalogFile;\n readonly contentDirectory: string;\n readonly manifest: SnapshotManifest;\n readonly refineComponents: readonly CemDeclaration[];\n}\n```\n\n```ts\ninterface CatalogFile {\n readonly packages: readonly PackageMeta[];\n readonly version: string;\n}\n\ninterface PackageMeta {\n readonly availableDocPages: readonly DocPage[];\n readonly category: string;\n readonly description: string;\n readonly exampleIds: readonly string[];\n readonly exports: readonly string[];\n readonly hasSource: boolean;\n readonly keywords: readonly string[];\n readonly name: string;\n readonly related: readonly string[];\n readonly slug: string;\n readonly version: string;\n}\n\ninterface Example {\n readonly code: string;\n readonly id: string;\n readonly name: string;\n}\n```\n\n```ts\ninterface Catalog {\n getComponent(tagName: string): CemDeclaration;\n getDocs(slug: string, page: DocPage): string;\n getExample(slug: string, exampleId: string): Example;\n getPackage(slug: string): PackageMeta;\n getSource(slug: string): string;\n getTypeSignature(slug: string, symbol: string): string;\n listComponents(): readonly CemDeclaration[];\n listExamples(slug: string): readonly Pick<Example, 'id' | 'name'>[];\n listPackages(): readonly PackageMeta[];\n search(query: string): readonly SearchHit[];\n}\n\ninterface SearchHit {\n readonly matchedExamples?: readonly string[];\n readonly matchedIn: readonly ('docs' | 'examples' | 'exports' | 'keywords' | 'metadata' | 'related' | 'source')[];\n readonly matchedPages?: readonly DocPage[];\n readonly name: string;\n readonly slug: string;\n}\n```\n\nCatalog exposes semantic reads. It does not expose its cached content chunks.\n\n```ts\ninterface HttpHost {\n dispose(): Promise<void>;\n readonly disposed: boolean;\n readonly host: string;\n readonly port: number;\n [Symbol.asyncDispose](): Promise<void>;\n}\n\ninterface HttpHostOptions {\n createServer: () => Server;\n host?: '127.0.0.1' | '::1';\n port: number;\n version: string;\n}\n```\n\n```ts\nconst DOC_PAGES = ['index', 'api', 'usage', 'examples'] as const;\ntype DocPage = (typeof DOC_PAGES)[number];\n\nconst SNAPSHOT_SCHEMA_VERSION = 2 as const;\n```\n\n```ts\ninterface CemDeclaration {\n readonly attributes?: readonly CemAttribute[];\n readonly cssParts?: readonly CemCssPart[];\n readonly cssProperties?: readonly CemCssProperty[];\n readonly description?: string;\n readonly events?: readonly CemEvent[];\n readonly members?: readonly CemMember[];\n readonly name?: string;\n readonly slots?: readonly CemSlot[];\n readonly superclass?: { readonly name: string; readonly package?: string };\n readonly tagName?: string;\n readonly [key: string]: unknown;\n}\n\ninterface CemAttribute {\n readonly default?: string;\n readonly description?: string;\n readonly fieldName?: string;\n readonly name: string;\n readonly type?: { readonly text: string };\n}\n\ninterface CemCssPart {\n readonly description?: string;\n readonly name: string;\n}\n\ninterface CemCssProperty {\n readonly default?: string;\n readonly description?: string;\n readonly name: string;\n}\n\ninterface CemEvent {\n readonly description?: string;\n readonly name: string;\n readonly type?: { readonly text: string };\n}\n\ninterface CemMember {\n readonly description?: string;\n readonly kind?: 'field' | 'method';\n readonly name: string;\n readonly type?: { readonly text: string };\n}\n\ninterface CemSlot {\n readonly description?: string;\n readonly name: string;\n}\n```\n\nComponent declarations and their nested data use readonly TypeScript types. The loader pins only\nthe contract its consumers depend on: declarations form an array with valid, unique custom-element\n`tagName`s.\n\n## Errors\n\n`CodexError` signals malformed snapshots or host failures. `CatalogError` adds `INVALID_ARG`,\n`NOT_FOUND`, or `UNAVAILABLE` for expected tool failures.\n",
|
|
6
|
-
"usage": "---\ntitle: 'Codex: Usage Guide'\ndescription: Install, connect, develop, and debug the Vielzeug MCP server.\n---\n\n[[toc]]\n\n## Basic Usage\n\nRun local stdio server:\n\n```sh\nnpx -y @vielzeug/codex\n```\n\nUse shipped `mcp-setup.json` for machine-readable generic configuration. Client-specific configuration must use its documented MCP format.\n\n## HTTP Mode\n\nHTTP uses Streamable HTTP and binds loopback only:\n\n```sh\nnpx -y @vielzeug/codex --port=3100\ncurl http://127.0.0.1:3100/health\n```\n\nResponse includes snapshot version. Runtime bind validation and Host/Origin allowlists restrict access to localhost; no remote host mode exists. Programmatic HTTP hosting takes a `createServer` factory that returns a fresh, unconnected server with its request handlers registered. Dispose the host asynchronously and observe `disposed` when coordinating shutdown.\n\n## Agent Skill\n\nCodex ships a `vielzeug` agent skill: a `SKILL.md` that tells an AI agent working in _your_ project to discover packages through the MCP tools instead of guessing, to use the owning `@vielzeug/*` package instead of hand-rolling, and to build UI from Refine components, tokens, and theme whenever `@vielzeug/refine` is installed. Install it into the project:\n\n```sh\nnpx -y @vielzeug/codex skills install\nnpx -y @vielzeug/codex skills install --target=.claude/skills\nnpx -y @vielzeug/codex skills install --force # overwrite an existing copy\n```\n\nWithout `--target`, the first existing directory among `.agents/skills`, `.github/skills`, and `.claude/skills` is used; when none exists, `.agents/skills` is created. The command refuses to overwrite an installed skill unless `--force` is passed. Rerun after upgrading codex to pick up the current package list, which is generated from the published manifests. The skill pairs with the MCP server: its lookups (`get-docs`, `refine-get-component`, `refine-validate-usage`, …) assume codex is connected, and it documents `node_modules` fallbacks for when it is not.\n\n## Local Development\n\nRequires Node 22+ and root setup:\n\n```sh\nbun install\ncd packages/codex\nbun run test:unit\nbun run test:integration\nbun run dev\n```\n\n`test:unit` uses fixtures only. `test:integration` regenerates a current snapshot then checks real monorepo inputs.\n\n`bun run dev` watches documentation and package inputs, regenerates `.dev/` through a staging swap, and restarts the server against it.\n\n## Debugging\n\n```sh\nbun run dev\nnode src/cli.ts --port=3100 --debug\ncurl http://127.0.0.1:3100/health\n```\n\n`--debug` logs tool durations and expected catalog errors to stderr. Build `@vielzeug/refine` before generating snapshot when component metadata changes.\n\n## Programmatic Usage\n\n```ts\nimport { SnapshotCatalog, StdioServerTransport, createMcpServer, loadSnapshot } from '@vielzeug/codex';\n\nconst snapshot = loadSnapshot();\nconst catalog = new SnapshotCatalog(snapshot);\nawait createMcpServer(catalog, { version: snapshot.manifest.version }).connect(new StdioServerTransport());\n```\n\n`createMcpServer` also registers the `refine-*` component tools whenever the loaded snapshot carries Refine metadata; there is nothing to opt into.\n\n## Best Practices\n\n- Use `search-packages` for capability discovery before loading broad source.\n- Use `get-type-signature` before loading full source.\n- Every snapshot is one flat directory (manifest, catalog, content chunks, optional Refine metadata); `--snapshot` points at it directly.\n- Pass `validateContents: true` to `loadSnapshot()` for artifact verification; normal startup keeps package chunks lazy.\n- Return a fresh configured server from `startHttpHost`'s `createServer` factory.\n- Keep HTTP local. Use stdio for normal client integration.\n- Run `bun run test:unit` before `bun run test:integration`.\n",
|
|
6
|
+
"usage": "---\ntitle: 'Codex: Usage Guide'\ndescription: Install, connect, develop, and debug the Vielzeug MCP server.\n---\n\n[[toc]]\n\n## Basic Usage\n\nRun local stdio server:\n\n```sh\nnpx -y @vielzeug/codex\n```\n\nUse shipped `mcp-setup.json` for machine-readable generic configuration. Client-specific configuration must use its documented MCP format.\n\n## HTTP Mode\n\nHTTP uses Streamable HTTP and binds loopback only:\n\n```sh\nnpx -y @vielzeug/codex --port=3100\ncurl http://127.0.0.1:3100/health\n```\n\nResponse includes snapshot version. Runtime bind validation and Host/Origin allowlists restrict access to localhost; no remote host mode exists. Programmatic HTTP hosting takes a `createServer` factory that returns a fresh, unconnected server with its request handlers registered. Dispose the host asynchronously and observe `disposed` when coordinating shutdown.\n\n## Agent Skill\n\nCodex ships a `vielzeug` agent skill: a `SKILL.md` that tells an AI agent working in _your_ project to discover packages through the MCP tools instead of guessing, to use the owning `@vielzeug/*` package instead of hand-rolling, and to build UI from Refine components, tokens, and theme whenever `@vielzeug/refine` is installed. Install it into the project:\n\n```sh\nnpx -y @vielzeug/codex skills install\nnpx -y @vielzeug/codex skills install --target=.claude/skills\nnpx -y @vielzeug/codex skills install --force # overwrite an existing copy\n```\n\nWithout `--target`, the first existing directory among `.agents/skills`, `.github/skills`, and `.claude/skills` is used; when none exists, `.agents/skills` is created. The command refuses to overwrite an installed skill unless `--force` is passed. Rerun after upgrading codex to pick up the current package list, which is generated from the published manifests. The skill pairs with the MCP server: its lookups (`get-docs`, `refine-get-component`, `refine-validate-usage`, …) assume codex is connected, and it documents `node_modules` fallbacks for when it is not.\n\n## Local Development\n\nRequires Node 22+ and root setup:\n\n```sh\nbun install\ncd packages/codex\nbun run test:unit\nbun run test:integration\nbun run dev\n```\n\n`test:unit` uses fixtures only. `test:integration` regenerates a current snapshot then checks real monorepo inputs.\n\n`bun run dev` watches documentation and package inputs, regenerates `.dev/` through a staging swap, and restarts the server against it.\n\n## Debugging\n\n```sh\nbun run dev\nnode src/cli.ts --port=3100 --debug\ncurl http://127.0.0.1:3100/health\n```\n\n`--debug` logs tool durations and expected catalog errors to stderr. Build `@vielzeug/refine` before generating snapshot when component metadata changes.\n\n## Programmatic Usage\n\n```ts\nimport { SnapshotCatalog, StdioServerTransport, createMcpServer, loadSnapshot } from '@vielzeug/codex';\n\nconst snapshot = loadSnapshot();\nconst catalog = new SnapshotCatalog(snapshot);\nawait createMcpServer(catalog, { version: snapshot.manifest.version }).connect(new StdioServerTransport());\n```\n\n`createMcpServer` also registers the `refine-*` component tools whenever the loaded snapshot carries Refine metadata; there is nothing to opt into.\n\n## Best Practices\n\n- Use `search-packages` for capability discovery before loading broad source.\n- Use `get-type-signature` before loading full source.\n- Call `check-install` when working inside a project that depends on `@vielzeug/*`: it compares the served snapshot with the versions that project declares and its lockfile resolves, so agents can tell whether snapshot docs may lag the install.\n- Every snapshot is one flat directory (manifest, catalog, content chunks, optional Refine metadata); `--snapshot` points at it directly.\n- Pass `validateContents: true` to `loadSnapshot()` for artifact verification; normal startup keeps package chunks lazy.\n- Return a fresh configured server from `startHttpHost`'s `createServer` factory.\n- Keep HTTP local. Use stdio for normal client integration.\n- Run `bun run test:unit` before `bun run test:integration`.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Codex: Examples'\ndescription: Practical MCP tool-call examples for package discovery, docs lookup, and Refine component queries.\n---\n\n## Examples\n\n- [Listing Packages](./examples/listing-packages.md)\n- [Searching Packages](./examples/searching-packages.md)\n- [Package Metadata](./examples/package-metadata.md)\n- [Reading Docs](./examples/reading-docs.md)\n- [Running REPL Examples](./examples/running-repl-examples.md)\n- [Looking Up Components](./examples/looking-up-components.md)\n- [Inspector](./examples/inspector.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [],
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"index": "---\ntitle: 'Ledger: Reversible async history'\ndescription: Serialized reversible command history with cancellation ownership and atomic reactive snapshots.\npackage: ledger\ncategory: utilities\nkeywords: [undo, redo, history, commands, async, reactive, ripple]\nexports:\n [\n compose,\n createLedger,\n LedgerError,\n LedgerCancelledError,\n LedgerConfigError,\n LedgerDisposedError,\n LedgerExecutionError,\n LedgerRollbackError,\n ]\nrelated: [ripple, keymap, forge, vault]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"ledger\" />\n\n## Why Ledger?\n\nUndo and redo require more than array manipulation when operations are asynchronous, cancellable, and visible in a UI. Ledger serializes only reversible commands, owns queue lifecycle, and publishes one atomic framework-neutral state snapshot without a reactive runtime dependency.\n\n```ts\n// Before\nconst undo = () => changes.pop()?.revert();\n\n// After\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger();\nawait ledger.do({ apply: saveNext, revert: restorePrevious });\nawait ledger.undo();\n```\n\n| Feature | Roll your own | Ledger |\n| ----------------------- | ----------------------- | -------------------------------------------- |\n| Bundle size | 0 B | <PackageInfo package=\"ledger\" type=\"size\" /> |\n| Reversible history | Manual arrays | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Serialized async work | Manual queue | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Queue cancellation | Manual ownership | Abort-aware lifecycle |\n| Framework-neutral state | Manual events | Structural `Subscribable<LedgerState>` |\n| Composition | Custom transaction code | `compose()` |\n\n<div class=\"decision-callout\">\n\n**Use Ledger when** you own reversible asynchronous state transitions and need undo, redo, or history UI.\n\n**Consider direct application code when** work is irreversible, fire-and-forget, or does not need history.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/ledger\n```\n\n```sh [npm]\nnpm install @vielzeug/ledger\n```\n\n```sh [yarn]\nyarn add @vielzeug/ledger\n```\n\n:::\n\n## Quick Start\n\nSubmit a reversible command, read state, then dispose its owner.\n\n```ts\nimport { createLedger } from '@vielzeug/ledger';\n\nlet value = 'before';\nconst ledger = createLedger();\n\nawait ledger.do({\n apply: () => {\n value = 'after';\n },\n label: 'Rename value',\n revert: () => {\n value = 'before';\n },\n});\n\nawait ledger.undo();\nconsole.log(ledger.state.getSnapshot().undo.length); // 0\nledger.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createLedger()`: Create serialized reversible command history\n- `state`: Read atomic queue, undo, redo, and acceptance state\n- `compose()`: Combine reversible commands into one reversible command\n- `whenIdle()`: Await queued and active operation settlement\n- `LedgerCancelledError`: Distinguish cancellation from execution failure\n- `maxHistory`: Keep a non-negative safe-integer undo depth\n- `[Symbol.dispose]()`: Seal, abort, and clear a ledger owner\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- [Ripple](/ripple/): Project Ledger's structural state readable into a signal when reactive derivations are needed.\n- [Keymap](/keymap/): Route undo and redo shortcuts to a Ledger error boundary.\n- [Forge](/forge/): Record reversible form transitions.\n- [Vault](/vault/): Persist application snapshots outside transient undo history.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
5
|
"api": "---\ntitle: 'Ledger: API Reference'\ndescription: Reference for serialized reversible commands, history state, composition, cancellation, disposal, and errors.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| -------------------------- | --------------------------------------- | ----------------- | ------------------------------------------- |\n| `createLedger()` | Create serialized reversible history | Sync construction | Every operation method is queued |\n| `compose()` | Combine commands into one history entry | Sync construction | Child metadata is not aggregated |\n| `ledger.do()` | Apply and record a command | Async | Failed or cancelled apply is not recorded |\n| `ledger.undo()` / `redo()` | Move the latest history entry | Async | Failures leave history on its original side |\n| `ledger.clear()` | Remove history without reverting | Async | Serialized behind earlier work |\n| `ledger.whenIdle()` | Await an empty operation queue | Async | Cannot force non-cooperative work to settle |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | -------------------------------------------------------------------------------------------------------------- |\n| `@vielzeug/ledger` | Complete Ledger runtime, error hierarchy, state-readable contract, unsubscribe type, and command/history types |\n\n## `createLedger()`\n\n```ts\nfunction createLedger<TMeta = undefined>(options?: LedgerOptions): Ledger<TMeta>;\n```\n\nCreates a ledger with one submission-order operation queue and one atomic state readable.\n\n```ts\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger<{ field: string }>({ maxHistory: 50 });\n```\n\n### `LedgerOptions`\n\n```ts\ninterface LedgerOptions {\n maxHistory?: number;\n}\n```\n\n`maxHistory` defaults to `100`. It must be a non-negative safe integer. `0` executes commands without retaining history.\n\n## `compose()`\n\n```ts\nfunction compose<TMeta = undefined>(\n commands: readonly ReversibleCommand<TMeta>[],\n label?: string,\n): ReversibleCommand<TMeta>;\n```\n\nSnapshots child command callbacks, applies children in order, and reverts them in reverse order. The result creates one history entry with the supplied label and `meta: undefined`.\n\nIf child application fails, completed children are compensated in reverse order. Compensation attempts continue after failures. Combined apply and compensation failures are preserved in an `AggregateError`, which Ledger exposes as `LedgerExecutionError.cause`. Normal composed reversion also attempts every child and reports failures through `LedgerRollbackError.cause` as an `AggregateError`.\n\n## `Ledger`\n\n```ts\ninterface Ledger<TMeta = undefined> {\n clear(): Promise<void>;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n do(command: ReversibleCommand<TMeta>, options?: LedgerCallOptions): Promise<void>;\n redo(options?: LedgerCallOptions): Promise<void>;\n readonly state: Subscribable<LedgerState<TMeta>>;\n undo(options?: LedgerCallOptions): Promise<void>;\n whenIdle(): Promise<void>;\n [Symbol.dispose](): void;\n}\n```\n\nAll operation methods are serialized in call order.\n\n### `do()`\n\nSnapshots the command's `apply`, `revert`, `label`, and metadata reference when submitted. On successful apply it appends one undo entry, evicts the oldest entry beyond `maxHistory`, and clears redo history. Apply failure rejects with `LedgerExecutionError` and records nothing. Ledger does not automatically revert a failed individual command.\n\n### `undo()`\n\nReverts the final undo entry. Success moves it to the end of redo history. If no undo entry exists, the queued operation resolves without changing history. Revert failure rejects with `LedgerRollbackError` and leaves the entry in undo history.\n\n### `redo()`\n\nApplies the final redo entry. Success moves it to the end of undo history. If no redo entry exists, it resolves without changing history. Apply failure rejects with `LedgerExecutionError` and leaves the entry in redo history.\n\n### `record()`\n\nAppends an already-executed command to undo history synchronously, without running it through the queue. For stores that execute their own writes: typically synchronous, embedded state stores: `undo()` calls the recorded `revert`, and `redo()` calls the recorded `apply`, so `apply` must be able to re-apply the effect. Recording shares `do()`'s bookkeeping: it clears redo history and evicts the oldest entry beyond `maxHistory`. It throws `LedgerDisposedError` on a disposed ledger.\n\n### `clear()`\n\nQueues removal of all undo and redo entries. It does not call command revert functions and does not cancel earlier work. When history is already empty it resolves without queueing; after disposal it rejects with `LedgerDisposedError`.\n\n### `whenIdle()`\n\nResolves immediately when `queued` and `running` are zero, otherwise resolves after both reach zero. Multiple waiters are supported. It rejects with `LedgerDisposedError` when the ledger is disposed, immediately or while waiting.\n\n### Disposal\n\n`dispose()` is permanent and idempotent. It clears undo and redo history, aborts active command contexts, rejects queued operations that have not started with `LedgerDisposedError`, and rejects pending `whenIdle()` waiters. Active commands must observe their signal and settle before `running` reaches zero. Read `disposed` to detect permanent disposal. `[Symbol.dispose]()` delegates to `dispose()`.\n\n## Command Types\n\n### `ReversibleCommand`\n\n```ts\ninterface ReversibleCommand<TMeta = undefined> {\n readonly apply: (context: CommandContext) => Promise<void> | void;\n readonly label?: string;\n readonly meta?: TMeta;\n readonly revert: (context: CommandContext) => Promise<void> | void;\n}\n```\n\n`apply` and `revert` may be synchronous or asynchronous. Metadata is retained by reference; Ledger does not deep-clone or deep-freeze it.\n\n### `CommandContext`\n\n```ts\ninterface CommandContext {\n readonly signal: AbortSignal;\n}\n```\n\nThe signal combines ledger disposal with the operation signal. Queued cancellation prevents user code from running. Active cancellation is cooperative. If user code ignores abort and completes, the operation still rejects with `LedgerCancelledError` and its history transition is not committed.\n\n### `LedgerCallOptions`\n\n```ts\ninterface LedgerCallOptions {\n signal?: AbortSignal;\n}\n```\n\nSupported by `do()`, `undo()`, and `redo()`. `clear()` has no call options.\n\n## State Types\n\n### `LedgerState`\n\n```ts\ninterface LedgerState<TMeta = undefined> {\n readonly queued: number;\n readonly redo: readonly HistoryEntry<TMeta>[];\n readonly running: number;\n readonly undo: readonly HistoryEntry<TMeta>[];\n}\n```\n\n| Field | Meaning |\n| --------- | ----------------------------------------------------------------------- |\n| `queued` | Submitted operations that have not started |\n| `running` | Currently executing operation; serialization keeps this at 0 or 1 |\n| `undo` | Chronological successfully applied history; final entry is next to undo |\n| `redo` | Chronological reverted history; final entry is next to redo |\n\nState objects and history arrays are frozen replacements.\n\n### `HistoryEntry`\n\n```ts\ninterface HistoryEntry<TMeta = undefined> {\n readonly label: string | undefined;\n readonly meta: TMeta | undefined;\n}\n```\n\nHistory entries are frozen and intentionally omit command callbacks.\n\n### `Subscribable` and `Unsubscribe`\n\n`Ledger.state` implements this framework-neutral structural contract, which matches `Subscribable` in `@vielzeug/arsenal`. Both names are root type exports.\n\n```ts\ntype Unsubscribe = () => void;\n\ninterface Subscribable<T> {\n getSnapshot(): T;\n subscribe(listener: () => void): Unsubscribe;\n}\n```\n\nSubscriptions are not immediate and receive no value argument. Listeners run synchronously from a snapshot after state replacement. A listener failure does not interrupt Ledger bookkeeping or later listeners; it is rethrown in a microtask.\n\n## Errors\n\n| Error | Trigger | History result |\n| ---------------------- | ------------------------------------------------------------- | ------------------------------------------ |\n| `LedgerCancelledError` | Queued signal cancellation or active cooperative cancellation | No transition committed |\n| `LedgerDisposedError` | Submission after disposal or queued work rejected by disposal | History already cleared by disposal |\n| `LedgerExecutionError` | `apply()` fails during `do()` or `redo()` | New command absent, or redo entry retained |\n| `LedgerRollbackError` | `revert()` fails during `undo()` | Undo entry retained |\n| `LedgerConfigError` | Invalid `maxHistory` | Construction fails |\n| `LedgerError` | Base class and internal history corruption | Depends on operation |\n\nWrapped operation failures preserve the original value in `.cause`. Use `instanceof LedgerError` to catch the hierarchy, then narrow to a specific subtype.\n",
|
|
6
6
|
"usage": "---\ntitle: 'Ledger: Usage Guide'\ndescription: Record reversible commands, observe serialized history, handle failures, and own cancellation and disposal.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCapture both sides of a reversible transition before submitting it.\n\n```ts\nimport { createLedger } from '@vielzeug/ledger';\n\nusing ledger = createLedger();\nconst item = { name: 'Old name' };\nconst previous = item.name;\nconst next = 'New name';\n\nawait ledger.do({\n apply: () => {\n item.name = next;\n },\n label: 'Rename item',\n revert: () => {\n item.name = previous;\n },\n});\n\nawait ledger.undo();\nawait ledger.redo();\n```\n\nAll `do()`, `undo()`, `redo()`, and `clear()` calls join one submission-order queue. Keep irreversible effects outside commands unless they have a real compensating operation.\n\n## Read Atomic State\n\n`state` is a framework-neutral `Subscribable`, not a Ripple signal. Read `getSnapshot()`, and subscribe to invalidation callbacks.\n\n```ts\nfunction renderHistory(): void {\n const { queued, redo, running, undo } = ledger.state.getSnapshot();\n undoButton.disabled = undo.length === 0 || ledger.disposed;\n redoButton.disabled = redo.length === 0 || ledger.disposed;\n spinner.hidden = queued + running === 0;\n}\n\nrenderHistory();\nconst stop = ledger.state.subscribe(renderHistory);\n```\n\nSubscriptions are not immediate and receive no value argument. They run synchronously from a listener snapshot after every state replacement. A failure is rethrown in a microtask without interrupting Ledger bookkeeping or later subscribers.\n\nState objects, history arrays, and history entries are frozen snapshots. `undo` and `redo` are chronological; the next command to undo or redo is the final item. Metadata values are retained by reference rather than deep-cloned.\n\n## Attach History Metadata\n\nSet `label` for presentation and use the ledger's metadata type for application context.\n\n```ts\nconst ledger = createLedger<{ field: string }>();\n\nawait ledger.do({\n apply: () => {\n form.email = next;\n },\n label: 'Edit email',\n meta: { field: 'email' },\n revert: () => {\n form.email = previous;\n },\n});\n\nconsole.log(ledger.state.getSnapshot().undo.at(-1));\n```\n\nLedger snapshots command callbacks, label, and metadata references when `do()` is submitted. Later mutation of the command object does not replace the captured callbacks.\n\n## Compose Reversible Commands\n\n`compose()` produces one command and one history entry. Children apply in order and revert in reverse order.\n\n```ts\nimport { compose } from '@vielzeug/ledger';\n\nawait ledger.do(\n compose(\n [\n {\n apply: () => {\n node.x = nextX;\n },\n revert: () => {\n node.x = previousX;\n },\n },\n {\n apply: () => {\n node.y = nextY;\n },\n revert: () => {\n node.y = previousY;\n },\n },\n ],\n 'Move node',\n ),\n);\n```\n\nIf a child apply fails, already-applied children are compensated in reverse order. Compensation continues after failures. If application and compensation both fail, `LedgerExecutionError.cause` is an `AggregateError` containing all failures. A composed command records the supplied label but does not aggregate child metadata.\n\n## Handle Operation Failures\n\n```ts\nimport { LedgerCancelledError, LedgerExecutionError, LedgerRollbackError } from '@vielzeug/ledger';\n\ntry {\n await ledger.undo();\n} catch (error) {\n if (error instanceof LedgerCancelledError) {\n // Expected cancellation.\n } else if (error instanceof LedgerRollbackError) {\n showUndoError(error.cause);\n } else if (error instanceof LedgerExecutionError) {\n showApplyError(error.cause);\n } else {\n throw error;\n }\n}\n```\n\nA failed `do()` is not recorded and is not automatically reverted. A failed `undo()` remains in undo history; a failed `redo()` remains in redo history, allowing retry after the underlying problem is corrected.\n\n## Cancel Work\n\nPass a signal per operation. Queued cancellation prevents user code from starting. Active work receives a combined signal and must stop cooperatively.\n\n```ts\nconst controller = new AbortController();\nconst operation = ledger.do(\n {\n apply: ({ signal }) => saveDraft(nextDraft, { signal }),\n revert: ({ signal }) => saveDraft(previousDraft, { signal }),\n },\n { signal: controller.signal },\n);\n\ncontroller.abort();\nawait operation.catch(handleHistoryFailure);\n```\n\nIf active user code ignores cancellation and finishes, Ledger rejects with `LedgerCancelledError` and does not record or move history. It does not compensate partial effects automatically, so command implementations must check or forward `context.signal` before committing changes.\n\n## Record Externally Executed Work\n\nWhen a synchronous store owns its writes, execute first and record the reversible entry afterwards: `undo()` calls the recorded `revert`, `redo()` calls the recorded `apply`, so `apply` must be able to re-apply the effect.\n\n```ts\nconst previous = item.name;\n\nitem.name = next; // the store's own synchronous write\nledger.record({\n apply: () => {\n item.name = next;\n },\n label: 'rename item',\n revert: () => {\n item.name = previous;\n },\n});\n```\n\nRecording is synchronous and shares `do()`'s bookkeeping: it clears redo history and evicts the oldest entry beyond `maxHistory`.\n\n## Limit and Clear History\n\n`maxHistory` defaults to `100` and accepts non-negative safe integers. Successful commands beyond the cap evict the oldest undo entries. `0` executes commands without retaining undo or redo history.\n\n```ts\nconst ledger = createLedger({ maxHistory: 30 });\nawait ledger.clear();\n```\n\n`clear()` is serialized behind earlier work and clears both history arrays without reverting commands.\n\n## Drain and Dispose\n\n`whenIdle()` resolves when both `queued` and `running` reach zero. It does not cancel work.\n\n```ts\nconst operation = ledger.do(command);\nconst idle = ledger.whenIdle();\n\nledger.dispose();\nawait operation.catch(handleHistoryFailure);\nawait idle;\n```\n\nDisposal is permanent and idempotent. It clears history, aborts active contexts, rejects queued work with `LedgerDisposedError`, and rejects pending `whenIdle()` waiters. Read `disposed` to detect it. Active operations settle cooperatively; `whenIdle()` waits for them. Work that never settles can keep `whenIdle()` pending.\n\n## Framework Integration\n\nKeep one ledger per owning scope and adapt its structural readable through the framework's subscription API.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useMemo, useSyncExternalStore } from 'react';\nimport { createLedger } from '@vielzeug/ledger';\n\nexport function UndoStatus() {\n const ledger = useMemo(() => createLedger(), []);\n const state = useSyncExternalStore(\n (notify) => ledger.state.subscribe(notify),\n () => ledger.state.getSnapshot(),\n () => ledger.state.getSnapshot(),\n );\n\n useEffect(() => () => ledger.dispose(), [ledger]);\n return (\n <span>\n {state.undo.length} undo / {state.redo.length} redo\n </span>\n );\n}\n```\n\n```ts [Vue 3]\nimport { onUnmounted, shallowRef } from 'vue';\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger();\nconst state = shallowRef(ledger.state.getSnapshot());\nconst stop = ledger.state.subscribe(() => {\n state.value = ledger.state.getSnapshot();\n});\n\nonUnmounted(() => {\n stop();\n ledger.dispose();\n});\n```\n\n```ts [Ripple]\nimport { signal } from '@vielzeug/ripple';\nimport { createLedger } from '@vielzeug/ledger';\n\nconst ledger = createLedger();\nconst state = signal(ledger.state.getSnapshot());\nconst stop = ledger.state.subscribe(() => {\n state.value = ledger.state.getSnapshot();\n});\n\nfunction dispose(): void {\n stop();\n ledger.dispose();\n}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nUse Keymap to route keyboard shortcuts into `undo()` and `redo()`. Project `ledger.state` into Ripple when reactive derivations are needed. Persist application snapshots with Vault; Ledger history itself is transient.\n\n## Best Practices\n\n- Capture previous and next values before submitting a command.\n- Keep irreversible effects outside Ledger commands.\n- Forward or check `context.signal` in asynchronous command work.\n- Catch every operation promise at the application boundary.\n- Read one `state` snapshot per render.\n- Keep state subscribers synchronous and handle failures through the application's global error boundary.\n- Use `whenIdle()` before releasing owners that require a drain boundary.\n- Dispose each owner-scoped ledger.\n",
|
|
7
|
-
"examples": "---\ntitle: 'Ledger: Examples'\ndescription: Recipes for reversible editor and form history with Ledger.\n---\n\n## Examples\n\n- [Text Editor History](./examples/text-editor.md)\n- [Form History](./examples/form-history.md)\n"
|
|
7
|
+
"examples": "---\ntitle: 'Ledger: Examples'\ndescription: Recipes for reversible editor and form history with Ledger.\n---\n\n## Examples\n\n- [Text Editor History](./examples/text-editor.md)\n- [JSON Delta History](./examples/json-delta-history.md)\n- [Form History](./examples/form-history.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
|
10
10
|
{
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"apiSource": "export { catalogKeys } from './catalog';\nexport {\n LinguaDisposedError,\n LinguaError,\n LinguaInvalidCatalogError,\n LinguaInvalidLocaleError,\n LinguaInvalidPluralCountError,\n LinguaMissingCatalogError,\n LinguaMissingKeyError,\n LinguaMissingValueError,\n} from './errors';\nexport { createI18n, type I18n } from './i18n';\nexport { createTranslator, type Translator } from './translator';\nexport type {\n Catalog,\n CatalogNode,\n Catalogs,\n I18nOptions,\n Locale,\n MessageKey,\n MissingHandler,\n MissingInfo,\n MissingStrategy,\n PluralCategory,\n PluralKey,\n PluralMessage,\n PluralOptions,\n SerializedI18n,\n SubscribeOptions,\n TextKey,\n TranslateOptions,\n TranslatorOptions,\n Values,\n} from './types';\n",
|
|
3
3
|
"docs": {
|
|
4
4
|
"index": "---\ntitle: 'Lingua: Explicit localization for TypeScript'\ndescription: Framework-neutral locale catalogs, typed translations, and explicit plural messages.\npackage: lingua\ncategory: i18n\nkeywords: [internationalization, translations, pluralization, locale, i18n, catalog-loading]\nrelated: [ripple, wayfinder, courier]\nexports:\n [\n createI18n,\n createTranslator,\n LinguaError,\n LinguaDisposedError,\n LinguaInvalidCatalogError,\n LinguaInvalidLocaleError,\n LinguaInvalidPluralCountError,\n LinguaMissingCatalogError,\n LinguaMissingKeyError,\n LinguaMissingValueError,\n ]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"lingua\" />\n\n## Why Lingua?\n\nLingua separates immutable translation from mutable locale state. Use `createTranslator` for one fixed-locale catalog, or `createI18n` when locale changes at runtime.\n\n```ts\n// Before\nconst message = catalogs[locale]?.inbox?.[count === 1 ? 'one' : 'other'] ?? 'inbox';\n\n// After\nconst output = i18n.translate('inbox', { count });\n```\n\n| Feature | Lingua | i18next | FormatJS |\n| ------------------------------- | -------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"lingua\" type=\"size\" /> | Varies by selected modules | Varies by selected modules |\n| Zero runtime dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> |\n| Explicit plural catalog nodes | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Convention/config dependent | ICU-message dependent |\n| Static and lazy locale catalogs | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Plugin/config dependent | Application-defined |\n| Immutable locale snapshots | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Application-defined | Application-defined |\n\n<div class=\"decision-callout\">\n\n**Use Lingua when** you need a compact TypeScript runtime with explicit catalog structure, deterministic fallback, and framework-neutral subscriptions.\n\n**Consider i18next or FormatJS when** you need their plugin ecosystems, message extraction pipelines, or framework-specific integrations.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/lingua\n```\n\n```sh [npm]\nnpm install @vielzeug/lingua\n```\n\n```sh [yarn]\nyarn add @vielzeug/lingua\n```\n\n:::\n\n## Quick Start\n\nCreate an i18n instance with an eager default catalog and a loader for other locales.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst en = { inbox: { plural: { one: 'One message', other: '{count} messages' } } };\nconst i18n = createI18n({\n catalogs: { en },\n locale: 'en',\n loadCatalog: (locale) => import(`./locales/${locale}.ts`).then((m) => m.default),\n});\n\ntry {\n console.log(i18n.translate('inbox', { count: 3 }));\n await i18n.setLocale('de');\n console.log(i18n.translate('inbox', { count: 1 }));\n} finally {\n i18n.dispose();\n}\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createTranslator()` compiles one immutable fixed-locale catalog.\n- `createI18n()` manages eager catalogs, locale changes, and optional lazy loading.\n- `translate()` renders text and plural messages through explicit catalog nodes.\n- `load()` deduplicates loading and resolves the active locale plus configured fallbacks.\n- `getSnapshot()` and `subscribe()` expose a stable locale snapshot for framework stores.\n- `serialize()` transfers resolved SSR catalogs for client hydration.\n- `missing: 'throw' | 'key' | handler` controls failure behaviour.\n- `validateCatalog()` remains an isolated subpath tool.\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- [Ripple](../ripple/index.md) adapts Lingua snapshots into reactive application state.\n- [Courier](../courier/index.md) can fetch locale catalogs before passing them to Lingua loaders.\n- [Wayfinder](../wayfinder/index.md) can drive locale selection from route state.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Lingua: API Reference'\ndescription: Complete API reference for @vielzeug/lingua.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ---------------------- | ------------------------------------------------------------ | -------------- | ------------------------------------------------------------------------------------------- |\n| `createTranslator()` | Compile one immutable locale catalog | Sync | No fallback locales |\n| `createI18n()` | Create mutable locale and catalog store | Sync | Provide eager catalogs, a loader, or both |\n| `createFormatter()` | Create a cached Intl facade from `/format` | Sync | Pass a locale getter for dynamic locale changes |\n| `createReactiveI18n()` | Mirror an i18n instance into ripple readables from `/ripple` | Sync | Optional `@vielzeug/ripple` peer; import from subpath |\n| `catalogKeys()` | Enumerate message keys as dotted paths | Sync | Takes a catalog (or subtree) only; for an i18n instance pass `state.catalogs[state.locale]` |\n| `validateCatalog()` | Check explicit plural forms from `/validate` | Sync | Import from subpath |\n| `compareCatalogs()` | Compare key parity across locales from `/validate` | Sync | First locale is the base; import from subpath |\n| `LinguaError` | Base class for Lingua errors | Sync | Use `instanceof LinguaError` for broad narrowing |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --------------------------- | ------------------------------------------------------------------------------------------- |\n| `@vielzeug/lingua` | Translation factories, state types, and Lingua errors |\n| `@vielzeug/lingua/format` | Standalone cached Intl formatter factory |\n| `@vielzeug/lingua/ripple` | `createReactiveI18n()`: reactive locale/translate bridge (optional `@vielzeug/ripple` peer) |\n| `@vielzeug/lingua/validate` | `validateCatalog()`, `compareCatalogs()`, and `ValidationIssue` |\n\n## Translation Factories\n\n### createTranslator\n\n```ts\nfunction createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C>;\n```\n\nCompiles one catalog and returns an immutable fixed-locale translator. Locale defaults to `en` and controls plural selection and diagnostics.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | --------------------------------------------------------- |\n| `catalog` | `C` | One catalog containing only messages and grouping objects |\n| `options` | `TranslatorOptions` | Locale and missing-message strategy |\n\n**Returns:** `Translator<C>`.\n\n**Example:**\n\n```ts\nimport { createTranslator } from '@vielzeug/lingua';\n\nconst translator = createTranslator({ save: 'Enregistrer' }, { locale: 'fr' });\n\ntranslator.translate('save');\n```\n\n| Method | Signature | Returns |\n| ----------- | -------------------------------------------------------------------- | ---------------------- |\n| `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })` | Rendered string |\n| `locale` | `Locale` | Resolved active locale |\n\n---\n\n### createI18n\n\n```ts\nfunction createI18n<C extends Catalog>(options: I18nOptions<C>): I18n<C>;\n```\n\nCreates the catalog store, current locale state, and the active translator.\n\n| Parameter | Type | Description |\n| --------------------- | ----------------------------- | ------------------------------------------------ |\n| `options.catalogs` | `Catalogs<C>` | Eager locale catalogs |\n| `options.locale` | `Locale` | Initial locale; defaults to `en` |\n| `options.loadCatalog` | `(locale) => Promise<C> \\| C` | Loader for catalogs not supplied eagerly |\n| `options.fallback` | `Locale \\| readonly Locale[]` | Fallback locales loaded with the selected locale |\n| `options.missing` | `MissingStrategy` | Missing-key/value strategy |\n\nProvide at least one of `catalogs` or `loadCatalog`; you may combine eager `catalogs` with `loadCatalog` for later locales.\n\n**Returns:** `I18n<C>`, with every `Translator<C>` method plus lifecycle methods.\n\n**Example:**\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { title: 'Home' } },\n locale: 'en',\n});\ni18n.translate('title');\n```\n\n| Method or property | Signature | Returns |\n| ------------------ | ------------------------------------- | -------------------------------------------------------------- |\n| `translate` | Translator method | Rendered string |\n| `load` | `({ locale? })` | `Promise<void>` after the locale and configured fallbacks load |\n| `setLocale` | `(locale)` | `Promise<void>` after an atomic loaded-locale commit |\n| `isLoaded` | `({ locale? })` | `boolean` |\n| `getSnapshot` | `()` | Current locale, referentially stable until it changes |\n| `subscribe` | `(listener, { immediate?, signal? })` | Unsubscribe function; listener receives the new locale |\n| `serialize` | `()` | Loader-free `SerializedI18n<C>` for SSR transfer |\n| `dispose` | `()` | `void` |\n| `locale` | `Locale` | Current canonical locale |\n| `disposed` | `boolean` | Disposal state |\n| `disposalSignal` | `AbortSignal` | Aborts on disposal |\n| `[Symbol.dispose]` | `()` | Delegates to `dispose()` |\n\n---\n\n## Reactive bridge (`@vielzeug/lingua/ripple`)\n\n### createReactiveI18n\n\n```ts\nfunction createReactiveI18n<C extends Catalog>(i18n: I18n<C>): ReactiveI18n<C>;\n```\n\nBridges a lingua instance into `@vielzeug/ripple` so translated strings are reactive. `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()` computes once and never re-runs, since it registers no tracked dependency. The bridge's `translate` first reads the reactive `locale` readable, so any binding built on it re-evaluates the instant `setLocale()` resolves.\n\n`@vielzeug/ripple` is an optional peer dependency: install it only when you use this subpath.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\nimport { createReactiveI18n } from '@vielzeug/lingua/ripple';\nimport { computed } from '@vielzeug/ripple';\n\nconst reactive = createReactiveI18n(createI18n({ catalogs, locale: 'en' }));\n\nconst heading = computed(() => reactive.translate('title')); // re-computes on setLocale()\nawait reactive.i18n.setLocale('fr');\n```\n\n| Property or method | Signature | Returns |\n| ------------------ | ------------------ | ------------------------------------------------------------------------------- |\n| `i18n` | `I18n<C>` | The underlying instance for imperative work (`setLocale`, `load`, disposal) |\n| `locale` | `Readable<Locale>` | Reactive locale: reading it inside a computed/template registers the dependency |\n| `translate` | `(key, options?)` | Rendered string; re-evaluates whenever the locale changes |\n\n---\n\n## Catalog Utilities\n\n### catalogKeys\n\n```ts\nfunction catalogKeys<C extends Catalog>(catalog: C): ReadonlyArray<MessageKey<C>>;\n```\n\nEnumerates every message key as a dotted path. Traverses nested grouping objects and explicit `{ plural: ... }` messages, producing the same paths that `TextKey<C>` represents at the type level. Pass any catalog object or subtree; for an `I18n` instance, read its current locale catalog first.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | ----------------------------------------- |\n| `catalog` | `C extends Catalog` | Raw catalog object or any catalog subtree |\n\n**Returns:** `ReadonlyArray<MessageKey<C>>`: dotted paths to every text and plural message.\n\n```ts\nimport { catalogKeys, createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { nav: { home: 'Home', settings: 'Settings' } } },\n locale: 'en',\n});\n\nconst state = i18n.serialize();\nconst allKeys = catalogKeys(state.catalogs[state.locale]); // ['nav.home', 'nav.settings']\nconst navKeys = catalogKeys(state.catalogs.en.nav); // ['home', 'settings']\n```\n\n---\n\n## Intl formatting\n\n### createFormatter\n\n```ts\nimport { createFormatter } from '@vielzeug/lingua/format';\n\nconst format = createFormatter(() => i18n.locale);\nformat.number(1_234.5);\nformat.currency(19.99, 'USD');\nformat.date(new Date(), { dateStyle: 'medium' });\n```\n\nThe formatter caches bounded `Intl` instances and resolves a locale getter for every call.\n\n## Validation\n\n### validateCatalog\n\n```ts\nfunction validateCatalog(catalog: Catalog, locale: Locale): ValidationIssue[];\n```\n\nValidates explicit plural messages against locale plural categories after catalog structural validation.\n\n| Parameter | Type | Description |\n| --------- | --------- | ---------------------------- |\n| `catalog` | `Catalog` | Explicit catalog to validate |\n| `locale` | `Locale` | BCP 47 locale tag |\n\n**Returns:** `ValidationIssue[]`.\n\n**Example:**\n\n```ts\nimport { validateCatalog } from '@vielzeug/lingua/validate';\n\nvalidateCatalog({ inbox: { plural: { one: 'One message' } } }, 'en');\n```\n\n### compareCatalogs\n\n```ts\nfunction compareCatalogs<C extends Catalog>(catalogs: Catalogs<C>): CatalogComparison;\n```\n\nCompares key sets across locales. First locale is the base: reports keys missing in each target and keys present in targets but absent from base. Validates each catalog structurally.\n\n| Parameter | Type | Description |\n| ---------- | ------------- | -------------------------------- |\n| `catalogs` | `Catalogs<C>` | Locale-keyed catalogs to compare |\n\n**Returns:** `CatalogComparison` with `missing` and `extra` arrays.\n\n```ts\nimport { compareCatalogs } from '@vielzeug/lingua/validate';\n\nconst result = compareCatalogs({\n en: { greeting: 'Hello', farewell: 'Goodbye' },\n de: { greeting: 'Hallo' },\n});\n// { missing: [{ key: 'farewell', locale: 'de' }], extra: [] }\n```\n\n## Types\n\n```ts\ntype Locale = string;\ntype PluralCategory = Intl.LDMLPluralRule;\ntype PluralMessage = { readonly plural: Partial<Record<PluralCategory, string>> };\ntype CatalogNode = Catalog | PluralMessage | string;\ntype Catalog = { readonly [key: string]: CatalogNode };\ntype Catalogs<C extends Catalog = Catalog> = Record<Locale, C>;\n\ntype MissingInfo = { readonly key: string; readonly locale: Locale; readonly name?: string };\ntype MissingHandler = (info: MissingInfo) => string;\ntype MissingStrategy = 'throw' | 'key' | MissingHandler;\n\ntype TranslatorOptions = { readonly locale?: Locale; readonly missing?: MissingStrategy };\n\ntype I18nOptions<C extends Catalog = Catalog> = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n} & (\n | { readonly catalogs: Catalogs<C>; readonly loadCatalog?: CatalogLoader<C> }\n | { readonly catalogs?: Catalogs<C>; readonly loadCatalog: CatalogLoader<C> }\n);\n\ntype CatalogLoader<C extends Catalog> = (locale: Locale) => Promise<C> | C;\n\ntype SerializedI18n<C extends Catalog = Catalog> = {\n readonly catalogs: Catalogs<C>;\n readonly locale: Locale;\n};\n\ntype I18n<C extends Catalog = Catalog> = Translator<C> & {\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n getSnapshot(): Locale;\n isLoaded(options?: { locale?: Locale }): boolean;\n load(options?: { locale?: Locale }): Promise<void>;\n serialize(): SerializedI18n<C>;\n setLocale(locale: Locale): Promise<void>;\n subscribe(listener: (locale: Locale) => void, options?: SubscribeOptions): () => void;\n [Symbol.dispose](): void;\n};\n\ntype Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n};\n```\n\n```ts\ntype Values = Record<string, unknown>;\ntype TranslateOptions = { values?: Values };\ntype PluralOptions = TranslateOptions & { count: number; ordinal?: boolean };\ntype SubscribeOptions = { immediate?: boolean; signal?: AbortSignal };\n\ntype CatalogPaths<\n C,\n Leaf,\n Prefix extends string = '',\n Depth extends readonly unknown[] = readonly [1, 1, 1, 1, 1, 1],\n> = Depth extends readonly [unknown, ...infer Rest]\n ? C extends Leaf\n ? Prefix\n : C extends PluralMessage\n ? never\n : C extends Catalog\n ? {\n [K in string & keyof C]: CatalogPaths<C[K], Leaf, Prefix extends '' ? K : `${Prefix}.${K}`, Rest>;\n }[string & keyof C]\n : never\n : never;\n\ntype MessageKey<C> = CatalogPaths<C, string | PluralMessage>;\ntype TextKey<C> = CatalogPaths<C, string>;\ntype PluralKey<C> = CatalogPaths<C, PluralMessage>;\n\ntype ValidationIssue = { key: string; locale: Locale; missing: Intl.LDMLPluralRule };\ntype CatalogComparison = {\n readonly missing: ReadonlyArray<{ key: string; locale: Locale }>;\n readonly extra: ReadonlyArray<{ key: string; locale: Locale }>;\n};\n```\n\n## Errors\n\n| Error | Trigger |\n| ------------------------------- | ------------------------------------------------------- |\n| `LinguaDisposedError` | State mutation or subscription after `dispose()` |\n| `LinguaInvalidCatalogError` | Invalid catalog node or reserved key |\n| `LinguaInvalidLocaleError` | Invalid BCP 47 locale tag |\n| `LinguaInvalidPluralCountError` | Non-finite plural count |\n| `LinguaMissingCatalogError` | No `loadCatalog` function or catalog source unavailable |\n| `LinguaMissingKeyError` | Missing translation key when `missing: 'throw'` |\n| `LinguaMissingValueError` | Missing interpolation value when `missing: 'throw'` |\n",
|
|
5
|
+
"api": "---\ntitle: 'Lingua: API Reference'\ndescription: Complete API reference for @vielzeug/lingua.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ---------------------- | ------------------------------------------------------------ | -------------- | ------------------------------------------------------------------------------------------- |\n| `createTranslator()` | Compile one immutable locale catalog | Sync | No fallback locales |\n| `createI18n()` | Create mutable locale and catalog store | Sync | Provide eager catalogs, a loader, or both |\n| `createFormatter()` | Create a cached Intl facade from `/format` | Sync | Pass a locale getter for dynamic locale changes |\n| `createReactiveI18n()` | Mirror an i18n instance into ripple readables from `/ripple` | Sync | Optional `@vielzeug/ripple` peer; import from subpath |\n| `catalogKeys()` | Enumerate message keys as dotted paths | Sync | Takes a catalog (or subtree) only; for an i18n instance pass `state.catalogs[state.locale]` |\n| `validateCatalog()` | Check explicit plural forms from `/validate` | Sync | Import from subpath |\n| `compareCatalogs()` | Compare key parity across locales from `/validate` | Sync | First locale is the base; import from subpath |\n| `LinguaError` | Base class for Lingua errors | Sync | Use `instanceof LinguaError` for broad narrowing |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --------------------------- | ------------------------------------------------------------------------------------------- |\n| `@vielzeug/lingua` | Translation factories, state types, and Lingua errors |\n| `@vielzeug/lingua/format` | Standalone cached Intl formatter factory |\n| `@vielzeug/lingua/ripple` | `createReactiveI18n()`: reactive locale/translate bridge (optional `@vielzeug/ripple` peer) |\n| `@vielzeug/lingua/validate` | `validateCatalog()`, `compareCatalogs()`, and `ValidationIssue` |\n\n## Translation Factories\n\n### createTranslator\n\n```ts\nfunction createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C>;\n```\n\nCompiles one catalog and returns an immutable fixed-locale translator. Locale defaults to `en` and controls plural selection and diagnostics.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | --------------------------------------------------------- |\n| `catalog` | `C` | One catalog containing only messages and grouping objects |\n| `options` | `TranslatorOptions` | Locale and missing-message strategy |\n\n**Returns:** `Translator<C>`.\n\n**Example:**\n\n```ts\nimport { createTranslator } from '@vielzeug/lingua';\n\nconst translator = createTranslator({ save: 'Enregistrer' }, { locale: 'fr' });\n\ntranslator.translate('save');\n```\n\n| Method | Signature | Returns |\n| ------------------ | -------------------------------------------------------------------- | ---------------------- |\n| `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })` | Rendered string |\n| `translateUnkeyed` | `(key: string, options?)` | Rendered string |\n| `locale` | `Locale` | Resolved active locale |\n\n---\n\n### createI18n\n\n```ts\nfunction createI18n<C extends Catalog>(options: I18nOptions<C>): I18n<C>;\n```\n\nCreates the catalog store, current locale state, and the active translator.\n\n| Parameter | Type | Description |\n| --------------------- | ----------------------------- | ------------------------------------------------ |\n| `options.catalogs` | `Catalogs<C>` | Eager locale catalogs |\n| `options.locale` | `Locale` | Initial locale; defaults to `en` |\n| `options.loadCatalog` | `(locale) => Promise<C> \\| C` | Loader for catalogs not supplied eagerly |\n| `options.fallback` | `Locale \\| readonly Locale[]` | Fallback locales loaded with the selected locale |\n| `options.missing` | `MissingStrategy` | Missing-key/value strategy |\n\nProvide at least one of `catalogs` or `loadCatalog`; you may combine eager `catalogs` with `loadCatalog` for later locales.\n\n**Returns:** `I18n<C>`, with every `Translator<C>` method plus lifecycle methods.\n\n**Example:**\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { title: 'Home' } },\n locale: 'en',\n});\ni18n.translate('title');\n```\n\n| Method or property | Signature | Returns |\n| ------------------ | ------------------------------------- | -------------------------------------------------------------- |\n| `translate` | Translator method | Rendered string |\n| `translateUnkeyed` | Translator method | Rendered string for a runtime key outside the typed key set |\n| `load` | `({ locale? })` | `Promise<void>` after the locale and configured fallbacks load |\n| `setLocale` | `(locale)` | `Promise<void>` after an atomic loaded-locale commit |\n| `isLoaded` | `({ locale? })` | `boolean` |\n| `getSnapshot` | `()` | Current locale, referentially stable until it changes |\n| `subscribe` | `(listener, { immediate?, signal? })` | Unsubscribe function; listener receives the new locale |\n| `serialize` | `()` | Loader-free `SerializedI18n<C>` for SSR transfer |\n| `dispose` | `()` | `void` |\n| `locale` | `Locale` | Current canonical locale |\n| `disposed` | `boolean` | Disposal state |\n| `disposalSignal` | `AbortSignal` | Aborts on disposal |\n| `[Symbol.dispose]` | `()` | Delegates to `dispose()` |\n\n---\n\n## Reactive bridge (`@vielzeug/lingua/ripple`)\n\n### createReactiveI18n\n\n```ts\nfunction createReactiveI18n<C extends Catalog>(i18n: I18n<C>): ReactiveI18n<C>;\n```\n\nBridges a lingua instance into `@vielzeug/ripple` so translated strings are reactive. `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()` computes once and never re-runs, since it registers no tracked dependency. The bridge's `translate` and `translateUnkeyed` first read the reactive `locale` readable, so any binding built on them re-evaluates the instant `setLocale()` resolves. For runtime-assembled keys inside reactive bindings use the bridge's `translateUnkeyed`: calling `i18n.translateUnkeyed` directly skips the reactive locale and caches the first result.\n\n`@vielzeug/ripple` is an optional peer dependency: install it only when you use this subpath.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\nimport { createReactiveI18n } from '@vielzeug/lingua/ripple';\nimport { computed } from '@vielzeug/ripple';\n\nconst reactive = createReactiveI18n(createI18n({ catalogs, locale: 'en' }));\n\nconst heading = computed(() => reactive.translate('title')); // re-computes on setLocale()\nawait reactive.i18n.setLocale('fr');\n```\n\n| Property or method | Signature | Returns |\n| ------------------ | ------------------ | ------------------------------------------------------------------------------- |\n| `i18n` | `I18n<C>` | The underlying instance for imperative work (`setLocale`, `load`, disposal) |\n| `locale` | `Readable<Locale>` | Reactive locale: reading it inside a computed/template registers the dependency |\n| `translate` | `(key, options?)` | Rendered string; re-evaluates whenever the locale changes |\n| `translateUnkeyed` | `(key, options?)` | Rendered string for a runtime key; re-evaluates whenever the locale changes |\n\n---\n\n## Catalog Utilities\n\n### catalogKeys\n\n```ts\nfunction catalogKeys<C extends Catalog>(catalog: C): ReadonlyArray<MessageKey<C>>;\n```\n\nEnumerates every message key as a dotted path. Traverses nested grouping objects and explicit `{ plural: ... }` messages, producing the same paths that `TextKey<C>` represents at the type level. Pass any catalog object or subtree; for an `I18n` instance, read its current locale catalog first.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | ----------------------------------------- |\n| `catalog` | `C extends Catalog` | Raw catalog object or any catalog subtree |\n\n**Returns:** `ReadonlyArray<MessageKey<C>>`: dotted paths to every text and plural message.\n\n```ts\nimport { catalogKeys, createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { nav: { home: 'Home', settings: 'Settings' } } },\n locale: 'en',\n});\n\nconst state = i18n.serialize();\nconst allKeys = catalogKeys(state.catalogs[state.locale]); // ['nav.home', 'nav.settings']\nconst navKeys = catalogKeys(state.catalogs.en.nav); // ['home', 'settings']\n```\n\n---\n\n## Intl formatting\n\n### createFormatter\n\n```ts\nimport { createFormatter } from '@vielzeug/lingua/format';\n\nconst format = createFormatter(() => i18n.locale);\nformat.number(1_234.5);\nformat.currency(19.99, 'USD');\nformat.date(new Date(), { dateStyle: 'medium' });\n```\n\nThe formatter caches bounded `Intl` instances and resolves a locale getter for every call.\n\n## Validation\n\n### validateCatalog\n\n```ts\nfunction validateCatalog(catalog: Catalog, locale: Locale): ValidationIssue[];\n```\n\nValidates explicit plural messages against locale plural categories after catalog structural validation.\n\n| Parameter | Type | Description |\n| --------- | --------- | ---------------------------- |\n| `catalog` | `Catalog` | Explicit catalog to validate |\n| `locale` | `Locale` | BCP 47 locale tag |\n\n**Returns:** `ValidationIssue[]`.\n\n**Example:**\n\n```ts\nimport { validateCatalog } from '@vielzeug/lingua/validate';\n\nvalidateCatalog({ inbox: { plural: { one: 'One message' } } }, 'en');\n```\n\n### compareCatalogs\n\n```ts\nfunction compareCatalogs<C extends Catalog>(catalogs: Catalogs<C>): CatalogComparison;\n```\n\nCompares key sets across locales. First locale is the base: reports keys missing in each target and keys present in targets but absent from base. Validates each catalog structurally.\n\n| Parameter | Type | Description |\n| ---------- | ------------- | -------------------------------- |\n| `catalogs` | `Catalogs<C>` | Locale-keyed catalogs to compare |\n\n**Returns:** `CatalogComparison` with `missing` and `extra` arrays.\n\n```ts\nimport { compareCatalogs } from '@vielzeug/lingua/validate';\n\nconst result = compareCatalogs({\n en: { greeting: 'Hello', farewell: 'Goodbye' },\n de: { greeting: 'Hallo' },\n});\n// { missing: [{ key: 'farewell', locale: 'de' }], extra: [] }\n```\n\n## Types\n\n```ts\ntype Locale = string;\ntype PluralCategory = Intl.LDMLPluralRule;\ntype PluralMessage = { readonly plural: Partial<Record<PluralCategory, string>> };\ntype CatalogNode = Catalog | PluralMessage | string;\ntype Catalog = { readonly [key: string]: CatalogNode };\ntype Catalogs<C extends Catalog = Catalog> = Record<Locale, C>;\n\ntype MissingInfo = { readonly key: string; readonly locale: Locale; readonly name?: string };\ntype MissingHandler = (info: MissingInfo) => string;\ntype MissingStrategy = 'throw' | 'key' | MissingHandler;\n\ntype TranslatorOptions = { readonly locale?: Locale; readonly missing?: MissingStrategy };\n\ntype I18nOptions<C extends Catalog = Catalog> = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n} & (\n | { readonly catalogs: Catalogs<C>; readonly loadCatalog?: CatalogLoader<C> }\n | { readonly catalogs?: Catalogs<C>; readonly loadCatalog: CatalogLoader<C> }\n);\n\ntype CatalogLoader<C extends Catalog> = (locale: Locale) => Promise<C> | C;\n\ntype SerializedI18n<C extends Catalog = Catalog> = {\n readonly catalogs: Catalogs<C>;\n readonly locale: Locale;\n};\n\ntype I18n<C extends Catalog = Catalog> = Translator<C> & {\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n getSnapshot(): Locale;\n isLoaded(options?: { locale?: Locale }): boolean;\n load(options?: { locale?: Locale }): Promise<void>;\n serialize(): SerializedI18n<C>;\n setLocale(locale: Locale): Promise<void>;\n subscribe(listener: (locale: Locale) => void, options?: SubscribeOptions): () => void;\n [Symbol.dispose](): void;\n};\n\ntype Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n translateUnkeyed(key: string, options?: TranslateOptions | PluralOptions): string;\n};\n```\n\n```ts\ntype Values = Record<string, unknown>;\ntype TranslateOptions = { values?: Values };\ntype PluralOptions = TranslateOptions & { count: number; ordinal?: boolean };\ntype SubscribeOptions = { immediate?: boolean; signal?: AbortSignal };\n\ntype CatalogPaths<\n C,\n Leaf,\n Prefix extends string = '',\n Depth extends readonly unknown[] = readonly [1, 1, 1, 1, 1, 1],\n> = Depth extends readonly [unknown, ...infer Rest]\n ? C extends Leaf\n ? Prefix\n : C extends PluralMessage\n ? never\n : C extends Catalog\n ? {\n [K in string & keyof C]: CatalogPaths<C[K], Leaf, Prefix extends '' ? K : `${Prefix}.${K}`, Rest>;\n }[string & keyof C]\n : never\n : never;\n\ntype MessageKey<C> = CatalogPaths<C, string | PluralMessage>;\ntype TextKey<C> = CatalogPaths<C, string>;\ntype PluralKey<C> = CatalogPaths<C, PluralMessage>;\n\ntype ValidationIssue = { key: string; locale: Locale; missing: Intl.LDMLPluralRule };\ntype CatalogComparison = {\n readonly missing: ReadonlyArray<{ key: string; locale: Locale }>;\n readonly extra: ReadonlyArray<{ key: string; locale: Locale }>;\n};\n```\n\n## Errors\n\n| Error | Trigger |\n| ------------------------------- | ------------------------------------------------------- |\n| `LinguaDisposedError` | State mutation or subscription after `dispose()` |\n| `LinguaInvalidCatalogError` | Invalid catalog node or reserved key |\n| `LinguaInvalidLocaleError` | Invalid BCP 47 locale tag |\n| `LinguaInvalidPluralCountError` | Non-finite plural count |\n| `LinguaMissingCatalogError` | No `loadCatalog` function or catalog source unavailable |\n| `LinguaMissingKeyError` | Missing translation key when `missing: 'throw'` |\n| `LinguaMissingValueError` | Missing interpolation value when `missing: 'throw'` |\n",
|
|
6
6
|
"usage": "---\ntitle: 'Lingua: Usage Guide'\ndescription: Translate explicit catalogs, load lazy locales, and connect locale snapshots to UI state.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate an i18n instance with eager locale catalogs. Strings are text messages; plural messages use `{ plural: ... }`.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: {\n en: {\n greeting: 'Hello, {name}!',\n inbox: { plural: { one: 'One message', other: '{count} messages' } },\n },\n },\n locale: 'en',\n});\n\nconsole.log(i18n.translate('greeting', { values: { name: 'Ada' } }));\nconsole.log(i18n.translate('inbox', { count: 3 }));\n```\n\nCall `dispose()` when the instance belongs to a temporary request, test, or route owner.\n\n## Define Explicit Catalogs\n\nUse nested objects only to group keys. A plural message always has `plural`, so regular objects containing `one` or `other` remain groups.\n\n```ts\nconst catalog = {\n account: {\n greeting: 'Hello, {name}!',\n unread: { plural: { one: 'One unread message', other: '{count} unread messages' } },\n },\n};\n```\n\nUse `{ values }` for text replacements. Pass `count` at top level for plural selection; Lingua injects it into selected template.\n\nCatalogs contain strings, grouping objects, and explicit `{ plural: ... }` messages only. Keep application data outside catalog, then translate display labels while constructing it.\n\n```ts\nimport { createTranslator } from '@vielzeug/lingua';\n\nconst messages = {\n status: { blocked: 'Blocked', done: 'Done', inProgress: 'In progress' },\n};\nconst statusDefinitions = [\n { labelKey: 'status.inProgress', value: 'in-progress' },\n { labelKey: 'status.blocked', value: 'blocked' },\n { labelKey: 'status.done', value: 'done' },\n] as const;\nconst translator = createTranslator(messages, { locale: 'en' });\nconst statusOptions = statusDefinitions.map(({ labelKey, value }) => ({\n label: translator.translate(labelKey),\n value,\n}));\n```\n\n## Missing Keys and Values\n\nMissing keys and values do not silently echo placeholders by default: Lingua warns in development and returns the key or `{name}`. Control failure behaviour with the `missing` option:\n\n| `missing` | Behaviour |\n| --------------------- | --------------------------------------------------------- |\n| `undefined` (default) | Warn in development; return key / `{name}` |\n| `'key'` | Return key / `{name}` silently |\n| `'throw'` | Throw `LinguaMissingKeyError` / `LinguaMissingValueError` |\n| `handler` | Call `({ key, locale, name? }) => string` |\n\n```ts\nconst translator = createTranslator(messages, { locale: 'en', missing: 'throw' });\n```\n\n## Enumerate Catalog Keys\n\nUse `catalogKeys()` to derive key arrays from the catalog itself instead of maintaining a parallel list that can go stale. It traverses nested grouping objects and explicit `{ plural: ... }` messages, returning the same dotted paths that `MessageKey<C>` represents at the type level.\n\nFor an `I18n` instance, read its current locale catalog first.\n\n```ts\nimport { catalogKeys, createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: {\n en: {\n greeting: 'Hello, {name}!',\n inbox: { plural: { one: 'One message', other: '{count} messages' } },\n nav: { home: 'Home', settings: 'Settings' },\n },\n },\n locale: 'en',\n});\n\nconst state = i18n.serialize();\nconst allKeys = catalogKeys(state.catalogs[state.locale]);\n// ['greeting', 'inbox', 'nav.home', 'nav.settings']\n```\n\nPass a raw catalog object to enumerate keys directly. Call `catalogKeys()` on a nested subtree to get exactly the keys in that group: no filtering, no casts.\n\n```ts\nimport { catalogKeys } from '@vielzeug/lingua';\n\nconst messages = {\n nav: { home: 'Home', settings: 'Settings' },\n} as const;\n\nconst allKeys = catalogKeys(messages);\n// ['nav.home', 'nav.settings']\n\nconst navKeys = catalogKeys(messages.nav);\n// ['home', 'settings']\n```\n\n## Use a Fixed-Locale Translator\n\nUse `createTranslator()` when one catalog and locale stay fixed for the translator's lifetime. It defaults locale to `en`; pass `locale` when plural rules or diagnostics need another locale. Lingua snapshots catalog messages during construction. Do not mutate source catalog objects afterward.\n\n```ts\nimport { createTranslator } from '@vielzeug/lingua';\n\nconst translator = createTranslator({ save: 'Enregistrer' }, { locale: 'fr' });\n\nconsole.log(translator.translate('save'));\n```\n\n## Load Catalogs and Switch Locales\n\nProvide eager catalogs for translations needed immediately and a `loadCatalog` function for other locales. `setLocale()` loads the selected locale and configured fallbacks before it commits the change.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { navigation: { settings: 'Settings' } } },\n fallback: 'en',\n locale: 'en',\n loadCatalog: (locale) => import(`./locales/${locale}.ts`).then((m) => m.default),\n});\n\nawait i18n.setLocale('fr');\nconsole.log(i18n.translate('navigation.settings'));\n```\n\nUse loader-only configuration when every locale is lazy, and call `load()` before the first translation. Concurrent loads for the same locale share work. A failed or superseded locale selection never changes the active locale.\n\n## Subscribe to Locale Changes\n\nSubscribe when UI state must change with the locale. Every callback receives the newly committed locale; translate through the instance to read current strings.\n\n```ts\nconst unsubscribe = i18n.subscribe(\n (locale) => {\n console.log(locale, i18n.translate('navigation.settings'));\n },\n { immediate: true },\n);\n\nunsubscribe();\n```\n\nPass `{ signal }` when an `AbortController` owns subscription lifetime.\n\n## SSR State\n\nSerialize resolved catalogs on the server and pass them back to `createI18n` on the client together with the serialized locale. `getSnapshot()` returns the current locale and stays referentially stable until the locale changes, so it works directly as a framework store snapshot.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst serverI18n = createI18n({\n catalogs: { en: { title: 'Server title' } },\n locale: 'en',\n});\n\nconst state = serverI18n.serialize();\nconst clientI18n = createI18n({ catalogs: state.catalogs, locale: state.locale });\n\nconsole.log(clientI18n.translate('title'));\nserverI18n.dispose();\nclientI18n.dispose();\n```\n\nThe serialized payload contains raw loaded catalogs and the active locale. It never contains loader functions. Pass an explicit `locale` only when the client should override the serialized locale.\n\n## Validation\n\nImport catalog validation from the dedicated subpath to keep translation state focused.\n\n```ts\nimport { compareCatalogs, validateCatalog } from '@vielzeug/lingua/validate';\n\nconst catalog = { inbox: { plural: { one: 'One message', other: '{count} messages' } } };\n\nconsole.log(validateCatalog(catalog, 'en'));\n```\n\nUse `compareCatalogs()` to catch missing or extra keys across locales: the most common i18n defect. First locale is the base.\n\n```ts\nimport { compareCatalogs } from '@vielzeug/lingua/validate';\n\nconst result = compareCatalogs({\n en: { greeting: 'Hello', farewell: 'Goodbye' },\n de: { greeting: 'Hallo' },\n});\n// { missing: [{ key: 'farewell', locale: 'de' }], extra: [] }\n```\n\n## Framework Integration\n\n`getSnapshot()` and `subscribe()` match external-store primitives directly: the snapshot is the locale string, referentially stable until the locale changes.\n\n::: code-group\n\n```ts [React]\nimport { useSyncExternalStore } from 'react';\n\nimport type { I18n } from '@vielzeug/lingua';\n\nexport function useLocale(i18n: I18n) {\n return useSyncExternalStore((onChange) => i18n.subscribe(onChange), i18n.getSnapshot, i18n.getSnapshot);\n}\n```\n\n```ts [Vue 3]\nimport { readonly, shallowRef } from 'vue';\n\nimport type { I18n } from '@vielzeug/lingua';\n\nexport function useLocale(i18n: I18n) {\n const locale = shallowRef(i18n.getSnapshot());\n\n i18n.subscribe((next) => {\n locale.value = next;\n });\n\n return readonly(locale);\n}\n```\n\n```ts [Svelte]\nimport { readable } from 'svelte/store';\n\nimport type { I18n } from '@vielzeug/lingua';\n\nexport function localeStore(i18n: I18n) {\n return readable(i18n.getSnapshot(), (set) => i18n.subscribe(set));\n}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nBridge Lingua's `getSnapshot()`/`subscribe()` pair directly when templates need reactive locale reads.\n\n```ts\nimport { createRipple } from '@vielzeug/ripple';\n\nconst ripple = createRipple();\nconst i18nState = ripple.fromSubscribable(i18n);\nexport const locale = ripple.computed(() => i18nState.value);\n\nexport const disposeLocaleBridge = () => ripple.dispose();\n```\n\nUse Courier loaders when locale catalogs come from HTTP rather than bundled modules; pass each loader to `loadCatalog`.\n\n## Best Practices\n\n- Define plural messages with `{ plural: ... }` and no sibling metadata.\n- Keep arrays and application metadata outside catalogs.\n- Treat source catalog objects as immutable after construction.\n- Provide eager catalogs for translations required during initial render.\n- Keep loader functions out of SSR payloads.\n- Dispose temporary instances after requests, tests, and route lifetimes.\n- Use `missing: 'throw'` in development to catch missing keys and values early.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Lingua: Examples'\ndescription: Focused examples for explicit catalogs and locale resources.\n---\n\n- [Static Translator](./examples/static-translator.md)\n- [Lazy Locale Catalog](./examples/feature-resources.md)\n- [SSR Hydration](./examples/ssr-hydration.md)\n"
|
|
8
8
|
},
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"apiSource": "// Public root surface of @vielzeug/patchwork. Every public export goes through this file.\nexport { PatchError, PatchPathError, PatchTestError } from './errors';\nexport { apply, diff, formatPointer, getIn, parsePointer, tryApply } from './patch';\nexport type {\n AddOperation,\n ApplyResult,\n CopyOperation,\n JsonObject,\n JsonPatch,\n JsonPointer,\n JsonValue,\n MoveOperation,\n PatchErrorInfo,\n PatchOperation,\n RemoveOperation,\n ReplaceOperation,\n TestOperation,\n} from './types';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Patchwork: RFC 6902 JSON Patch'\ndescription: 'RFC 6902 JSON Patch: structural diff, immutable apply, and guarded tryApply for sync protocols.'\npackage: patchwork\ncategory: utilities\nkeywords: [json-patch, rfc-6902, rfc-6901, json-pointer, diff, patch, sync, collaboration, immutable]\nexports: [apply, tryApply, diff, getIn, parsePointer, formatPointer]\nrelated: [tandem, forge, vault]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"patchwork\" />\n\n## Why Patchwork?\n\nOnce two places hold the same document, sending the whole document is the lazy answer that\nscales worst: bandwidth grows with document size, not with what changed, and blind writes\nclobber concurrent edits. JSON Patch is the wire format for the honest answer, and Patchwork\nimplements it with the two properties sync code actually needs: `apply` is **immutable with\nstructural sharing** (untouched subtrees keep their object identity, so React and every memo\nlayer work for free), and `diff` is **structural** (objects diff field-by-field, append-only\narrays stay one operation).\n\n```ts\nimport { apply, diff } from '@vielzeug/patchwork';\n\nconst patch = diff(before, after); // [{ op: 'replace', path: '/user/address/zip', value: '1010' }]\nconst next = apply(before, patch); // before untouched; next.user.address is new, next.user.orders === before.user.orders\n```\n\nA failed `test` operation is an ordinary answer in protocol code, not an exception:\n`tryApply` returns `{ ok: false, error: { index, path, reason } }`, so conflict handling is\ndata you can log and reply to. Zero runtime dependencies, spec-exact pointers (`~0`/`~1`\nescaping, `-` append), and a browser-safe build.\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/patchwork\n```\n\n```sh [npm]\nnpm install @vielzeug/patchwork\n```\n\n```sh [yarn]\nyarn add @vielzeug/patchwork\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { apply, diff, tryApply } from '@vielzeug/patchwork';\n\nconst doc = { items: ['a'], title: 'Cart' };\nconst patch = diff(doc, { items: ['a', 'b'], title: 'Wagen' });\n// [{ op: 'add', path: '/items/-', value: 'b' }, { op: 'replace', path: '/title', value: 'Wagen' }]\n\nconst next = apply(doc, patch); // doc untouched; next.title changed, next.items is a new array (it grew)\n\ntryApply(doc, [{ op: 'test', path: '/title', value: 'Other' }, ...patch]);\n// { ok: false, error: { index: 0, reason: 'test', path: '/title', message: … } }\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`apply`**: immutable RFC 6902 — all six operations, copy-on-write with structural sharing.\n- **`tryApply`**: the same engine as data; a failed `test` or bad pointer returns a structured rejection with the failing operation index.\n- **`diff`**: per-field object patches, suffix-
|
|
5
|
-
"api": "---\ntitle: 'Patchwork: API Reference'\ndescription: 'Public API of @vielzeug/patchwork: apply, tryApply, diff, pointer helpers, types, and errors.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --------------- | ------------------------------------------------------ | --------- | -------------------------------------------------------------- |\n| `apply` | Immutable RFC 6902 application with structural sharing | Sync | Throws on unresolvable pointer or failed `test` |\n| `tryApply` | Same engine, rejection as data | Sync | `error.index` is the failing operation, not the document size |\n| `diff` | Structural patch from `from` to `to` | Sync | Patch values reference `to`; clone if `to` keeps mutating |\n| `getIn` | Pointer read | Sync | Returns `undefined` both for missing and for non-JSON descents |\n| `parsePointer` | Pointer → decoded tokens | Sync | Throws `PatchPathError` on pointers not starting with `/` |\n| `formatPointer` | Tokens → pointer | Sync | `[]` formats to `''` (the whole document) |\n\n## Package Entry Point\n\n```ts\nimport { apply, diff, getIn, parsePointer, tryApply } from '@vielzeug/patchwork';\n```\n\n## Functions\n\n### apply\n\n```ts\nfunction apply<T extends JsonValue>(doc: T, patch: JsonPatch): T;\n```\n\nApplies every operation in order, copy-on-write: untouched subtrees keep their identity, and\na fully no-op patch returns `doc` itself. `add` inserts into arrays (index may equal the\nlength), sets/overwrites object members, and supports `-` append; `remove` and `replace`\nrequire the target to exist; `move` removes the `from` location then adds at `path`; `copy`\nadds a `structuredClone`; `test` compares structurally. Values from `add`/`copy` are cloned\ninto the document.\n\nThrows `PatchPathError` when a pointer does not resolve or an index is out of bounds, and\n`PatchTestError` when a `test` operation does not match.\n\n### tryApply\n\n```ts\nfunction tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult;\n```\n\nNever throws for patch failures: returns `{ ok: true, doc }` or\n`{ ok: false, error: { index, path, reason: 'path' | 'test', message } }`, where `path` is\
|
|
6
|
-
"usage": "---\ntitle: 'Patchwork: Usage Guide'\ndescription: 'How to use @vielzeug/patchwork: applying patches, conflicts with tryApply, structural diff, pointers, and the JSON domain.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nA patch is just an array of operations — build them by hand or compute them with `diff`, then\napply them immutably:\n\n```ts\nimport { apply, diff } from '@vielzeug/patchwork';\n\nconst cart = { items: [{ qty: 1, sku: 'a' }], meta: { rev: 7 }, total: '99' };\nconst edited = { items: [{ qty: 3, sku: 'a' }], meta: { rev: 8 }, total: '99' };\n\nconst patch = diff(cart, edited);\n// [{ op: 'replace', path: '/items/0/qty', value: 3 }, { op: 'replace', path: '/meta/rev', value: 8 }]\n\nconst next = apply(cart, patch);\nnext !== cart; // a new document\nnext.total === cart.total; // untouched subtrees keep their identity, so memoized\nnext.items !== cart.items; // selectors recompute only over the branches that changed\n```\n\n`apply` returns the same reference when a patch is a no-op (`[]`, or a `replace` with an\nequal value), so `Object.is(before, after)` is a reliable \"did anything change\" check.\n\n## Reading and Pointers\n\n```ts\nimport { formatPointer, getIn, parsePointer } from '@vielzeug/patchwork';\n\ngetIn(cart, '/items/0/sku'); // 'a'\ngetIn(cart, '/items/9'); // undefined — reads never throw\nparsePointer('/a~1b/c~0d'); // ['a/b', 'c~d']\nformatPointer(['a/b', 'c~d']); // '/a~1b/c~0d'\n```\n\n`null` is a value, not an absence: `getIn({ a: null }, '/a')` is `null`, while\n`getIn({ a: null }, '/b')` is `undefined`.\n\n## Conflicts as Data\n\nIn collaborative code a rejected patch is a normal message, not a crash. `apply` throws\n(`PatchPathError` for unresolvable pointers, `PatchTestError` for failed `test` operations);\n`tryApply` returns the same outcome as data:\n\n```ts\nimport { tryApply } from '@vielzeug/patchwork';\n\nconst result = tryApply(doc, [\n { op: 'test', path: '/rev', value: 41 }, // client last saw rev 41\n { op: 'replace', path: '/title', value: 'New' },\n]);\n\nif (!result.ok) {\n // { index: 0, path: '/rev', reason: 'test', message: … } — reply \"conflict, rebase on rev 42\"\n}\n```\n\nGuarding a write with a leading `test` is the whole optimistic-concurrency protocol: the\nserver `tryApply`s, and a failed test means someone else moved first.\n\n## What diff Emits\n\n- **Objects**: per-key `remove`s, `add`s, and recursive descent — changed fields cost one small operation each, regardless of document size.\n- **Arrays**: the common suffix
|
|
4
|
+
"index": "---\ntitle: 'Patchwork: RFC 6902 JSON Patch'\ndescription: 'RFC 6902 JSON Patch: structural diff, immutable apply, and guarded tryApply for sync protocols.'\npackage: patchwork\ncategory: utilities\nkeywords: [json-patch, rfc-6902, rfc-6901, json-pointer, diff, patch, sync, collaboration, immutable]\nexports: [apply, tryApply, diff, getIn, parsePointer, formatPointer]\nrelated: [tandem, forge, vault]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"patchwork\" />\n\n## Why Patchwork?\n\nOnce two places hold the same document, sending the whole document is the lazy answer that\nscales worst: bandwidth grows with document size, not with what changed, and blind writes\nclobber concurrent edits. JSON Patch is the wire format for the honest answer, and Patchwork\nimplements it with the two properties sync code actually needs: `apply` is **immutable with\nstructural sharing** (untouched subtrees keep their object identity, so React and every memo\nlayer work for free), and `diff` is **structural** (objects diff field-by-field, append-only\narrays stay one operation, and inserts land at exactly the right index).\n\n```ts\nimport { apply, diff } from '@vielzeug/patchwork';\n\nconst patch = diff(before, after); // [{ op: 'replace', path: '/user/address/zip', value: '1010' }]\nconst next = apply(before, patch); // before untouched; next.user.address is new, next.user.orders === before.user.orders\n```\n\nA failed `test` operation is an ordinary answer in protocol code, not an exception:\n`tryApply` returns `{ ok: false, error: { index, path, reason } }`, so conflict handling is\ndata you can log and reply to. Zero runtime dependencies, spec-exact pointers (`~0`/`~1`\nescaping, `-` append), and a browser-safe build.\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/patchwork\n```\n\n```sh [npm]\nnpm install @vielzeug/patchwork\n```\n\n```sh [yarn]\nyarn add @vielzeug/patchwork\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { apply, diff, tryApply } from '@vielzeug/patchwork';\n\nconst doc = { items: ['a'], title: 'Cart' };\nconst patch = diff(doc, { items: ['a', 'b'], title: 'Wagen' });\n// [{ op: 'add', path: '/items/-', value: 'b' }, { op: 'replace', path: '/title', value: 'Wagen' }]\n\nconst next = apply(doc, patch); // doc untouched; next.title changed, next.items is a new array (it grew)\n\ntryApply(doc, [{ op: 'test', path: '/title', value: 'Other' }, ...patch]);\n// { ok: false, error: { index: 0, reason: 'test', path: '/title', message: … } }\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`apply`**: immutable RFC 6902 — all six operations, copy-on-write with structural sharing.\n- **`tryApply`**: the same engine as data; a failed `test` or bad pointer returns a structured rejection with the failing operation index.\n- **`diff`**: per-field object patches, prefix/suffix-aligned arrays (appends, prepends, and middle inserts cost a single `add`), pointer-escaped keys.\n- **Pointer API**: `parsePointer`/`formatPointer` with `~0`/`~1` escaping and `getIn` for reads.\n- **Spec-exact edges**: `null` is a value not an absence, `replace` requires an existing target, array `add` inserts, `-` appends.\n- **Input isolation**: `add`/`copy` values are cloned in, so the caller's objects can never mutate a document afterwards.\n- **Hard JSON domain**: numbers, strings, booleans, null, arrays, objects — no functions, no prototypes, nothing to inherit.\n- **`@vielzeug/patchwork/merge`**: opt-in three-way merge — field-level reconciliation of diverged copies with `conflicts` as data.\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- [Tandem](/tandem/): transports patches over the wire in sync protocols.\n- [Forge](/forge/): tracks the dirty fields whose changes become patches.\n- [Vault](/vault/): schemas that define what a patchable document may contain.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: 'Patchwork: API Reference'\ndescription: 'Public API of @vielzeug/patchwork: apply, tryApply, diff, pointer helpers, types, and errors.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --------------- | ------------------------------------------------------ | --------- | -------------------------------------------------------------- |\n| `apply` | Immutable RFC 6902 application with structural sharing | Sync | Throws on unresolvable pointer or failed `test` |\n| `tryApply` | Same engine, rejection as data | Sync | `error.index` is the failing operation, not the document size |\n| `diff` | Structural patch from `from` to `to` | Sync | Patch values reference `to`; clone if `to` keeps mutating |\n| `getIn` | Pointer read | Sync | Returns `undefined` both for missing and for non-JSON descents |\n| `parsePointer` | Pointer → decoded tokens | Sync | Throws `PatchPathError` on pointers not starting with `/` |\n| `formatPointer` | Tokens → pointer | Sync | `[]` formats to `''` (the whole document) |\n\n## Package Entry Point\n\n```ts\nimport { apply, diff, getIn, parsePointer, tryApply } from '@vielzeug/patchwork';\nimport { merge } from '@vielzeug/patchwork/merge'; // three-way merge subpath\n```\n\n## Functions\n\n### apply\n\n```ts\nfunction apply<T extends JsonValue>(doc: T, patch: JsonPatch): T;\n```\n\nApplies every operation in order, copy-on-write: untouched subtrees keep their identity, and\na fully no-op patch returns `doc` itself. `add` inserts into arrays (index may equal the\nlength), sets/overwrites object members, and supports `-` append; `remove` and `replace`\nrequire the target to exist; `move` removes the `from` location then adds at `path`; `copy`\nadds a `structuredClone`; `test` compares structurally. Values from `add`/`copy` are cloned\ninto the document.\n\nThrows `PatchPathError` when a pointer does not resolve or an index is out of bounds, and\n`PatchTestError` when a `test` operation does not match.\n\n### tryApply\n\n```ts\nfunction tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult;\n```\n\nNever throws for patch failures: returns `{ ok: true, doc }` or\n`{ ok: false, error: { index, path, reason: 'path' | 'test', message } }`, where `path` is the\nexact pointer that failed — for `move`/`copy`, whichever side (source or target) was bad.\n\n### diff\n\n```ts\nfunction diff(from: JsonValue, to: JsonValue): JsonPatch;\n```\n\nComputes a patch that turns `from` into `to`. Objects diff per key; arrays align on their\ncommon prefix and suffix, recurse positionally through the middle, and emit ordered removals\nand indexed inserts around it (`-` only for true appends); anything else becomes one\n`replace` at the deepest shared pointer. The result always round-trips\n(`apply(from, diff(from, to))` deep-equals `to`) — verified by a seeded round-trip test.\n\n### getIn / parsePointer / formatPointer\n\n```ts\nfunction getIn(doc: JsonValue, pointer: JsonPointer): JsonValue | undefined;\nfunction parsePointer(pointer: JsonPointer): string[];\nfunction formatPointer(tokens: readonly string[]): JsonPointer;\n```\n\nRFC 6901 throughout: `~1` decodes to `/`, `~0` to `~`; the empty pointer is the whole\ndocument. `parsePointer('x')` throws — pointers start with `/` or are empty.\n\n### merge (subpath `@vielzeug/patchwork/merge`)\n\n```ts\nfunction merge(base: JsonValue, local: JsonValue, remote: JsonValue, options?: MergeOptions): MergeResult;\n```\n\nReconciles two diverged copies of `base` field-by-field. Returns `{ doc, conflicts }`:\n`doc` applies both sides where they do not collide, and `conflicts` lists every location\nwhere both sides changed the base differently (`{ base, local, path, remote }`, with\n`undefined` marking a deleted or never-present side). `options.resolution` picks the winner\n(`'remote'` default; `'local'` available) — conflicts are reported either way. Arrays: pure\nappends concatenate (local first), pure truncations take the shorter, anything else\nconflicts as a whole array. Types `MergeConflict`, `MergeOptions`, and `MergeResult` are\nexported from the subpath.\n\n## Types\n\n| Type | Purpose |\n| ---------------- | --------------------------------------------------------------- |\n| `JsonValue` | The JSON domain: null, boolean, number, string, arrays, objects |\n| `JsonObject` | `{ [key: string]: JsonValue }` |\n| `JsonPointer` | A string RFC 6901 pointer |\n| `PatchOperation` | Union of the six RFC 6902 operations |\n| `JsonPatch` | `readonly PatchOperation[]` |\n| `ApplyResult` | `{ ok: true, doc } \\| { ok: false, error: PatchErrorInfo }` |\n| `PatchErrorInfo` | `{ index, path, reason: 'path' \\| 'test', message }` |\n\nIndividual operation types (`AddOperation`, `RemoveOperation`, `ReplaceOperation`,\n`MoveOperation`, `CopyOperation`, `TestOperation`) are exported for building typed patch\nbuilders.\n\n## Errors\n\n| Error | Thrown when |\n| ---------------- | ----------------------------------------------------------------------------------------------------------------------------- |\n| `PatchError` | Base class for every patchwork error |\n| `PatchPathError` | A pointer does not resolve, an index is out of bounds, or a pointer is malformed; `error.pointer` names the offending pointer |\n| `PatchTestError` | A `test` operation did not match the document |\n",
|
|
6
|
+
"usage": "---\ntitle: 'Patchwork: Usage Guide'\ndescription: 'How to use @vielzeug/patchwork: applying patches, conflicts with tryApply, structural diff, pointers, and the JSON domain.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nA patch is just an array of operations — build them by hand or compute them with `diff`, then\napply them immutably:\n\n```ts\nimport { apply, diff } from '@vielzeug/patchwork';\n\nconst cart = { items: [{ qty: 1, sku: 'a' }], meta: { rev: 7 }, total: '99' };\nconst edited = { items: [{ qty: 3, sku: 'a' }], meta: { rev: 8 }, total: '99' };\n\nconst patch = diff(cart, edited);\n// [{ op: 'replace', path: '/items/0/qty', value: 3 }, { op: 'replace', path: '/meta/rev', value: 8 }]\n\nconst next = apply(cart, patch);\nnext !== cart; // a new document\nnext.total === cart.total; // untouched subtrees keep their identity, so memoized\nnext.items !== cart.items; // selectors recompute only over the branches that changed\n```\n\n`apply` returns the same reference when a patch is a no-op (`[]`, or a `replace` with an\nequal value), so `Object.is(before, after)` is a reliable \"did anything change\" check.\n\n## Reading and Pointers\n\n```ts\nimport { formatPointer, getIn, parsePointer } from '@vielzeug/patchwork';\n\ngetIn(cart, '/items/0/sku'); // 'a'\ngetIn(cart, '/items/9'); // undefined — reads never throw\nparsePointer('/a~1b/c~0d'); // ['a/b', 'c~d']\nformatPointer(['a/b', 'c~d']); // '/a~1b/c~0d'\n```\n\n`null` is a value, not an absence: `getIn({ a: null }, '/a')` is `null`, while\n`getIn({ a: null }, '/b')` is `undefined`.\n\n## Conflicts as Data\n\nIn collaborative code a rejected patch is a normal message, not a crash. `apply` throws\n(`PatchPathError` for unresolvable pointers, `PatchTestError` for failed `test` operations);\n`tryApply` returns the same outcome as data:\n\n```ts\nimport { tryApply } from '@vielzeug/patchwork';\n\nconst result = tryApply(doc, [\n { op: 'test', path: '/rev', value: 41 }, // client last saw rev 41\n { op: 'replace', path: '/title', value: 'New' },\n]);\n\nif (!result.ok) {\n // { index: 0, path: '/rev', reason: 'test', message: … } — reply \"conflict, rebase on rev 42\"\n}\n```\n\nGuarding a write with a leading `test` is the whole optimistic-concurrency protocol: the\nserver `tryApply`s, and a failed test means someone else moved first.\n\n## What diff Emits\n\n- **Objects**: per-key `remove`s, `add`s, and recursive descent — changed fields cost one small operation each, regardless of document size.\n- **Arrays**: the common prefix and suffix are aligned and the middle walked positionally; appends become a single `{ op: 'add', path: '/x/-' }`, prepends and middle inserts a single indexed `add`, and surplus entries become ordered index removes.\n- **Different types or root changes**: one `replace` at the shared ancestor — patches stay short and always apply cleanly.\n\n`diff` optimizes for apply-safety and small steady-state payloads (edit-one-field,\nappend-one-row), which is exactly the traffic of form autosaves, live documents, and audit\ntrails. It is not an attempt at minimal-edit-count: reordering an array yields positional\nreplaces, which are correct, just not clever.\n\n## Three-Way Merge (Subpath)\n\nWhen two copies of a document diverge from a common ancestor, `@vielzeug/patchwork/merge`\nreconciles them field-by-field instead of one side overwriting the other:\n\n```ts\nimport { merge } from '@vielzeug/patchwork/merge';\n\nconst base = { price: 10, title: 'Doc', tags: ['a'] };\nconst local = { price: 10, title: 'My edit', tags: ['a', 'mine'] };\nconst remote = { price: 12, title: 'Doc', tags: ['a', 'theirs'] };\n\nconst { doc, conflicts } = merge(base, local, remote);\n// doc: { price: 12, title: 'My edit', tags: ['a', 'mine', 'theirs'] }\n// conflicts: [] — only same-field collisions conflict\n```\n\nThe policy is deliberately conservative: objects merge key-by-key to any depth, a delete\nbeats an untouched copy, both sides only appending an array concatenates (local first), and\nboth sides only truncating takes the shorter result. Anything else — a mid-list array edit,\nan append versus a truncate, different additions to the same key — is reported in\n`conflicts` and resolved by `options.resolution` (`'remote'` default, `'local'` opt-in),\nnever guessed. Ship the merged doc back to either side as an ordinary patch with\n`diff(side, doc)`.\n\nThis module is policy, not RFC 6902: the core entry point stays spec-only on purpose.\n\n## The JSON Domain\n\nDocuments are JSON: `null`, booleans, numbers, strings, arrays, and plain objects. `apply`\nclones every incoming `add`/`copy` value (`structuredClone`), so objects you built the patch\nfrom can be mutated freely afterwards without touching the document. `diff` treats the two\ndocuments read-only and never clones what it returns — `value`s in the patch point into `to`,\nso freeze `to` (or clone the patch) if you intend to keep mutating it.\n\n## Error Handling\n\nAll errors extend `PatchError`. `apply` throws at the first failing operation and leaves\nnothing behind (it builds the next document copy-on-write, so a throw discards it).\n`PatchErrorInfo.path` names the pointer the failing operation targeted — for `move`/`copy`\nthat is the `from` location when the source was missing.\n\n## Best Practices\n\n- Use `tryApply` at network boundaries and `apply` in pure local code — exceptions are for programmer errors, rejections are for protocol answers.\n- Prefix state-changing patches with a `{ op: 'test', path: '/rev', … }` operation instead of shipping whole documents; the patch is the lock.\n- Keep patches in your logs as data (they are JSON): replaying `apply` over an old snapshot reconstructs exactly what was sent.\n- Do not feed non-JSON values (functions, `undefined`, `Date`) through `apply`; validate documents with [Vault](/vault/) schemas at the edge and the domain stays clean.\n- In a sync engine, merge on the server with `{ resolution: 'remote' }` and show the `conflicts` array to the user — silent wins are how sync tools lose trust.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Patchwork: Examples'\ndescription: Practical examples and recipes for @vielzeug/patchwork.\n---\n\n## Examples\n\n- [Diff and Apply](./examples/diff-and-apply.md)\n- [Optimistic Sync with test Operations](./examples/optimistic-sync.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
|
@@ -16,6 +16,11 @@
|
|
|
16
16
|
"id": "diff-basic",
|
|
17
17
|
"code": "import { apply, diff } from '@vielzeug/patchwork'\n\nconst before = { address: { zip: '1010' }, items: ['a'], rev: 1 }\nconst after = { address: { zip: '1020' }, items: ['a', 'b'], rev: 2 }\n\nconst patch = diff(before, after)\nconsole.log(JSON.stringify(patch))\nconsole.log(JSON.stringify(apply(before, patch)))",
|
|
18
18
|
"name": "Diff - Structural patches"
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"id": "merge-basic",
|
|
22
|
+
"code": "import { diff, apply } from '@vielzeug/patchwork'\nimport { merge } from '@vielzeug/patchwork/merge'\n\nconst base = { price: 10, title: 'Doc', tags: ['a'] }\nconst local = { price: 10, title: 'My edit', tags: ['a', 'mine'] }\nconst remote = { price: 12, title: 'Doc', tags: ['a', 'theirs'] }\n\nconst { doc, conflicts } = merge(base, local, remote)\nconsole.log(JSON.stringify(doc))\nconsole.log(conflicts.length)\nconsole.log(JSON.stringify(apply(local, diff(local, doc))))",
|
|
23
|
+
"name": "Merge - Three-way field-level reconciliation"
|
|
19
24
|
}
|
|
20
25
|
],
|
|
21
26
|
"typeSignatures": {
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"apiSource": "// Public root surface of @vielzeug/scribe. Every public export goes through this file.\n\nexport { ScribeError, ScribeLimitError } from './errors';\nexport { parseProse } from './parse';\nexport { proseOutline, proseToText, renderProseDom, renderProseHtml } from './render';\nexport type {\n ProseAlignment,\n ProseBlock,\n ProseBlockquote,\n ProseCodeBlock,\n ProseCodeSpan,\n ProseDoc,\n ProseEmphasis,\n ProseHardBreak,\n ProseHeading,\n ProseHeadingLevel,\n ProseImage,\n ProseInline,\n ProseLink,\n ProseList,\n ProseListItem,\n ProseOutlineEntry,\n ProseOutlineOptions,\n ProseParagraph,\n ProseParseOptions,\n ProseRenderOptions,\n ProseSoftBreak,\n ProseStrikethrough,\n ProseStrong,\n ProseTable,\n ProseTableCell,\n ProseText,\n ProseThematicBreak,\n} from './types';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Scribe: safe Markdown prose'\ndescription: 'Safe Markdown prose: deterministic parser, XSS-safe DOM and HTML renderers, outline and plain-text extraction'\npackage: scribe\ncategory: utilities\nkeywords: [markdown, prose, rendering, xss, sanitizer, content, chat, streaming, table-of-contents]\nexports: [parseProse, renderProseHtml, renderProseDom, proseToText, proseOutline]\nrelated: [refine, archive]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"scribe\" />\n\n## Why Scribe?\n\nRendering Markdown someone else wrote is a security decision. The usual stack pairs a parser\nthat happily passes raw HTML through with a sanitizer bolted on afterward — one forgotten\n`innerHTML` and the bolt is worthless. Scribe makes safety a property of construction instead:\nraw HTML is **not** part of the language, text reaches the DOM only through\n`createTextNode`/`createElement`, and no attribute is ever sourced from the document except\npolicy-checked `href`/`src`. There is no sanitizer step to forget because there is no unsafe\npath to take.\n\n```ts\n// Before: parser + sanitizer + escape hatch\nimport { marked } from 'marked';\nimport DOMPurify from 'dompurify';\ncontainer.innerHTML = DOMPurify.sanitize(marked.parse(userText)); // two libs, one memory\n\n// After: one fixed-profile pipeline, safe by construction\nimport { parseProse, renderProseDom } from '@vielzeug/scribe';\ncontainer.replaceChildren(renderProseDom(parseProse(userText))); // zero deps, no innerHTML\n```\n\nThe profile is a fixed, deterministic GFM-flavored subset — headings, lists, code, tables,\nemphasis, links, images, autolinks, strikethrough — with deliberate, documented limits: no\nraw HTML, reference links, setext headings, entities, or plugin system. Chat bubbles, archive\npublications, and documentation excerpts are exactly the prose this covers.\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/scribe\n```\n\n```sh [npm]\nnpm install @vielzeug/scribe\n```\n\n```sh [yarn]\nyarn add @vielzeug/scribe\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { parseProse, proseOutline, renderProseHtml } from '@vielzeug/scribe';\n\nconst doc = parseProse('# Setup\\n\\nRun **install** first.\\n\\n## Configure\\n\\nEdit the config.');\n\nconsole.log(renderProseHtml(doc, { headingIds: true }));\n// <h1 id=\"setup\">Setup</h1>\n// <p>Run <strong>install</strong> first.</p>\n// <h2 id=\"configure\">Configure</h2>\n// <p>Edit the config.</p>\n\nconsole.log(proseOutline(doc)); // TOC ids match the ids above, exactly\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`parseProse`**: frozen, serializable AST from a fixed GFM-flavored profile — no raw HTML, no plugins, deterministic output.\n- **`renderProseHtml`**: escaped HTML string for SSR, static sites, and tests.\n- **`renderProseDom`**: `DocumentFragment` built with DOM APIs only — markup-lookalike content renders as visible characters.\n- **`proseToText`**: plain text for notifications, search indexing, and previews.\n- **`proseOutline`**: top-level headings with slug ids that match the renderers exactly.\n- **Policy-checked links**: relative/`http`/`https`/`mailto` pass, `javascript:`/`data:` degrade to label text with a dev warning — never a crash, never an anchor.\n- **Hard limits**: oversized or pathologically nested input fails fast with `ScribeLimitError` instead of hanging.\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- [Refine](/refine/): `ore-prose` renders Markdown with this pipeline and Refine typography.\n- [Archive](/archive/): publishes the prose that Scribe renders.\n- [Spell](/spell/): validation for the structured payloads around the prose.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
4
|
+
"index": "---\ntitle: 'Scribe: safe Markdown prose'\ndescription: 'Safe Markdown prose: deterministic parser, XSS-safe DOM and HTML renderers, outline and plain-text extraction'\npackage: scribe\ncategory: utilities\nkeywords: [markdown, prose, rendering, xss, sanitizer, content, chat, streaming, table-of-contents]\nexports: [parseProse, renderProseHtml, renderProseDom, proseToText, proseOutline, ScribeError, ScribeLimitError]\nrelated: [refine, archive]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"scribe\" />\n\n## Why Scribe?\n\nRendering Markdown someone else wrote is a security decision. The usual stack pairs a parser\nthat happily passes raw HTML through with a sanitizer bolted on afterward — one forgotten\n`innerHTML` and the bolt is worthless. Scribe makes safety a property of construction instead:\nraw HTML is **not** part of the language, text reaches the DOM only through\n`createTextNode`/`createElement`, and no attribute is ever sourced from the document except\npolicy-checked `href`/`src`. There is no sanitizer step to forget because there is no unsafe\npath to take.\n\n```ts\n// Before: parser + sanitizer + escape hatch\nimport { marked } from 'marked';\nimport DOMPurify from 'dompurify';\ncontainer.innerHTML = DOMPurify.sanitize(marked.parse(userText)); // two libs, one memory\n\n// After: one fixed-profile pipeline, safe by construction\nimport { parseProse, renderProseDom } from '@vielzeug/scribe';\ncontainer.replaceChildren(renderProseDom(parseProse(userText))); // zero deps, no innerHTML\n```\n\nThe profile is a fixed, deterministic GFM-flavored subset — headings, lists, code, tables,\nemphasis, links, images, autolinks, strikethrough — with deliberate, documented limits: no\nraw HTML, reference links, setext headings, entities, or plugin system. Chat bubbles, archive\npublications, and documentation excerpts are exactly the prose this covers.\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/scribe\n```\n\n```sh [npm]\nnpm install @vielzeug/scribe\n```\n\n```sh [yarn]\nyarn add @vielzeug/scribe\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { parseProse, proseOutline, renderProseHtml } from '@vielzeug/scribe';\n\nconst doc = parseProse('# Setup\\n\\nRun **install** first.\\n\\n## Configure\\n\\nEdit the config.');\n\nconsole.log(renderProseHtml(doc, { headingIds: true }));\n// <h1 id=\"setup\">Setup</h1>\n// <p>Run <strong>install</strong> first.</p>\n// <h2 id=\"configure\">Configure</h2>\n// <p>Edit the config.</p>\n\nconsole.log(proseOutline(doc)); // TOC ids match the ids above, exactly\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`parseProse`**: frozen, serializable AST from a fixed GFM-flavored profile — no raw HTML, no plugins, deterministic output.\n- **`renderProseHtml`**: escaped HTML string for SSR, static sites, and tests.\n- **`renderProseDom`**: `DocumentFragment` built with DOM APIs only — markup-lookalike content renders as visible characters.\n- **`proseToText`**: plain text for notifications, search indexing, and previews.\n- **`proseOutline`**: top-level headings with slug ids that match the renderers exactly.\n- **Policy-checked links**: relative/`http`/`https`/`mailto` pass, `javascript:`/`data:` degrade to label text with a dev warning — never a crash, never an anchor.\n- **Hard limits**: oversized or pathologically nested input fails fast with `ScribeLimitError` instead of hanging.\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- [Refine](/refine/): `ore-prose` renders Markdown with this pipeline and Refine typography.\n- [Archive](/archive/): publishes the prose that Scribe renders.\n- [Spell](/spell/): validation for the structured payloads around the prose.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
5
|
"api": "---\ntitle: 'Scribe: API Reference'\ndescription: 'Public API of @vielzeug/scribe: parser, renderers, outline, text extraction, types, and errors.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| ----------------- | -------------------------------------------- | --------- | ------------------------------------------------------------------- |\n| `parseProse` | Markdown string → frozen `ProseDoc` AST | Sync | Fixed profile: raw HTML, entities, reference links are literal text |\n| `renderProseHtml` | AST → escaped HTML string | Sync | No heading `id`s unless `headingIds: true` |\n| `renderProseDom` | AST → `DocumentFragment` built with DOM APIs | Sync | Needs a DOM; pass the doc, not its blocks |\n| `proseToText` | AST → plain text | Sync | Links keep labels, images keep alt text |\n| `proseOutline` | Headings with ids, renderer order | Sync | Nested headings count in the slug sequence, matching the renderer |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------ | -------------------------- |\n| `@vielzeug/scribe` | Complete public Scribe API |\n\n## Functions\n\n### `parseProse(markdown, options?)`\n\nParses the fixed GFM-flavored profile (see the Usage Guide) into a frozen `ProseDoc`.\nLink/image destinations are policy-checked here: relative URLs always pass, `data:` always\nfails, other schemes require membership in `options.linkProtocols` (default\n`['http', 'https', 'mailto']`). A rejected destination becomes the label/alt text plus a\ndev-only warning — parsing never throws for a bad URL.\n\n```ts\nconst doc = parseProse('Read the [guide](/scribe/).');\n```\n\n- **Throws** `ScribeLimitError` beyond 200,000 characters or 32 nesting levels.\n\n### `renderProseHtml(doc, options?)` → `string`\n\nEscapes every dynamic value; emits only the fixed tag set. `options.headingIds` adds unique\nslug ids matching `proseOutline`.\n\n### `renderProseDom(doc, options?)` → `DocumentFragment`\n\nDOM construction only (`createTextNode`/`createElement`/`setAttribute`): content can never\nexecute. Requires a browser environment. Same options and id behavior as the string renderer.\n\n### `proseToText(doc)` → `string`\n\nPlain text: blocks separated by blank lines, list markers preserved, links reduced to labels.\nFor notifications, search indexing, and previews.\n\n### `proseOutline(doc, options?)` → `readonly ProseOutlineEntry[]`\n\nHeadings as `{ level, text, id }` in document order — the same traversal and slug sequence the\nrenderers use with `headingIds`, including headings nested in blockquotes and lists.\n`options.maxLevel` (1–6) filters entries without shifting the slug sequence, so ids keep\nmatching the rendered document.\n\n## Types\n\nThe AST is public: safe to branch on, cache, and cross worker boundaries (frozen, serializable).\n\n| Type | Purpose |\n| --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |\n| `ProseDoc` | `{ blocks }`: the parsed document |\n| `ProseBlock` | Union of block nodes (paragraph, heading, list …) |\n| `ProseInline` | Union of inline nodes (text, link, codeSpan …) |\n| `ProseParagraph`, `ProseHeading`, `ProseCodeBlock`, `ProseBlockquote`, `ProseList`, `ProseListItem`, `ProseThematicBreak`, `ProseTable`, `ProseTableCell` | Block variants |\n| `ProseText`, `ProseCodeSpan`, `ProseStrong`, `ProseEmphasis`, `ProseStrikethrough`, `ProseLink`, `ProseImage`, `ProseSoftBreak`, `ProseHardBreak` | Inline variants |\n| `ProseParseOptions`, `ProseRenderOptions`, `ProseOutlineOptions` | Option bags |\n| `ProseOutlineEntry`, `ProseHeadingLevel`, `ProseAlignment` | Outline entry, `1–6`, table alignment |\n\n## Errors\n\n| Error | Thrown by | Meaning |\n| ------------------ | -------------- | ----------------------------------------------- |\n| `ScribeError` | — (base class) | Narrow with `instanceof` for any scribe failure |\n| `ScribeLimitError` | `parseProse` | Input exceeds the size or nesting limit |\n",
|
|
6
|
-
"usage": "---\ntitle: 'Scribe: Usage Guide'\ndescription: 'How to use @vielzeug/scribe: parsing, the language profile, rendering to HTML and DOM, link policy, and the security model.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nParse Markdown into a frozen AST once, then render it as many times as you like into any of\nfour shapes:\n\n```ts\nimport { parseProse, proseOutline, proseToText, renderProseDom, renderProseHtml } from '@vielzeug/scribe';\n\nconst doc = parseProse('# Hello\\n\\nShip **today**.');\n\nrenderProseHtml(doc); // string (SSR, VitePress, archive publications)\nrenderProseDom(doc); // DocumentFragment (client replaces, refine ore-prose)\nproseToText(doc); // plain text (search, notifications, a11y)\nproseOutline(doc); // [{ level: 1, text: 'Hello', id: 'hello' }]\n```\n\n`renderProseDom` builds nodes exclusively with `document.createElement` and\n`document.createTextNode` — the DOM path cannot inject markup at all. It requires a live\n`document`; in Node use `renderProseHtml`.\n\n## The Language Profile\n\nScribe implements a fixed CommonMark + GFM subset — the same on every platform and every\nrelease:\n\n| Feature | Notes
|
|
6
|
+
"usage": "---\ntitle: 'Scribe: Usage Guide'\ndescription: 'How to use @vielzeug/scribe: parsing, the language profile, rendering to HTML and DOM, link policy, and the security model.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nParse Markdown into a frozen AST once, then render it as many times as you like into any of\nfour shapes:\n\n```ts\nimport { parseProse, proseOutline, proseToText, renderProseDom, renderProseHtml } from '@vielzeug/scribe';\n\nconst doc = parseProse('# Hello\\n\\nShip **today**.');\n\nrenderProseHtml(doc); // string (SSR, VitePress, archive publications)\nrenderProseDom(doc); // DocumentFragment (client replaces, refine ore-prose)\nproseToText(doc); // plain text (search, notifications, a11y)\nproseOutline(doc); // [{ level: 1, text: 'Hello', id: 'hello' }]\n```\n\n`renderProseDom` builds nodes exclusively with `document.createElement` and\n`document.createTextNode` — the DOM path cannot inject markup at all. It requires a live\n`document`; in Node use `renderProseHtml`.\n\n## The Language Profile\n\nScribe implements a fixed CommonMark + GFM subset — the same on every platform and every\nrelease:\n\n| Feature | Notes |\n| ------------ | ------------------------------------------------------------------------------------------------------------------------------- |\n| Headings | ATX (`#`–`######`) only; setext underlines render literally |\n| Emphasis | `*`, `**`, `***`, `_`, `__` with CommonMark flanking rules (`snake_case` is safe); `~~strikethrough~~` |\n| Code | Fenced (``` / `~~~`, info string preserved as `lang`), indented (4 spaces), backtick spans |\n| Blocks | Paragraphs, blockquotes, thematic breaks, hard breaks (`two spaces` or `\\`) |\n| Lists | `-`/`+`/`*` bullets and `1.` ordered; strict last-marker nesting; simplified tight/loose rule |\n| Tables | GFM pipes with alignment row; a table must start on its own line |\n| Links/images | Inline links with optional titles, images with alt text; angle-bracket URI and email (`mailto:`) autolinks; bare `http(s)` URLs |\n| Task lists | `[ ]`/`[x]` items render a **disabled** checkbox (never interactive) |\n\nDeliberately absent: raw HTML and entities (rendered as inert text), reference link\ndefinitions, setext headings, lazy list continuation, definition lists, footnotes, math.\n\n## HTML and DOM Rendering\n\n### Headings with ids\n\n```ts\nimport { parseProse, renderProseHtml } from '@vielzeug/scribe';\n\nconst doc = parseProse('# Guide\\n\\n# Guide');\n\nrenderProseHtml(doc, { headingIds: true });\n// <h1 id=\"guide\">Guide</h1><h1 id=\"guide-2\">Guide</h1>\n```\n\n`proseOutline` runs the same slugger over the full doc, so its `id` values always match the\nids the renderer emits for the same document.\n\n### DOM vs HTML\n\nBoth renderers produce identical structures. Choose by surface:\n\n```ts\n// Node / static site: a string you embed in a page\nconst html = renderProseHtml(parseProse(source), { headingIds: true });\n\n// Browser: real nodes for replaceChildren — no innerHTML, no sanitizer needed\narticle.replaceChildren(renderProseDom(parseProse(source), { headingIds: true }));\n```\n\n## Link Policy\n\nEvery link destination and image src passes a protocol allowlist **after** control-character\nstripping and numeric entity decoding (so `:javascript:` degrades like the direct form):\n\n```ts\nimport { parseProse, renderProseHtml } from '@vielzeug/scribe';\n\nconst doc = parseProse('[a](javascript:alert(1)) [b](https://ok.test) [c](/relative)');\n\nrenderProseHtml(doc);\n// <p>a <a href=\"https://ok.test\">b</a> <a href=\"/relative\">c</a></p>\n// ↑ rejected link degraded to its label text\n```\n\nDefault allowlist is `http`, `https`, `mailto`; `data:` can never be allowed\n(`data:image/svg+xml` carries scripts). Relative and protocol-relative (`//host`)\ndestinations always pass — they carry no scheme. Override with:\n\n```ts\nparseProse(source, { linkProtocols: ['https'] });\n```\n\nDegradation keeps the link **label** (or image **alt**) as plain text — content is never\nsilently dropped — and a dev-mode warning names the rejected destination.\n\n## Outline and Plain Text\n\n```ts\nimport { parseProse, proseOutline, proseToText } from '@vielzeug/scribe';\n\nconst doc = parseProse('# Intro\\n\\nText\\n\\n## Setup\\n\\nMore text.');\n\nproseOutline(doc); // [{ level: 1, text: 'Intro', id: 'intro' }, …]\nproseOutline(doc, { maxLevel: 2 }); // shallow TOC for sidebars\nproseToText(doc); // \"Intro\\nText\\nSetup\\nMore text.\" for search & alerts\n```\n\nOutline `id`s are produced by the same slugger the renderer uses with `headingIds`, so TOC\nanchors resolve against the rendered HTML with no extra bookkeeping. `proseToText` keeps code\ncontent and drops formatting, links, and images.\n\n## Error Handling\n\nOnly two throw paths exist:\n\n```ts\nimport { parseProse, ScribeError, ScribeLimitError } from '@vielzeug/scribe';\n\ntry {\n parseProse(megabyteOfMarkdown); // > 200_000 characters\n} catch (error) {\n if (error instanceof ScribeLimitError) console.error(error.reason, error.limit);\n}\n```\n\n`ScribeError` is the base class; `ScribeLimitError` covers the input size cap and the\nnesting-depth cap (32). Anything malformed degrades to literal text instead of throwing —\nunclosed emphasis, dangling fences, and broken tables all render as readable prose.\n\n## Refine Integration\n\n`@vielzeug/refine` ships [`<ore-prose>`](/refine/components/prose), which wraps this\npipeline with Refine theme tokens:\n\n```html\n<ore-prose markdown=\"# Hello\\n\\nRendered with **Refine** tokens.\"></ore-prose>\n```\n\nIt re-emits `ScribeError` as an `error` event and falls back to the source's plain text.\n\n## Best Practices\n\n1. **Parse once, render many.** The AST is frozen; keep it and re-render instead of reparsing the same source.\n2. **`headingIds` on both sides.** When you build a TOC with `proseOutline`, enable `headingIds` in the renderer, or the anchors match nothing.\n3. **Don't post-process the HTML with `innerHTML`.** If you need different semantics, walk the AST instead — the renderers are the safety boundary; re-parsing your own edits through `innerHTML` reopens the hole they close. `[VERIFY]`\n4. **Keep hostile input under the caps.** A `ScribeLimitError` is the signal to reject the input at your boundary, not to retry with a bigger limit.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Scribe: Examples'\ndescription: Practical examples and recipes for @vielzeug/scribe.\n---\n\n## Examples\n\n- [Parse and Render](./examples/parse-and-render.md)\n- [Safe Rendering for Untrusted Content](./examples/safe-rendering.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
|
-
"apiSource": "export { CsvScanner,
|
|
2
|
+
"apiSource": "export { CsvScanner, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';\nexport { TabulaError, TabulaParseError, TabulaRowError, TabulaValidationError } from './errors';\nexport { createCsvGridStream } from './stream';\nexport { parseTypedRecords } from './typed';\nexport type {\n TabulaOptions,\n TabulaParseOptions,\n TabulaRecordOptions,\n TabulaRecordSerializeOptions,\n TabulaSerializeOptions,\n} from './types';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: 'Tabula: typed CSV and TSV'\ndescription: 'Typed CSV and TSV: RFC 4180 parser with schema-validated rows, streaming reader, and safe serializer.'\npackage: tabula\ncategory: utilities\nkeywords: [csv, tsv, delimiter, spreadsheet, import, export, parser, serializer, rfc-4180, data-exchange]\nexports: [
|
|
5
|
-
"api": "---\ntitle: 'Tabula: API Reference'\ndescription: 'Public API of @vielzeug/tabula: parsers, serializer, delimiter detection, streaming reader, typed rows, types, and errors.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --------------------- | ---------------------------------------------------- | --------- | -------------------------------------------------------------------- |\n| `parseGrid` | RFC 4180 text → string grid | Sync | Blank lines skipped unless `skipEmptyLines: false` |\n| `parseRecords` | First row (or `headers`) as keys | Sync | Short rows omit keys; extra cells are dropped |\n| `
|
|
6
|
-
"usage": "---\ntitle: 'Tabula: Usage Guide'\ndescription: 'How to use @vielzeug/tabula: parsing grids and records, delimiter detection, serializing, streaming, and schema-typed rows.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nEverything is strings in, strings out — CSV has no types, and tabula does not pretend\notherwise. Parse to a grid when you need positional access, or to records when the first row\nis a header:\n\n```ts\nimport { parseGrid, parseRecords } from '@vielzeug/tabula';\n\nparseGrid('a,b\\n\"x,y\",z\\n');\n// [['a', 'b'], ['x,y', 'z']]\n\nparseRecords('id,total\\n7,\"1,200.00\"\\n');\n// [{ id: '7', total: '1,200.00' }]\n```\n\nA few parser behaviors worth knowing because every hand-rolled parser gets them wrong:\n\n- A BOM is stripped, and `\\r\\n`, `\\r`, and `\\n` all end a record.\n- `\"\"` inside a quoted field is an escaped quote; fields are quoted only as needed on output.\n- A row longer than the header is truncated to the header; a shorter row simply omits keys\n (no surprise `undefined` values in your records).\n- Blank lines are skipped by default; pass `skipEmptyLines: false` to keep them as `['']`.\n\n## Delimiter Detection\n\
|
|
4
|
+
"index": "---\ntitle: 'Tabula: typed CSV and TSV'\ndescription: 'Typed CSV and TSV: RFC 4180 parser with schema-validated rows, streaming reader, and safe serializer.'\npackage: tabula\ncategory: utilities\nkeywords: [csv, tsv, delimiter, spreadsheet, import, export, parser, serializer, rfc-4180, data-exchange]\nexports: [parseGrid, parseRecords, toCsv, recordsToCsv, createCsvGridStream, parseTypedRecords, CsvScanner]\nrelated: [spell, archive]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"tabula\" />\n\n## Why Tabula?\n\nCSV is the format every spreadsheet, analytics tool, and finance department speaks — and the\nformat most hand-rolled parsers get subtly wrong: an embedded comma in a quoted title, a\ndouble-quote escape, a CRLF that silently becomes part of a value. Tabula implements RFC 4180\nexactly, with one scanner behind every entry point, so paste-box input, uploaded files, and\nNode streams all parse with identical semantics.\n\n```ts\n// Before: a join that dies on the first comma inside a product name\nconst rows = orders.map((o) => [o.id, o.title, o.total].join(',')); // title: \"Red, Metallic\" → corrupt\n\n// After: quoting, CRLF, and escaping are the library's problem\nimport { parseRecords, recordsToCsv } from '@vielzeug/tabula';\n\nconst csv = recordsToCsv(orders); // every field quoted only when needed, round-trips exactly\n```\n\nRecords are plain objects, and `parseTypedRecords` hands them straight to a\n[Spell](/spell/) standard schema — strings in, typed rows out, with per-line issues aggregated\ninto one error. The streaming reader processes chunks and blobs without ever buffering the\nwhole document.\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/tabula\n```\n\n```sh [npm]\nnpm install @vielzeug/tabula\n```\n\n```sh [yarn]\nyarn add @vielzeug/tabula\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { parseRecords, recordsToCsv } from '@vielzeug/tabula';\n\nconst grid = parseRecords('id,total\\n7,\"1,200.00\"\\n8,99.50\\n');\n// [{ id: '7', total: '1,200.00' }, { id: '8', total: '99.50' }]\n\nconsole.log(recordsToCsv([{ a: 1, b: 'x,y' }]));\n// a,b\n// 1,\"x,y\"\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`parseGrid`**: RFC 4180 scanner into a string grid — BOM stripped, CRLF/CR/LF endings, `\"\"` escapes, configurable delimiter.\n- **`parseRecords`**: first row as keys (or your own `headers`), short rows omit keys instead of inventing `undefined`.\n- **Delimiter auto-detection**: `,`, `;`, and tab are counted outside quotes on the first line — no content sniffing, and pinning `delimiter` skips it.\n- **`toCsv` / `recordsToCsv`**: quotes only when needed, `quoteAll` for spreadsheet paranoia, CRLF by default.\n- **`createCsvGridStream`**: a `TransformStream` of rows for uploads and Node streams; even delimiter auto-detection buffers at most one line.\n- **`parseTypedRecords`**: rows through any Spell/standard-schema validator — one `TabulaValidationError` with every row's line number and issues.\n- **One scanner everywhere**: `CsvScanner` is push-based; sync parse, streams, and typed parsing share the exact same state machine.\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- [Spell](/spell/): the schema engine behind `parseTypedRecords`.\n- [Archive](/archive/): stores the files these rows came from.\n- [Tempo](/tempo/): parse and serialize the dates that live in CSV columns.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: 'Tabula: API Reference'\ndescription: 'Public API of @vielzeug/tabula: parsers, serializer, delimiter detection, streaming reader, typed rows, types, and errors.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --------------------- | ---------------------------------------------------- | --------- | -------------------------------------------------------------------- |\n| `parseGrid` | RFC 4180 text → string grid | Sync | Blank lines skipped unless `skipEmptyLines: false` |\n| `parseRecords` | First row (or `headers`) as keys | Sync | Short rows omit keys; extra cells are dropped |\n| `toCsv` | Grid → CSV text | Sync | CRLF by default; pass `newline: '\\n'` for LF output |\n| `recordsToCsv` | Records → CSV text with column union | Sync | Without `columns`, order comes from first-seen keys |\n| `createCsvGridStream` | `TransformStream<string, string[]>` for chunked text | Async | The header row is emitted like any other row |\n| `parseTypedRecords` | Records through a standard schema | Sync | Async schemas throw; failures aggregate into `TabulaValidationError` |\n| `CsvScanner` | Push-based state machine behind every parser | Sync | Call `finish()` after the last `push()`; auto-detects when unpinned |\n\n## Package Entry Point\n\n```ts\nimport { parseGrid, parseRecords, recordsToCsv, toCsv } from '@vielzeug/tabula';\n```\n\n## Functions\n\n### parseGrid\n\n```ts\nfunction parseGrid(text: string, options?: TabulaParseOptions): string[][];\n```\n\nParses CSV text into rows of cells. A leading BOM is stripped; `\\r\\n`, `\\r`, and `\\n` all\nterminate records; `\"\"` inside quoted fields is an escaped quote; quotes inside unquoted\nfields are literal (spreadsheet producers emit them constantly). `delimiter` must be a single\ncharacter and defaults to auto-detection: the scanner counts `,`, `;`, and tab outside quotes on\nthe first line and takes the winner (ties go to `,`).\n\n### parseRecords\n\n```ts\nfunction parseRecords(text: string, options?: TabulaRecordOptions): Record<string, string>[];\n```\n\nReads the first row as headers unless `headers` is supplied (then the first row is data).\nExtra cells beyond the header are dropped; missing cells leave the key off the record.\nEmpty `headers` throws `TabulaParseError`.\n\n### toCsv\n\n```ts\nfunction toCsv(rows: Iterable<readonly unknown[]>, options?: TabulaSerializeOptions): string;\n```\n\nSerializes a grid. Fields are quoted only when they contain the delimiter, a quote, `\\r`,\n`\\n`, or leading/trailing spaces — or when `quoteAll` is set. `null`/`undefined` become empty\ncells; other values go through `String()`. Lines end with `\\r\\n` unless `newline` says\notherwise.\n\n### recordsToCsv\n\n```ts\nfunction recordsToCsv(records: Iterable<Record<string, unknown>>, options?: TabulaRecordSerializeOptions): string;\n```\n\nWrites a header row plus one row per record. Columns are `options.columns` or the first-seen\nunion of record keys. Missing keys serialize as empty cells.\n\n### createCsvGridStream\n\n```ts\nfunction createCsvGridStream(options?: TabulaParseOptions): TransformStream<string, string[]>;\n```\n\nTransforms streamed text into completed rows. Until the first newline arrives (needed for\ndelimiter auto-detection unless `delimiter` is pinned) input is buffered by the scanner; after\nthat rows are emitted as they complete.\n\n### parseTypedRecords\n\n```ts\nfunction parseTypedRecords<T>(\n text: string,\n schema: StandardSchemaV1<Record<string, unknown>, T>,\n options?: TabulaRecordOptions,\n): T[];\n```\n\nValidates every record through `schema['~standard'].validate`. Valid rows accumulate;\ninvalid rows produce a `TabulaRowError` with the row's 1-based physical line number, exactly\nas a spreadsheet would show it. All rows are attempted, then failures throw as one `TabulaValidationError`.\n\n### CsvScanner\n\n```ts\nclass CsvScanner {\n constructor(options?: TabulaParseOptions);\n push(text: string, onRow: (row: string[], line: number) => void): void;\n finish(onRow: (row: string[], line: number) => void): void;\n}\n```\n\nThe push-based state machine every parser shares — split a fetch body however you like and\nsemantics stay identical. Without a pinned `delimiter` it holds input until the first line\ncompletes, auto-detects, and starts emitting. `push` may be called with any chunk boundary,\nmid-quote included.\nEach row arrives with the 1-based physical line it started on (quoted newlines and blank\nlines included), which is what `TabulaRowError.line` reports.\n\n## Types\n\n| Type | Purpose |\n| ------------------------------ | -------------------------------------------------- |\n| `TabulaOptions` | `{ delimiter? }` shared by parsers and serializers |\n| `TabulaParseOptions` | `+ { skipEmptyLines? }` (default `true`) |\n| `TabulaRecordOptions` | `+ { headers? }` for headerless documents |\n| `TabulaSerializeOptions` | `{ delimiter?, quoteAll?, newline? }` |\n| `TabulaRecordSerializeOptions` | `+ { columns? }` for explicit column order |\n\n## Errors\n\n| Error | Thrown when |\n| ----------------------- | --------------------------------------------------------------------------------- |\n| `TabulaError` | Base class for every tabula error |\n| `TabulaParseError` | A request cannot be honored (`headers: []`, multi-char `delimiter`, async schema) |\n| `TabulaRowError` | One row failed schema validation (`line`, `issues`) |\n| `TabulaValidationError` | Typed parse finished with any invalid rows (`errors: TabulaRowError[]`) |\n",
|
|
6
|
+
"usage": "---\ntitle: 'Tabula: Usage Guide'\ndescription: 'How to use @vielzeug/tabula: parsing grids and records, delimiter detection, serializing, streaming, and schema-typed rows.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nEverything is strings in, strings out — CSV has no types, and tabula does not pretend\notherwise. Parse to a grid when you need positional access, or to records when the first row\nis a header:\n\n```ts\nimport { parseGrid, parseRecords } from '@vielzeug/tabula';\n\nparseGrid('a,b\\n\"x,y\",z\\n');\n// [['a', 'b'], ['x,y', 'z']]\n\nparseRecords('id,total\\n7,\"1,200.00\"\\n');\n// [{ id: '7', total: '1,200.00' }]\n```\n\nA few parser behaviors worth knowing because every hand-rolled parser gets them wrong:\n\n- A BOM is stripped, and `\\r\\n`, `\\r`, and `\\n` all end a record.\n- `\"\"` inside a quoted field is an escaped quote; fields are quoted only as needed on output.\n- A row longer than the header is truncated to the header; a shorter row simply omits keys\n (no surprise `undefined` values in your records).\n- Blank lines are skipped by default; pass `skipEmptyLines: false` to keep them as `['']`.\n\n## Delimiter Detection\n\nEvery parse entry point auto-detects the delimiter unless you pin one: the scanner counts `,`,\n`;`, and tab occurrences outside quotes on the first line and takes the winner (ties go to `,`).\nA paste box and an uploaded `.csv` both just work:\n\n```ts\nimport { parseGrid } from '@vielzeug/tabula';\n\nparseGrid('a;b\\n1;2\\n'); // German Excel export: delimiter is ';'\n```\n\nPin `delimiter` whenever the source is known — it is faster (the parser never counts) and it\nmakes a stray comma in a title harmless.\n\n## Serializing\n\n`toCsv` writes a grid; `recordsToCsv` writes records, taking the column order from explicit\n`columns` or from the first-seen key order. Fields are quoted only when they contain the\ndelimiter, a quote, a newline, or leading/trailing spaces:\n\n```ts\nimport { recordsToCsv, toCsv } from '@vielzeug/tabula';\n\ntoCsv([['note'], ['said \"hi\"']]);\n// note\\r\\n\"said \"\"hi\"\"\"\n\nrecordsToCsv([{ b: 2, a: 1 }], { columns: ['a', 'b'], newline: '\\n' });\n// a,b\\n1,2\n```\n\n`null` and `undefined` serialize as empty cells; everything else goes through `String()`.\nUse `quoteAll: true` when the consumer is a spreadsheet import wizard that guesses column\ntypes from the first rows.\n\n## Streaming\n\n`createCsvGridStream` is a `TransformStream<string, string[]>`: pipe a text stream through it\nand consume rows as they complete. Even when auto-detecting the delimiter it buffers at most\none line, so gigabyte exports never touch memory:\n\n```ts\nimport { createCsvGridStream } from '@vielzeug/tabula';\n\nconst rows = file.stream().pipeThrough(new TextDecoderStream()).pipeThrough(createCsvGridStream());\nfor await (const row of rows) consume(row);\n```\n\nThe header row is emitted like any other row — decide what to do with it at the consumer.\n\n## Typed Rows\n\n`parseTypedRecords` runs every record through a Spell (or any standard-schema) validator and\naggregates failures: one `TabulaValidationError` carrying a `TabulaRowError` per bad row with\nits 1-based line number, so a broken export is reported in full rather than at the first bad\ncell.\n\n```ts\nimport { s } from '@vielzeug/spell';\nimport { parseTypedRecords } from '@vielzeug/tabula';\n\nconst orderSchema = s.object({ id: s.string(), qty: s.coerce.number() });\nconst orders = parseTypedRecords(text, orderSchema); // qty arrives as a number\n```\n\nSchema validation must be synchronous; an async schema throws a `TypeError` immediately\nrather than half-parsing the file.\n\n## Error Handling\n\nAll errors extend `TabulaError`. Parsing is deliberately forgiving of stray quotes\n(spreadsheet producers emit them constantly), so `TabulaParseError` fires only on requests\nthat cannot be honored, such as `headers: []`. Row-level validation failures arrive as one\n`TabulaValidationError` whose `errors` lists a `TabulaRowError` per bad line — report those\nper line, not as one opaque message.\n\n## Best Practices\n\n- Pin `delimiter` and `quote` when the producer is known; auto-detect only for paste boxes and unknown uploads.\n- Feed user imports through `parseTypedRecords` with Spell schemas — CSV hands you strings, and the coercion is where bugs live.\n- Serialize with `recordsToCsv` and explicit `columns` for exports; key insertion order is accidental API otherwise.\n- For files larger than a few MB, stream: `createCsvGridStream` keeps memory flat and shares the exact scanner semantics of `parseGrid`.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Tabula: Examples'\ndescription: Practical examples and recipes for @vielzeug/tabula.\n---\n\n## Examples\n\n- [Parse and Serialize](./examples/parse-and-serialize.md)\n- [Typed Import Pipeline](./examples/typed-imports.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
|
@@ -14,17 +14,16 @@
|
|
|
14
14
|
},
|
|
15
15
|
{
|
|
16
16
|
"id": "serialize-basic",
|
|
17
|
-
"code": "import {
|
|
18
|
-
"name": "Serialize - Safe quoting and
|
|
17
|
+
"code": "import { toCsv } from '@vielzeug/tabula'\n\nconst csv = toCsv([['note', 'value'], ['said \"hi\"', 'a,b'], ['plain', 42]], { newline: '\\n' })\nconsole.log(csv)\n\nconst tsv = toCsv([['note', 'value'], ['tab\\there', 42]], { delimiter: '\\t', newline: '\\n' })\nconsole.log(tsv)",
|
|
18
|
+
"name": "Serialize - Safe quoting and delimiters"
|
|
19
19
|
}
|
|
20
20
|
],
|
|
21
21
|
"typeSignatures": {
|
|
22
|
-
"CsvScanner": "export { CsvScanner,
|
|
23
|
-
"
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
"toCsv": "export { CsvScanner, detectDelimiter, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';",
|
|
22
|
+
"CsvScanner": "export { CsvScanner, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';",
|
|
23
|
+
"parseGrid": "export { CsvScanner, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';",
|
|
24
|
+
"parseRecords": "export { CsvScanner, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';",
|
|
25
|
+
"recordsToCsv": "export { CsvScanner, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';",
|
|
26
|
+
"toCsv": "export { CsvScanner, parseGrid, parseRecords, recordsToCsv, toCsv } from './csv';",
|
|
28
27
|
"TabulaError": "export { TabulaError, TabulaParseError, TabulaRowError, TabulaValidationError } from './errors';",
|
|
29
28
|
"TabulaParseError": "export { TabulaError, TabulaParseError, TabulaRowError, TabulaValidationError } from './errors';",
|
|
30
29
|
"TabulaRowError": "export { TabulaError, TabulaParseError, TabulaRowError, TabulaValidationError } from './errors';",
|