@vielzeug/codex 26.11.12 → 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 +188 -62
- package/data/llms-full.txt +1711 -921
- package/data/llms.txt +4 -1
- package/data/manifest.json +2 -6
- package/data/packages/archive.json +1 -1
- package/data/packages/arsenal.json +4 -2
- package/data/packages/clockwork.json +3 -3
- package/data/packages/codex.json +20 -11
- package/data/packages/coins.json +22 -24
- package/data/packages/courier.json +12 -11
- package/data/packages/flux.json +2 -2
- package/data/packages/forge.json +3 -3
- package/data/packages/herald.json +2 -2
- package/data/packages/ledger.json +1 -1
- package/data/packages/lingua.json +37 -42
- package/data/packages/patchwork.json +50 -0
- package/data/packages/postmaster.json +8 -8
- package/data/packages/refine.json +2 -2
- package/data/packages/scribe.json +57 -0
- package/data/packages/sentinel.json +1 -1
- package/data/packages/sourcerer.json +2 -2
- package/data/packages/tabula.json +39 -0
- package/data/packages/tavern.json +20 -18
- package/data/packages/tempo.json +48 -63
- package/data/packages/vault.json +29 -31
- package/data/packages/wayfinder.json +12 -7
- package/data/refine.json +76 -0
- package/dist/catalog.d.ts +13 -1
- package/dist/catalog.js +80 -53
- package/dist/catalog.js.map +1 -1
- package/dist/cli.js +5 -5
- package/dist/cli.js.map +1 -1
- package/dist/consumer.d.ts +17 -0
- package/dist/consumer.js +114 -0
- package/dist/consumer.js.map +1 -0
- package/dist/errors.js +0 -1
- package/dist/errors.js.map +1 -1
- package/dist/http.d.ts +0 -1
- package/dist/http.js +0 -5
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/port.js +2 -2
- package/dist/port.js.map +1 -1
- package/dist/server.d.ts +5 -3
- package/dist/server.js +10 -6
- package/dist/server.js.map +1 -1
- package/dist/snapshot.d.ts +11 -8
- package/dist/snapshot.js +24 -128
- package/dist/snapshot.js.map +1 -1
- package/dist/tools/index.d.ts +0 -2
- package/dist/tools/index.js +0 -2
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/packages.js +50 -0
- package/dist/tools/packages.js.map +1 -1
- package/dist/tools/refine.d.ts +2 -2
- package/dist/tools/refine.js.map +1 -1
- package/dist/types.d.ts +2 -30
- package/dist/types.js +1 -1
- package/package.json +2 -13
- package/skills/vielzeug/SKILL.md +4 -1
- package/data/search.json +0 -1688
- package/dist/refine-catalog.d.ts +0 -15
- package/dist/refine-catalog.js +0 -27
- package/dist/refine-catalog.js.map +0 -1
- package/dist/refine.d.ts +0 -7
- package/dist/refine.js +0 -9
- package/dist/refine.js.map +0 -1
package/data/llms-full.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Vielzeug: Full Documentation
|
|
2
2
|
|
|
3
|
-
> Complete documentation for
|
|
3
|
+
> Complete documentation for 46 packages. Version: 26.11.13
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -1573,6 +1573,7 @@ console.log(byRole, health, profile);
|
|
|
1573
1573
|
| `assert` | Assert and narrow a condition | Sync | Available from `/function` |
|
|
1574
1574
|
| `retry` | Retry async work | Async | Rethrows final error |
|
|
1575
1575
|
| `taskPool` | Bound concurrent tasks | Async | Available from `/async` |
|
|
1576
|
+
| `timer` | Re-armable single-slot timeout | Async | Available from `/async` |
|
|
1576
1577
|
| `cache` | In-memory identity-keyed cache | Async | Available from `/cache` |
|
|
1577
1578
|
| `fuzzyFilter` | Filter string or selected object fields | Sync | Object collections require `select` |
|
|
1578
1579
|
| `fuzzyScore` | Rank string or selected object fields | Sync | Object collections require `select` |
|
|
@@ -1697,6 +1698,28 @@ const user = await pool.run((signal) => fetch('/user', { signal }).then((respons
|
|
|
1697
1698
|
pool.dispose();
|
|
1698
1699
|
```
|
|
1699
1700
|
|
|
1701
|
+
### timer
|
|
1702
|
+
|
|
1703
|
+
```ts
|
|
1704
|
+
interface Timer {
|
|
1705
|
+
arm(ms: number): void;
|
|
1706
|
+
cancel(): void;
|
|
1707
|
+
readonly pending: boolean;
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
timer(fn: () => void): Timer
|
|
1711
|
+
```
|
|
1712
|
+
|
|
1713
|
+
A single-slot, re-armable timeout. `arm()` cancels any pending run first, so at most one run is ever scheduled. `pending` is already `false` inside the callback, which may re-arm the timer.
|
|
1714
|
+
|
|
1715
|
+
```ts
|
|
1716
|
+
import { timer } from '@vielzeug/arsenal/async';
|
|
1717
|
+
|
|
1718
|
+
const idleFlush = timer(() => flush());
|
|
1719
|
+
idleFlush.arm(500); // debounced: re-arming restarts the delay
|
|
1720
|
+
idleFlush.cancel();
|
|
1721
|
+
```
|
|
1722
|
+
|
|
1700
1723
|
---
|
|
1701
1724
|
|
|
1702
1725
|
## Cache
|
|
@@ -3484,7 +3507,7 @@ const machine = defineMachine()({
|
|
|
3484
3507
|
invoke: [
|
|
3485
3508
|
{
|
|
3486
3509
|
src: ({ signal }) => fetch('/api/items', { signal }).then((response) => response.json() as Promise),
|
|
3487
|
-
onDone: ({ result }) => ({ items: result, type: 'DONE' }),
|
|
3510
|
+
onDone: ({ result }) => ({ items: result as string[], type: 'DONE' }),
|
|
3488
3511
|
},
|
|
3489
3512
|
],
|
|
3490
3513
|
on: { DONE: { reduce: ({ event }) => ({ items: event.items }), target: 'ready' } },
|
|
@@ -3646,10 +3669,13 @@ Throws `ClockworkDefinitionError` when a definition carries a timer delay outsid
|
|
|
3646
3669
|
### `Actor.subscribe()`
|
|
3647
3670
|
|
|
3648
3671
|
```ts
|
|
3649
|
-
subscribe(
|
|
3672
|
+
subscribe(
|
|
3673
|
+
listener: (snapshot: MachineSnapshot) => void,
|
|
3674
|
+
options?: { readonly signal?: AbortSignal },
|
|
3675
|
+
): () => void;
|
|
3650
3676
|
```
|
|
3651
3677
|
|
|
3652
|
-
Subscribes to future committed actor snapshots. It does not run immediately; read `actor.snapshot` for the initial value. Returns an unsubscribe function. Subscriber failures are reported through `tap()` as `error` events with `phase: 'subscriber'` without stopping remaining subscribers, declared effects, or the actor.
|
|
3678
|
+
Subscribes to future committed actor snapshots. It does not run immediately; read `actor.snapshot` for the initial value. `options.signal` auto-unsubscribes when the signal aborts; an already-aborted signal creates no subscription. Returns an unsubscribe function. Subscriber failures are reported through `tap()` as `error` events with `phase: 'subscriber'` without stopping remaining subscribers, declared effects, or the actor.
|
|
3653
3679
|
|
|
3654
3680
|
**Example:**
|
|
3655
3681
|
|
|
@@ -3757,10 +3783,13 @@ Returns whether the current actor snapshot accepts an event. A guard failure is
|
|
|
3757
3783
|
### `actor.subscribe()`
|
|
3758
3784
|
|
|
3759
3785
|
```ts
|
|
3760
|
-
subscribe(
|
|
3786
|
+
subscribe(
|
|
3787
|
+
listener: (snapshot: MachineSnapshot) => void,
|
|
3788
|
+
options?: { readonly signal?: AbortSignal },
|
|
3789
|
+
): () => void;
|
|
3761
3790
|
```
|
|
3762
3791
|
|
|
3763
|
-
Registers a listener for committed snapshots. The listener does not run immediately.
|
|
3792
|
+
Registers a listener for committed snapshots. The listener does not run immediately. `options.signal` auto-unsubscribes on abort; an already-aborted signal creates no subscription.
|
|
3764
3793
|
|
|
3765
3794
|
**Returns:** An unsubscribe function.
|
|
3766
3795
|
|
|
@@ -3824,7 +3853,7 @@ type MachineConfig,
|
|
|
3824
3853
|
};
|
|
3825
3854
|
```
|
|
3826
3855
|
|
|
3827
|
-
A flat machine definition. State nodes cannot contain child states. The `StateNode`, `Transition`, `After`, `Invoke`, `Effect`, `Guard`, and `Reducer` shapes are inferred inline and exported for reusable helpers. `After.delay` must be finite and between 0 and 2,147,483,647 milliseconds; delayed guards and reducers receive `event: undefined`.
|
|
3856
|
+
A flat machine definition. State nodes cannot contain child states. The `StateNode`, `Transition`, `After`, `Invoke`, `Effect`, `Guard`, and `Reducer` shapes are inferred inline and exported for reusable helpers. `After.delay` must be finite and between 0 and 2,147,483,647 milliseconds; delayed guards and reducers receive `event: undefined`. `Invoke` inside a state node fixes its `Result` to `unknown`, so `onDone` receives `result: unknown`; narrow or cast where the result enters your mapped event.
|
|
3828
3857
|
|
|
3829
3858
|
### `Actor`
|
|
3830
3859
|
|
|
@@ -4021,6 +4050,8 @@ Effects receive `context`, the triggering `event` (or `undefined` for initial en
|
|
|
4021
4050
|
|
|
4022
4051
|
Invokes start on state entry. `src` gets readonly entry context, the triggering event or `undefined`, and an `AbortSignal`. `onDone` or `onError` map settlement to ordinary events. All invokes are cancelled when the actor exits the state or disposes.
|
|
4023
4052
|
|
|
4053
|
+
`onDone` receives `result: unknown`: without a schema system the machine cannot tie one callback's parameter to each `src`'s concrete return type, so narrow or cast explicitly where the result enters your event.
|
|
4054
|
+
|
|
4024
4055
|
```ts
|
|
4025
4056
|
type LoadEvent =
|
|
4026
4057
|
| { type: 'FETCH' }
|
|
@@ -4041,7 +4072,7 @@ const loader = defineMachine()({
|
|
|
4041
4072
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
4042
4073
|
return response.json() as Promise;
|
|
4043
4074
|
},
|
|
4044
|
-
onDone: ({ result }) => ({ items: result, type: 'SUCCESS' }),
|
|
4075
|
+
onDone: ({ result }) => ({ items: result as string[], type: 'SUCCESS' }),
|
|
4045
4076
|
onError: ({ error }) => ({ message: String(error), type: 'FAILURE' }),
|
|
4046
4077
|
},
|
|
4047
4078
|
],
|
|
@@ -4077,7 +4108,7 @@ const notification = defineMachine()({
|
|
|
4077
4108
|
|
|
4078
4109
|
## Snapshot observation and persistence
|
|
4079
4110
|
|
|
4080
|
-
`actor.snapshot` is the current shallow-frozen `MachineSnapshot`; read it directly rather than calling a snapshot method. Use `subscribe()` to integrate a state library or persist future committed snapshots. Fresh actors run their initial entry effects and resources; restored actors start only the restored state's invokes and timers, not its entry effects.
|
|
4111
|
+
`actor.snapshot` is the current shallow-frozen `MachineSnapshot`; read it directly rather than calling a snapshot method. Use `subscribe()` to integrate a state library or persist future committed snapshots; pass `{ signal }` to auto-unsubscribe when an owner's lifetime ends. Fresh actors run their initial entry effects and resources; restored actors start only the restored state's invokes and timers, not its entry effects.
|
|
4081
4112
|
|
|
4082
4113
|
```ts
|
|
4083
4114
|
const stored = sessionStorage.getItem('wizard');
|
|
@@ -4265,8 +4296,8 @@ npx -y @vielzeug/codex
|
|
|
4265
4296
|
|
|
4266
4297
|
- `loadSnapshot` validates chunked snapshot metadata.
|
|
4267
4298
|
- `SnapshotCatalog` loads package content only when requested.
|
|
4268
|
-
- `createMcpServer` registers
|
|
4269
|
-
-
|
|
4299
|
+
- `createMcpServer` registers package tools, plus Refine component tools whenever the snapshot carries them.
|
|
4300
|
+
- The single entry point publishes TypeScript declarations.
|
|
4270
4301
|
- `startHttpHost` enforces loopback binding plus localhost Host and Origin validation.
|
|
4271
4302
|
|
|
4272
4303
|
## Documentation
|
|
@@ -4284,30 +4315,41 @@ npx -y @vielzeug/codex
|
|
|
4284
4315
|
|
|
4285
4316
|
## API Overview
|
|
4286
4317
|
|
|
4287
|
-
| Symbol
|
|
4288
|
-
|
|
|
4289
|
-
| `loadSnapshot`
|
|
4290
|
-
| `
|
|
4291
|
-
| `
|
|
4292
|
-
| `
|
|
4293
|
-
| `startHttpHost`
|
|
4318
|
+
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
4319
|
+
| ------------------ | ------------------------------------------ | -------------- | ------------------------------------- |
|
|
4320
|
+
| `loadSnapshot` | Read validated snapshot metadata | Sync | Content chunks load lazily |
|
|
4321
|
+
| `validateSnapshot` | Full artifact verification (all chunks) | Sync | Generation/CI use, not normal startup |
|
|
4322
|
+
| `SnapshotCatalog` | Query package corpus and Refine components | Sync | Construct from loaded snapshot |
|
|
4323
|
+
| `createMcpServer` | MCP adapter factory | Sync | Requires catalog and version |
|
|
4324
|
+
| `startHttpHost` | Loopback Streamable HTTP host | Async | HTTP remains local-only |
|
|
4294
4325
|
|
|
4295
|
-
## Package Entry
|
|
4326
|
+
## Package Entry Point
|
|
4296
4327
|
|
|
4297
|
-
|
|
4298
|
-
|
|
4299
|
-
|
|
4300
|
-
| `@vielzeug/codex/refine` | Refine catalog and MCP server with component tools |
|
|
4328
|
+
`@vielzeug/codex` is the single entry point: catalog (package docs plus bundled Refine component
|
|
4329
|
+
metadata), snapshot loader, errors, the MCP server factory, the loopback HTTP host, and a
|
|
4330
|
+
re-export of `StdioServerTransport`. There is one `Catalog` surface and one server factory.
|
|
4301
4331
|
|
|
4302
4332
|
## Snapshot
|
|
4303
4333
|
|
|
4304
4334
|
### `loadSnapshot`
|
|
4305
4335
|
|
|
4306
4336
|
```ts
|
|
4307
|
-
loadSnapshot(
|
|
4337
|
+
loadSnapshot(directory?: string, options?: { validateContents?: boolean }): LoadedSnapshot;
|
|
4338
|
+
```
|
|
4339
|
+
|
|
4340
|
+
Loads one snapshot directory: `manifest.json` plus `catalog.json` (eager metadata), an optional
|
|
4341
|
+
`refine.json`, and lazily read `packages/.json` content chunks. `directory` defaults to the
|
|
4342
|
+
bundled `data/`. The snapshot layout is fixed by code; the manifest carries `{ schemaVersion, version }`
|
|
4343
|
+
only. `validateContents: true` turns the lazy chunks into an eager cross-checked read.
|
|
4344
|
+
|
|
4345
|
+
### `validateSnapshot`
|
|
4346
|
+
|
|
4347
|
+
```ts
|
|
4348
|
+
validateSnapshot(snapshotRoot?: string): void;
|
|
4308
4349
|
```
|
|
4309
4350
|
|
|
4310
|
-
|
|
4351
|
+
Runs `loadSnapshot` with `validateContents: true`. Used by snapshot generation, integration tests,
|
|
4352
|
+
and artifact verification; normal startup keeps package chunks lazy.
|
|
4311
4353
|
|
|
4312
4354
|
### `SnapshotCatalog`
|
|
4313
4355
|
|
|
@@ -4315,7 +4357,11 @@ Loads catalog/search metadata and Refine metadata. `snapshotRoot` defaults to bu
|
|
|
4315
4357
|
new SnapshotCatalog(snapshot: LoadedSnapshot)
|
|
4316
4358
|
```
|
|
4317
4359
|
|
|
4318
|
-
Provides
|
|
4360
|
+
Provides package lookup, docs/source/example/signature access, deterministic search, and the
|
|
4361
|
+
Refine component lookup (`listComponents()`, `getComponent(tagName)`). Component methods return an
|
|
4362
|
+
empty list (and `NOT_FOUND` per tag) when the snapshot carries no Refine metadata. `search()`
|
|
4363
|
+
reads content chunks through the same lazy cache as the content getters; there is no separate
|
|
4364
|
+
search index.
|
|
4319
4365
|
|
|
4320
4366
|
---
|
|
4321
4367
|
|
|
@@ -4327,27 +4373,10 @@ Provides generic package lookup, docs/source/example/signature access, and deter
|
|
|
4327
4373
|
createMcpServer(catalog: Catalog, options: { version: string; debug?: boolean }): Server;
|
|
4328
4374
|
```
|
|
4329
4375
|
|
|
4330
|
-
Registers generic package tools over `Catalog
|
|
4331
|
-
|
|
4332
|
-
|
|
4333
|
-
|
|
4334
|
-
### `createMcpServerWithRefine`
|
|
4335
|
-
|
|
4336
|
-
```ts
|
|
4337
|
-
createMcpServerWithRefine(catalog: RefineCatalog, options: { version: string; debug?: boolean }): Server;
|
|
4338
|
-
```
|
|
4339
|
-
|
|
4340
|
-
Creates a server with the general Vielzeug package catalog tools and the additional `refine-*` component tools.
|
|
4341
|
-
|
|
4342
|
-
### `SnapshotRefineCatalog`
|
|
4343
|
-
|
|
4344
|
-
```ts
|
|
4345
|
-
new SnapshotRefineCatalog(snapshot: LoadedSnapshot)
|
|
4346
|
-
```
|
|
4347
|
-
|
|
4348
|
-
Extends `SnapshotCatalog` with `getComponent()` and `listComponents()`.
|
|
4349
|
-
|
|
4350
|
-
Component declarations and their nested data use readonly TypeScript types.
|
|
4376
|
+
Registers the generic package tools over `Catalog`, plus the `refine-*` component tools when the
|
|
4377
|
+
catalog actually carries Refine metadata; tools that could only answer "unavailable" are never
|
|
4378
|
+
offered. The root also re-exports `StdioServerTransport` for connecting the server without a
|
|
4379
|
+
second package import.
|
|
4351
4380
|
|
|
4352
4381
|
## HTTP
|
|
4353
4382
|
|
|
@@ -4357,34 +4386,23 @@ Component declarations and their nested data use readonly TypeScript types.
|
|
|
4357
4386
|
startHttpHost(options: HttpHostOptions): Promise;
|
|
4358
4387
|
```
|
|
4359
4388
|
|
|
4360
|
-
Starts Streamable HTTP on `127.0.0.1` by default. Runtime validation accepts only `127.0.0.1` or
|
|
4389
|
+
Starts Streamable HTTP on `127.0.0.1` by default. Runtime validation accepts only `127.0.0.1` or
|
|
4390
|
+
`::1`; every request must also pass localhost Host and Origin checks. `createServer` must return a
|
|
4391
|
+
fresh, unconnected server with its request handlers registered.
|
|
4361
4392
|
|
|
4362
4393
|
## Types
|
|
4363
4394
|
|
|
4364
4395
|
```ts
|
|
4365
|
-
interface SnapshotPointer {
|
|
4366
|
-
readonly directory: string;
|
|
4367
|
-
}
|
|
4368
|
-
|
|
4369
4396
|
interface SnapshotManifest {
|
|
4370
|
-
readonly catalog: 'catalog.json';
|
|
4371
|
-
readonly contentDirectory: 'packages';
|
|
4372
|
-
readonly refine: 'refine.json' | null;
|
|
4373
4397
|
readonly schemaVersion: typeof SNAPSHOT_SCHEMA_VERSION;
|
|
4374
|
-
readonly search: 'search.json';
|
|
4375
4398
|
readonly version: string;
|
|
4376
4399
|
}
|
|
4377
|
-
```
|
|
4378
|
-
|
|
4379
|
-
Dev snapshots use `SnapshotPointer` (via `current.json`); published snapshots are static directories.
|
|
4380
4400
|
|
|
4381
|
-
```ts
|
|
4382
4401
|
interface LoadedSnapshot {
|
|
4383
4402
|
readonly catalog: CatalogFile;
|
|
4384
4403
|
readonly contentDirectory: string;
|
|
4385
4404
|
readonly manifest: SnapshotManifest;
|
|
4386
4405
|
readonly refineComponents: readonly CemDeclaration[];
|
|
4387
|
-
readonly search: readonly SearchRecord[];
|
|
4388
4406
|
}
|
|
4389
4407
|
```
|
|
4390
4408
|
|
|
@@ -4394,19 +4412,6 @@ interface CatalogFile {
|
|
|
4394
4412
|
readonly version: string;
|
|
4395
4413
|
}
|
|
4396
4414
|
|
|
4397
|
-
interface SearchRecord {
|
|
4398
|
-
readonly category: string;
|
|
4399
|
-
readonly description: string;
|
|
4400
|
-
readonly docs: Readonly>>;
|
|
4401
|
-
readonly examples: readonly { readonly id: string; readonly text: string }[];
|
|
4402
|
-
readonly exports: string;
|
|
4403
|
-
readonly keywords: string;
|
|
4404
|
-
readonly name: string;
|
|
4405
|
-
readonly related: string;
|
|
4406
|
-
readonly slug: string;
|
|
4407
|
-
readonly source: string | null;
|
|
4408
|
-
}
|
|
4409
|
-
|
|
4410
4415
|
interface PackageMeta {
|
|
4411
4416
|
readonly availableDocPages: readonly DocPage[];
|
|
4412
4417
|
readonly category: string;
|
|
@@ -4430,21 +4435,18 @@ interface Example {
|
|
|
4430
4435
|
|
|
4431
4436
|
```ts
|
|
4432
4437
|
interface Catalog {
|
|
4438
|
+
getComponent(tagName: string): CemDeclaration;
|
|
4433
4439
|
getDocs(slug: string, page: DocPage): string;
|
|
4434
4440
|
getExample(slug: string, exampleId: string): Example;
|
|
4435
4441
|
getPackage(slug: string): PackageMeta;
|
|
4436
4442
|
getSource(slug: string): string;
|
|
4437
4443
|
getTypeSignature(slug: string, symbol: string): string;
|
|
4444
|
+
listComponents(): readonly CemDeclaration[];
|
|
4438
4445
|
listExamples(slug: string): readonly Pick[];
|
|
4439
4446
|
listPackages(): readonly PackageMeta[];
|
|
4440
4447
|
search(query: string): readonly SearchHit[];
|
|
4441
4448
|
}
|
|
4442
4449
|
|
|
4443
|
-
interface RefineCatalog extends Catalog {
|
|
4444
|
-
getComponent(tagName: string): CemDeclaration;
|
|
4445
|
-
listComponents(): readonly CemDeclaration[];
|
|
4446
|
-
}
|
|
4447
|
-
|
|
4448
4450
|
interface SearchHit {
|
|
4449
4451
|
readonly matchedExamples?: readonly string[];
|
|
4450
4452
|
readonly matchedIn: readonly ('docs' | 'examples' | 'exports' | 'keywords' | 'metadata' | 'related' | 'source')[];
|
|
@@ -4458,7 +4460,6 @@ Catalog exposes semantic reads. It does not expose its cached content chunks.
|
|
|
4458
4460
|
|
|
4459
4461
|
```ts
|
|
4460
4462
|
interface HttpHost {
|
|
4461
|
-
readonly disposalSignal: AbortSignal;
|
|
4462
4463
|
dispose(): Promise;
|
|
4463
4464
|
readonly disposed: boolean;
|
|
4464
4465
|
readonly host: string;
|
|
@@ -4478,11 +4479,9 @@ interface HttpHostOptions {
|
|
|
4478
4479
|
const DOC_PAGES = ['index', 'api', 'usage', 'examples'] as const;
|
|
4479
4480
|
type DocPage = (typeof DOC_PAGES)[number];
|
|
4480
4481
|
|
|
4481
|
-
const SNAPSHOT_SCHEMA_VERSION =
|
|
4482
|
+
const SNAPSHOT_SCHEMA_VERSION = 2 as const;
|
|
4482
4483
|
```
|
|
4483
4484
|
|
|
4484
|
-
CEM types and `RefineCatalog` are exported from `/refine`.
|
|
4485
|
-
|
|
4486
4485
|
```ts
|
|
4487
4486
|
interface CemDeclaration {
|
|
4488
4487
|
readonly attributes?: readonly CemAttribute[];
|
|
@@ -4536,9 +4535,14 @@ interface CemSlot {
|
|
|
4536
4535
|
}
|
|
4537
4536
|
```
|
|
4538
4537
|
|
|
4538
|
+
Component declarations and their nested data use readonly TypeScript types. The loader pins only
|
|
4539
|
+
the contract its consumers depend on: declarations form an array with valid, unique custom-element
|
|
4540
|
+
`tagName`s.
|
|
4541
|
+
|
|
4539
4542
|
## Errors
|
|
4540
4543
|
|
|
4541
|
-
`CodexError` signals malformed snapshots or host failures. `CatalogError` adds `INVALID_ARG`,
|
|
4544
|
+
`CodexError` signals malformed snapshots or host failures. `CatalogError` adds `INVALID_ARG`,
|
|
4545
|
+
`NOT_FOUND`, or `UNAVAILABLE` for expected tool failures.
|
|
4542
4546
|
|
|
4543
4547
|
### Usage Guide
|
|
4544
4548
|
|
|
@@ -4561,7 +4565,7 @@ npx -y @vielzeug/codex --port=3100
|
|
|
4561
4565
|
curl http://127.0.0.1:3100/health
|
|
4562
4566
|
```
|
|
4563
4567
|
|
|
4564
|
-
Response 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`
|
|
4568
|
+
Response 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.
|
|
4565
4569
|
|
|
4566
4570
|
## Agent Skill
|
|
4567
4571
|
|
|
@@ -4589,7 +4593,7 @@ bun run dev
|
|
|
4589
4593
|
|
|
4590
4594
|
`test:unit` uses fixtures only. `test:integration` regenerates a current snapshot then checks real monorepo inputs.
|
|
4591
4595
|
|
|
4592
|
-
`bun run dev` watches documentation and package inputs,
|
|
4596
|
+
`bun run dev` watches documentation and package inputs, regenerates `.dev/` through a staging swap, and restarts the server against it.
|
|
4593
4597
|
|
|
4594
4598
|
## Debugging
|
|
4595
4599
|
|
|
@@ -4611,23 +4615,14 @@ const catalog = new SnapshotCatalog(snapshot);
|
|
|
4611
4615
|
await createMcpServer(catalog, { version: snapshot.manifest.version }).connect(new StdioServerTransport());
|
|
4612
4616
|
```
|
|
4613
4617
|
|
|
4614
|
-
|
|
4615
|
-
|
|
4616
|
-
```ts
|
|
4617
|
-
import { StdioServerTransport, loadSnapshot } from '@vielzeug/codex';
|
|
4618
|
-
import { createMcpServerWithRefine, SnapshotRefineCatalog } from '@vielzeug/codex/refine';
|
|
4619
|
-
|
|
4620
|
-
const snapshot = loadSnapshot();
|
|
4621
|
-
const catalog = new SnapshotRefineCatalog(snapshot);
|
|
4622
|
-
const server = createMcpServerWithRefine(catalog, { version: snapshot.manifest.version });
|
|
4623
|
-
await server.connect(new StdioServerTransport());
|
|
4624
|
-
```
|
|
4618
|
+
`createMcpServer` also registers the `refine-*` component tools whenever the loaded snapshot carries Refine metadata; there is nothing to opt into.
|
|
4625
4619
|
|
|
4626
4620
|
## Best Practices
|
|
4627
4621
|
|
|
4628
4622
|
- Use `search-packages` for capability discovery before loading broad source.
|
|
4629
4623
|
- Use `get-type-signature` before loading full source.
|
|
4630
|
-
-
|
|
4624
|
+
- 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.
|
|
4625
|
+
- Every snapshot is one flat directory (manifest, catalog, content chunks, optional Refine metadata); `--snapshot` points at it directly.
|
|
4631
4626
|
- Pass `validateContents: true` to `loadSnapshot()` for artifact verification; normal startup keeps package chunks lazy.
|
|
4632
4627
|
- Return a fresh configured server from `startHttpHost`'s `createServer` factory.
|
|
4633
4628
|
- Keep HTTP local. Use stdio for normal client integration.
|
|
@@ -4822,7 +4817,7 @@ function round(
|
|
|
4822
4817
|
value: Money,
|
|
4823
4818
|
options: { fractionDigits: number; rounding?: RoundingMode },
|
|
4824
4819
|
): Money;
|
|
4825
|
-
function
|
|
4820
|
+
function toDecimalString(value: Money): string;
|
|
4826
4821
|
```
|
|
4827
4822
|
|
|
4828
4823
|
`factor` and `divisor` are plain decimal strings; exponent notation, whitespace, and a leading plus are invalid. Matching currency identity is required for binary operations. `round()` requires integer `fractionDigits` from 0 through the currency's `minorUnit`. Scaling and rounding default to `halfAwayFromZero`.
|
|
@@ -4948,18 +4943,9 @@ Every Coins failure extends `CoinsError` and exposes `code`.
|
|
|
4948
4943
|
class CoinsError extends Error {
|
|
4949
4944
|
readonly code: CoinsErrorCode;
|
|
4950
4945
|
}
|
|
4951
|
-
|
|
4952
|
-
class CurrencyMismatchError extends CoinsError {
|
|
4953
|
-
readonly expected: string;
|
|
4954
|
-
readonly received: string;
|
|
4955
|
-
}
|
|
4956
|
-
|
|
4957
|
-
class InvalidCurrencyError extends CoinsError {
|
|
4958
|
-
readonly value: unknown;
|
|
4959
|
-
}
|
|
4960
4946
|
```
|
|
4961
4947
|
|
|
4962
|
-
|
|
4948
|
+
Every failure is a `CoinsError`; branch on the literal `code` union, not on subclasses, and read `message` (and `cause` when present) for details.
|
|
4963
4949
|
|
|
4964
4950
|
### Usage Guide
|
|
4965
4951
|
|
|
@@ -4968,11 +4954,11 @@ class InvalidCurrencyError extends CoinsError {
|
|
|
4968
4954
|
Construct decimal values with a currency definition. Coins stores minor units internally and never accepts implicit floating-point input.
|
|
4969
4955
|
|
|
4970
4956
|
```ts
|
|
4971
|
-
import { USD, add, money,
|
|
4957
|
+
import { USD, add, money, toDecimalString } from '@vielzeug/coins';
|
|
4972
4958
|
|
|
4973
4959
|
const subtotal = add(money('12.50', USD), money('7.25', USD));
|
|
4974
4960
|
|
|
4975
|
-
console.log(
|
|
4961
|
+
console.log(toDecimalString(subtotal)); // '19.75'
|
|
4976
4962
|
```
|
|
4977
4963
|
|
|
4978
4964
|
Use bigint only when data is already in minor units:
|
|
@@ -5002,7 +4988,7 @@ money('500', rewards);
|
|
|
5002
4988
|
Pass plain decimal strings to scaling operations; exponent notation, signs such as `+1`, whitespace, and numeric inputs are rejected. `multiply()`, `divide()`, `exchange()`, `round()`, and visible formatting default to `halfAwayFromZero`; pass a named mode when accounting policy requires another rule.
|
|
5003
4989
|
|
|
5004
4990
|
```ts
|
|
5005
|
-
import { USD, divide, money, multiply, round,
|
|
4991
|
+
import { USD, divide, money, multiply, round, toDecimalString } from '@vielzeug/coins';
|
|
5006
4992
|
|
|
5007
4993
|
const subtotal = money('19.99', USD);
|
|
5008
4994
|
const taxed = multiply(subtotal, '1.08', { rounding: 'halfEven' });
|
|
@@ -5012,7 +4998,7 @@ const roundedInput = money('19.999', USD, { rounding: 'halfAwayFromZero' });
|
|
|
5012
4998
|
const split = divide(taxed, '3', { rounding: 'floor' });
|
|
5013
4999
|
const displayed = round(taxed, { fractionDigits: 0, rounding: 'halfAwayFromZero' });
|
|
5014
5000
|
|
|
5015
|
-
console.log(
|
|
5001
|
+
console.log(toDecimalString(split), toDecimalString(displayed));
|
|
5016
5002
|
```
|
|
5017
5003
|
|
|
5018
5004
|
## Aggregate and Allocate
|
|
@@ -5020,15 +5006,15 @@ console.log(toDecimal(split), toDecimal(displayed));
|
|
|
5020
5006
|
`sum()` infers currency from non-empty values. Pass a canonical `{ currency }` for possibly empty iterables. `allocate()` preserves every minor unit, distributes remainders by largest fractional share with stable index ties, and applies the same allocation symmetrically to negative values. Counts and dense weight arrays are limited to 100,000 shares.
|
|
5021
5007
|
|
|
5022
5008
|
```ts
|
|
5023
|
-
import { USD, allocate, money, sum,
|
|
5009
|
+
import { USD, allocate, money, sum, toDecimalString } from '@vielzeug/coins';
|
|
5024
5010
|
|
|
5025
5011
|
const total = sum([money('10.00', USD), money('5.00', USD)]);
|
|
5026
5012
|
const zero = sum([], { currency: USD });
|
|
5027
5013
|
const weighted = allocate(money('10.00', USD), ['1', '2', '1']);
|
|
5028
5014
|
const even = allocate(money(5n, USD, { unit: 'minor' }), 2);
|
|
5029
5015
|
|
|
5030
|
-
console.log(
|
|
5031
|
-
console.log(weighted.map(
|
|
5016
|
+
console.log(toDecimalString(total));
|
|
5017
|
+
console.log(weighted.map(toDecimalString));
|
|
5032
5018
|
console.log(even.map((value) => value.amount)); // [3n, 2n]
|
|
5033
5019
|
```
|
|
5034
5020
|
|
|
@@ -5758,7 +5744,7 @@ const user = await courier.get('/users/{id}', {
|
|
|
5758
5744
|
prefetch(path: P, config: PrefetchConfig): Promise;
|
|
5759
5745
|
```
|
|
5760
5746
|
|
|
5761
|
-
Starts the same cached GET used by `get()`. `config.cache` is required; `signal`, per-call `timeout`, and `responseType: 'raw'` are unavailable. Fresh values and pending loads are reused. The promise settles when the attempt finishes. Request failures emit `request-error` through `tap()` and resolve without caching data.
|
|
5747
|
+
Starts the same cached GET used by `get()`. `config.cache` is required; `signal`, per-call `timeout`, and `responseType: 'raw'` are unavailable. Fresh values and pending loads are reused. The promise settles when the attempt finishes. Request failures emit `request-error` through `tap()` and resolve without caching data. Cache, key, and URL configuration errors reject before any request is dispatched.
|
|
5762
5748
|
|
|
5763
5749
|
### `invalidateCache()` and `clearCache()`
|
|
5764
5750
|
|
|
@@ -5873,6 +5859,12 @@ type GetRequestConfig = Omit,
|
|
|
5873
5859
|
body?: never;
|
|
5874
5860
|
};
|
|
5875
5861
|
|
|
5862
|
+
// The verbs (`post`, `put`, `patch`, `delete`) accept `HttpRequestConfig`:
|
|
5863
|
+
// request options without `method` or `cache`, exported for typing wrappers.
|
|
5864
|
+
type HttpRequestConfig = Omit, 'cache' | 'method'> & {
|
|
5865
|
+
cache?: never;
|
|
5866
|
+
};
|
|
5867
|
+
|
|
5876
5868
|
type PrefetchConfig = Omit,
|
|
5877
5869
|
'cache' | 'responseType' | 'signal' | 'timeout'
|
|
5878
5870
|
> & {
|
|
@@ -5885,19 +5877,19 @@ type PrefetchConfig = Omit,
|
|
|
5885
5877
|
|
|
5886
5878
|
## Errors
|
|
5887
5879
|
|
|
5888
|
-
| Error | Trigger
|
|
5889
|
-
| ------------------------------ |
|
|
5890
|
-
| `CourierError` | Base class for all Courier errors
|
|
5891
|
-
| `CourierHttpError` | Non-2xx HTTP response
|
|
5892
|
-
| `CourierNetworkError` | Request failure without response
|
|
5893
|
-
| `CourierTimeoutError` | Timeout signal aborts request
|
|
5894
|
-
| `CourierAbortError` | Caller or client cancellation
|
|
5895
|
-
| `CourierSchemaValidationError` | Response schema fails
|
|
5896
|
-
| `CourierParseError` | Response body cannot parse
|
|
5897
|
-
| `CourierConfigError` |
|
|
5898
|
-
| `CourierDisposedError` | Work starts after disposal
|
|
5880
|
+
| Error | Trigger | Notable properties |
|
|
5881
|
+
| ------------------------------ | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
|
|
5882
|
+
| `CourierError` | Base class for all Courier errors | Use `instanceof` to narrow |
|
|
5883
|
+
| `CourierHttpError` | Non-2xx HTTP response | `status`, `data`, `headers`, `method`, `url`, `problem`; `CourierHttpError.is(e, status?)` narrows by status |
|
|
5884
|
+
| `CourierNetworkError` | Request failure without response | `method`, `url`, `cause` |
|
|
5885
|
+
| `CourierTimeoutError` | Timeout signal aborts request | `method`, `url`, `cause` |
|
|
5886
|
+
| `CourierAbortError` | Caller or client cancellation | `method`, `url`, `cause` |
|
|
5887
|
+
| `CourierSchemaValidationError` | Response schema fails | `data`, `cause` |
|
|
5888
|
+
| `CourierParseError` | Response body cannot parse | N/A |
|
|
5889
|
+
| `CourierConfigError` | Caller bug in the request (GET/HEAD body, raw + schema, unresolved path param, non-JSON-serializable body) | N/A |
|
|
5890
|
+
| `CourierDisposedError` | Work starts after disposal | N/A |
|
|
5899
5891
|
|
|
5900
|
-
Errors thrown directly by custom middleware are preserved rather than reclassified.
|
|
5892
|
+
Errors thrown directly by custom middleware are preserved rather than reclassified. Every request method (`request`, `get`, `prefetch`, and the verbs) reports failures as a rejected promise; only `createCourier()` throws synchronously, for invalid timeout and cache options.
|
|
5901
5893
|
|
|
5902
5894
|
### Problem details
|
|
5903
5895
|
|
|
@@ -6057,7 +6049,7 @@ await courier.prefetch('/users/{id}', { cache, params: { id: userId } });
|
|
|
6057
6049
|
const user = await courier.get('/users/{id}', { cache, params: { id: userId } });
|
|
6058
6050
|
```
|
|
6059
6051
|
|
|
6060
|
-
`prefetch()` returns a promise that settles when warming finishes. Request failures are not cached or rejected from that promise; the physical request emits `request-error` through `tap()`. Cache, key, and URL configuration errors
|
|
6052
|
+
`prefetch()` returns a promise that settles when warming finishes. Request failures are not cached or rejected from that promise; the physical request emits `request-error` through `tap()`. Cache, key, and URL configuration errors reject before prefetch dispatches a request.
|
|
6061
6053
|
|
|
6062
6054
|
Invalidate a structured prefix after writes. Every matching settled or pending key becomes ineligible for caching, while unrelated entries remain available.
|
|
6063
6055
|
|
|
@@ -6118,7 +6110,7 @@ await courier.get('/health', { timeout: 2_000 });
|
|
|
6118
6110
|
|
|
6119
6111
|
## Error Handling
|
|
6120
6112
|
|
|
6121
|
-
Courier classifies URL, request-construction, fetch, cancellation, HTTP, response-parsing, and schema failures into distinct error classes. Errors thrown directly by custom middleware are preserved.
|
|
6113
|
+
Courier classifies URL, request-construction, fetch, cancellation, HTTP, response-parsing, and schema failures into distinct error classes. Errors thrown directly by custom middleware are preserved. Every request method reports failures as a rejected promise; only `createCourier()` throws synchronously, for invalid timeout and cache options.
|
|
6122
6114
|
|
|
6123
6115
|
```ts
|
|
6124
6116
|
import {
|
|
@@ -8293,10 +8285,9 @@ try {
|
|
|
8293
8285
|
|
|
8294
8286
|
## Package Entry Point
|
|
8295
8287
|
|
|
8296
|
-
| Import
|
|
8297
|
-
|
|
|
8298
|
-
| `@vielzeug/flux`
|
|
8299
|
-
| `@vielzeug/flux/async` | `toAsyncIterable()` only |
|
|
8288
|
+
| Import | Purpose |
|
|
8289
|
+
| ---------------- | --------------------------------------------------------------------------------------------- |
|
|
8290
|
+
| `@vielzeug/flux` | Core streams, operators, consumers, errors, types, `createChannel()`, and `toAsyncIterable()` |
|
|
8300
8291
|
|
|
8301
8292
|
## Core
|
|
8302
8293
|
|
|
@@ -8482,10 +8473,12 @@ mergeMap(project: (value: A) => Stream, options: FlattenOptions): Operator
|
|
|
8482
8473
|
|
|
8483
8474
|
Runs inner streams with bounded concurrency and queue capacity. Exceeding capacity errors output with `FluxCapacityError`.
|
|
8484
8475
|
|
|
8485
|
-
| Option | Type
|
|
8486
|
-
| ------------- |
|
|
8487
|
-
| `concurrency` | `number \|
|
|
8488
|
-
| `capacity` | `number`
|
|
8476
|
+
| Option | Type | Description |
|
|
8477
|
+
| ------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------- |
|
|
8478
|
+
| `concurrency` | `number \| 'unbounded'` | Maximum concurrently active inner subscriptions; `'unbounded'` starts every value immediately |
|
|
8479
|
+
| `capacity` | `number` | Positive maximum queued source values (required when `concurrency` is a number; unused when `'unbounded'`) |
|
|
8480
|
+
|
|
8481
|
+
Finite `concurrency` without a `capacity` throws `RangeError` when the operator is created.
|
|
8489
8482
|
|
|
8490
8483
|
---
|
|
8491
8484
|
|
|
@@ -8718,7 +8711,7 @@ interface Stream {
|
|
|
8718
8711
|
type OverflowPolicy = 'drop-newest' | 'drop-oldest' | 'error';
|
|
8719
8712
|
type AsyncIterableOptions = { capacity: number; overflow: OverflowPolicy; signal?: AbortSignal };
|
|
8720
8713
|
type TimerOptions = { delay: number; interval?: number };
|
|
8721
|
-
type FlattenOptions = { concurrency: number; capacity: number };
|
|
8714
|
+
type FlattenOptions = { concurrency: number; capacity: number } | { concurrency: 'unbounded'; capacity?: undefined };
|
|
8722
8715
|
type RetryOptions = { times: number; delay?: number | ((attempt: number) => number) };
|
|
8723
8716
|
type ToArrayOptions = { maxItems: number; signal?: AbortSignal };
|
|
8724
8717
|
type ValueOptions = { signal?: AbortSignal; defaultValue?: T };
|
|
@@ -8804,7 +8797,7 @@ clicks.subscribe({
|
|
|
8804
8797
|
});
|
|
8805
8798
|
```
|
|
8806
8799
|
|
|
8807
|
-
Use `switchMap()` for latest-only work, `mergeMap()` for concurrent work with bounded concurrency and queue capacity, and `concatMap()` for ordered work with bounded queue capacity.
|
|
8800
|
+
Use `switchMap()` for latest-only work, `mergeMap()` for concurrent work with bounded concurrency and queue capacity (`{ concurrency: 'unbounded' }` starts every value immediately), and `concatMap()` for ordered work with bounded queue capacity.
|
|
8808
8801
|
|
|
8809
8802
|
```ts
|
|
8810
8803
|
import { from, pipe, retry, switchMap } from '@vielzeug/flux';
|
|
@@ -8959,7 +8952,7 @@ const events = fromSubscribe((listener) => bus.on('message', listener));
|
|
|
8959
8952
|
- Pass `{ signal }` from component, request, or task owner.
|
|
8960
8953
|
- Provide `error` when subscription can recover locally.
|
|
8961
8954
|
- Use `pipe(source, ...)`; never mutate stream definitions.
|
|
8962
|
-
- Bound `mergeMap()` concurrency and queue capacity.
|
|
8955
|
+
- Bound `mergeMap()` concurrency and queue capacity, or choose `'unbounded'` explicitly.
|
|
8963
8956
|
- Bound `concatMap()` queue capacity.
|
|
8964
8957
|
- Bound `toArray()` with realistic `maxItems`.
|
|
8965
8958
|
- Choose async iterator overflow policy deliberately.
|
|
@@ -9749,7 +9742,7 @@ pnpm add @vielzeug/forge
|
|
|
9749
9742
|
- Explicit `validate()` and `submit()` timing
|
|
9750
9743
|
- `/dom`: optional element binding
|
|
9751
9744
|
- `/schema`: validator-agnostic Standard Schema adapter
|
|
9752
|
-
- `/persist`: explicit
|
|
9745
|
+
- `/persist`: explicit key/value draft persistence
|
|
9753
9746
|
- `/form-data`: browser submission serialization
|
|
9754
9747
|
|
|
9755
9748
|
## Documentation
|
|
@@ -9777,7 +9770,7 @@ pnpm add @vielzeug/forge
|
|
|
9777
9770
|
| `submit()` | Validate and submit one captured snapshot | Async | Concurrent submission rejects |
|
|
9778
9771
|
| `bindField()` | Bind a field to an HTML element | Sync | Caller owns returned cleanup |
|
|
9779
9772
|
| `schemaValidator()` | Adapt Standard Schema validation | Async | Transform output is not applied |
|
|
9780
|
-
| `loadForm()` / `saveForm()` | Explicit
|
|
9773
|
+
| `loadForm()` / `saveForm()` | Explicit key/value draft persistence | Async | Loading will not overwrite newer edits |
|
|
9781
9774
|
| `toFormData()` | Serialize supported values | Sync | Dotted keys and object arrays reject |
|
|
9782
9775
|
|
|
9783
9776
|
## Package Entry Point
|
|
@@ -9944,11 +9937,11 @@ Accepts any Standard Schema-compatible validator. Portable issues are copied int
|
|
|
9944
9937
|
```ts
|
|
9945
9938
|
import { loadForm, saveForm } from '@vielzeug/forge/persist';
|
|
9946
9939
|
|
|
9947
|
-
await saveForm(form, store, '
|
|
9948
|
-
await loadForm(form, store, '
|
|
9940
|
+
await saveForm(form, store, 'profile');
|
|
9941
|
+
await loadForm(form, store, 'profile', { signal });
|
|
9949
9942
|
```
|
|
9950
9943
|
|
|
9951
|
-
The store is structural
|
|
9944
|
+
The store is a structural key/value contract: `get(key)` and `put(key, value)`, sync or async. Saved drafts are the form values themselves; `loadForm` restores only plain objects and reports anything else as missing. The optional signal and form disposal cancel pending work; a load returns `false` when values changed before the draft arrived.
|
|
9952
9945
|
|
|
9953
9946
|
## FormData
|
|
9954
9947
|
|
|
@@ -10079,18 +10072,18 @@ Spell schemas implement Standard Schema directly. Forge uses the schema result o
|
|
|
10079
10072
|
## Persist a draft
|
|
10080
10073
|
|
|
10081
10074
|
```ts
|
|
10082
|
-
import { loadForm, saveForm } from '@vielzeug/forge/persist';
|
|
10075
|
+
import { type FormDraftStore, loadForm, saveForm } from '@vielzeug/forge/persist';
|
|
10083
10076
|
|
|
10084
|
-
const
|
|
10085
|
-
|
|
10086
|
-
|
|
10077
|
+
const store: FormDraftStore = {
|
|
10078
|
+
get: async (key) => JSON.parse((await localStorage.getItem(key)) ?? 'null'),
|
|
10079
|
+
put: async (key, value) => localStorage.setItem(key, JSON.stringify(value)),
|
|
10087
10080
|
};
|
|
10088
10081
|
|
|
10089
|
-
await saveForm(form, store, '
|
|
10090
|
-
await loadForm(form, store, '
|
|
10082
|
+
await saveForm(form, store, 'profile');
|
|
10083
|
+
await loadForm(form, store, 'profile', { signal });
|
|
10091
10084
|
```
|
|
10092
10085
|
|
|
10093
|
-
Persistence remains explicit. The store owns durability and
|
|
10086
|
+
Persistence remains explicit. The store owns durability and serialization format; Forge owns the draft shape, which is the form values themselves. Loading returns `false` rather than overwriting edits made while storage was pending, and it never restores a draft that is not a plain object.
|
|
10094
10087
|
|
|
10095
10088
|
## Serialize FormData
|
|
10096
10089
|
|
|
@@ -10161,7 +10154,7 @@ The owner that creates the form disposes it. Framework subscriptions own only th
|
|
|
10161
10154
|
## Working with Other Vielzeug Libraries
|
|
10162
10155
|
|
|
10163
10156
|
- Pass Spell schemas to `schemaValidator()` through Standard Schema.
|
|
10164
|
-
-
|
|
10157
|
+
- Wrap Vault stores in a small `FormDraftStore` adapter for `loadForm()` and `saveForm()`.
|
|
10165
10158
|
- Bind Ore or native controls with `bindField()` and owner cleanup.
|
|
10166
10159
|
|
|
10167
10160
|
## Best Practices
|
|
@@ -10968,13 +10961,10 @@ type Bus = {
|
|
|
10968
10961
|
listenerCount(event?: EventKey): number;
|
|
10969
10962
|
on>(event: K, listener: Listener, options?: SubscribeOptions): Unsubscribe;
|
|
10970
10963
|
onAny(listener: (event: EventKey, payload: unknown) => void, options?: SubscribeOptions): Unsubscribe;
|
|
10971
|
-
once>(event: K, listener: Listener, options?:
|
|
10972
|
-
tap(handler: (event: HeraldEvent) => void, options?:
|
|
10973
|
-
wait>(event: K, options?:
|
|
10974
|
-
waitAny[]>(
|
|
10975
|
-
events: K,
|
|
10976
|
-
options?: { signal?: AbortSignal },
|
|
10977
|
-
): Promise>;
|
|
10964
|
+
once>(event: K, listener: Listener, options?: SubscribeOptions): Unsubscribe;
|
|
10965
|
+
tap(handler: (event: HeraldEvent) => void, options?: SubscribeOptions): Unsubscribe;
|
|
10966
|
+
wait>(event: K, options?: SubscribeOptions): Promise;
|
|
10967
|
+
waitAny[]>(events: K, options?: SubscribeOptions): Promise>;
|
|
10978
10968
|
wildcardCount(): number;
|
|
10979
10969
|
};
|
|
10980
10970
|
```
|
|
@@ -10993,7 +10983,7 @@ type SubscribeOptions = { signal?: AbortSignal };
|
|
|
10993
10983
|
type Unsubscribe = () => void;
|
|
10994
10984
|
```
|
|
10995
10985
|
|
|
10996
|
-
`on()` returns an idempotent unsubscribe function. `once()` is the one-shot variant: it unsubscribes before invoking the listener. An already-aborted signal creates no subscription.
|
|
10986
|
+
`SubscribeOptions` is the single options type for every subscription-shaped method: `on`, `once`, `onAny`, `tap`, `wait`, and `waitAny`. `on()` returns an idempotent unsubscribe function. `once()` is the one-shot variant: it unsubscribes before invoking the listener. An already-aborted signal creates no subscription.
|
|
10997
10987
|
|
|
10998
10988
|
### `onAny()`
|
|
10999
10989
|
|
|
@@ -11005,7 +10995,7 @@ Resolves with the next payload for one event. It rejects with the external signa
|
|
|
11005
10995
|
|
|
11006
10996
|
### `waitAny()`
|
|
11007
10997
|
|
|
11008
|
-
Accepts one or more event keys. It resolves once with a typed `{ event, payload }` discriminated union and removes every losing subscription.
|
|
10998
|
+
Accepts one or more event keys. It resolves once with a typed `{ event, payload }` discriminated union and removes every losing subscription. An empty list throws a synchronous `TypeError`.
|
|
11009
10999
|
|
|
11010
11000
|
```ts
|
|
11011
11001
|
const result = await bus.waitAny(['count', 'ready']);
|
|
@@ -11159,7 +11149,7 @@ const result = await bus.waitAny(['cart:updated', 'user:logout'], {
|
|
|
11159
11149
|
if (result.event === 'cart:updated') console.log(result.payload.count);
|
|
11160
11150
|
```
|
|
11161
11151
|
|
|
11162
|
-
These methods do not replay earlier events. External cancellation rejects with the signal reason. Bus disposal rejects pending waits with `BusDisposedError`.
|
|
11152
|
+
These methods do not replay earlier events. External cancellation rejects with the signal reason. Bus disposal rejects pending waits with `BusDisposedError`. `waitAny()` with an empty event list throws a synchronous `TypeError`.
|
|
11163
11153
|
|
|
11164
11154
|
## Handle Listener Failures
|
|
11165
11155
|
|
|
@@ -13978,6 +13968,7 @@ Use Keymap to route keyboard shortcuts into `undo()` and `redo()`. Project `ledg
|
|
|
13978
13968
|
## Examples
|
|
13979
13969
|
|
|
13980
13970
|
- [Text Editor History](./examples/text-editor.md)
|
|
13971
|
+
- [JSON Delta History](./examples/json-delta-history.md)
|
|
13981
13972
|
- [Form History](./examples/form-history.md)
|
|
13982
13973
|
|
|
13983
13974
|
### REPL Examples
|
|
@@ -14063,11 +14054,9 @@ try {
|
|
|
14063
14054
|
- `createTranslator()` compiles one immutable fixed-locale catalog.
|
|
14064
14055
|
- `createI18n()` manages eager catalogs, locale changes, and optional lazy loading.
|
|
14065
14056
|
- `translate()` renders text and plural messages through explicit catalog nodes.
|
|
14066
|
-
- `translateDynamic()` makes runtime-key lookup explicit.
|
|
14067
|
-
- `parts()` returns typed discriminated parts for framework content.
|
|
14068
14057
|
- `load()` deduplicates loading and resolves the active locale plus configured fallbacks.
|
|
14069
|
-
- `getSnapshot()` and `subscribe()` expose
|
|
14070
|
-
- `serialize()`
|
|
14058
|
+
- `getSnapshot()` and `subscribe()` expose a stable locale snapshot for framework stores.
|
|
14059
|
+
- `serialize()` transfers resolved SSR catalogs for client hydration.
|
|
14071
14060
|
- `missing: 'throw' | 'key' | handler` controls failure behaviour.
|
|
14072
14061
|
- `validateCatalog()` remains an isolated subpath tool.
|
|
14073
14062
|
|
|
@@ -14091,7 +14080,7 @@ try {
|
|
|
14091
14080
|
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
14092
14081
|
| ---------------------- | ------------------------------------------------------------ | -------------- | ------------------------------------------------------------------------------------------- |
|
|
14093
14082
|
| `createTranslator()` | Compile one immutable locale catalog | Sync | No fallback locales |
|
|
14094
|
-
| `createI18n()` | Create mutable locale and catalog store | Sync | Provide catalogs,
|
|
14083
|
+
| `createI18n()` | Create mutable locale and catalog store | Sync | Provide eager catalogs, a loader, or both |
|
|
14095
14084
|
| `createFormatter()` | Create a cached Intl facade from `/format` | Sync | Pass a locale getter for dynamic locale changes |
|
|
14096
14085
|
| `createReactiveI18n()` | Mirror an i18n instance into ripple readables from `/ripple` | Sync | Optional `@vielzeug/ripple` peer; import from subpath |
|
|
14097
14086
|
| `catalogKeys()` | Enumerate message keys as dotted paths | Sync | Takes a catalog (or subtree) only; for an i18n instance pass `state.catalogs[state.locale]` |
|
|
@@ -14135,13 +14124,11 @@ const translator = createTranslator({ save: 'Enregistrer' }, { locale: 'fr' });
|
|
|
14135
14124
|
translator.translate('save');
|
|
14136
14125
|
```
|
|
14137
14126
|
|
|
14138
|
-
| Method | Signature
|
|
14139
|
-
| ------------------ |
|
|
14140
|
-
| `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })`
|
|
14141
|
-
| `
|
|
14142
|
-
| `
|
|
14143
|
-
| `partsDynamic` | `(key, options)` | Parts for runtime key |
|
|
14144
|
-
| `locale` | `Locale` | Resolved active locale |
|
|
14127
|
+
| Method | Signature | Returns |
|
|
14128
|
+
| ------------------ | -------------------------------------------------------------------- | ---------------------- |
|
|
14129
|
+
| `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })` | Rendered string |
|
|
14130
|
+
| `translateUnkeyed` | `(key: string, options?)` | Rendered string |
|
|
14131
|
+
| `locale` | `Locale` | Resolved active locale |
|
|
14145
14132
|
|
|
14146
14133
|
---
|
|
14147
14134
|
|
|
@@ -14151,18 +14138,17 @@ translator.translate('save');
|
|
|
14151
14138
|
function createI18n(options: I18nOptions): I18n;
|
|
14152
14139
|
```
|
|
14153
14140
|
|
|
14154
|
-
Creates catalog store, current locale state, and
|
|
14141
|
+
Creates the catalog store, current locale state, and the active translator.
|
|
14155
14142
|
|
|
14156
|
-
| Parameter | Type | Description
|
|
14157
|
-
| --------------------- | ----------------------------- |
|
|
14158
|
-
| `options.catalogs` | `Catalogs` | Eager locale catalogs
|
|
14159
|
-
| `options.locale` | `Locale` | Initial locale; defaults to
|
|
14160
|
-
| `options.loadCatalog` | `(locale) => Promise \| C` |
|
|
14161
|
-
| `options.fallback` | `Locale \| readonly Locale[]` | Fallback locales loaded with the selected locale
|
|
14162
|
-
| `options.missing` | `MissingStrategy` | Missing-key/value strategy
|
|
14163
|
-
| `options.state` | `TranslationState` | Eager serialized state; mutually exclusive with `catalogs` |
|
|
14143
|
+
| Parameter | Type | Description |
|
|
14144
|
+
| --------------------- | ----------------------------- | ------------------------------------------------ |
|
|
14145
|
+
| `options.catalogs` | `Catalogs` | Eager locale catalogs |
|
|
14146
|
+
| `options.locale` | `Locale` | Initial locale; defaults to `en` |
|
|
14147
|
+
| `options.loadCatalog` | `(locale) => Promise \| C` | Loader for catalogs not supplied eagerly |
|
|
14148
|
+
| `options.fallback` | `Locale \| readonly Locale[]` | Fallback locales loaded with the selected locale |
|
|
14149
|
+
| `options.missing` | `MissingStrategy` | Missing-key/value strategy |
|
|
14164
14150
|
|
|
14165
|
-
Provide `catalogs
|
|
14151
|
+
Provide at least one of `catalogs` or `loadCatalog`; you may combine eager `catalogs` with `loadCatalog` for later locales.
|
|
14166
14152
|
|
|
14167
14153
|
**Returns:** `I18n`, with every `Translator` method plus lifecycle methods.
|
|
14168
14154
|
|
|
@@ -14181,13 +14167,13 @@ i18n.translate('title');
|
|
|
14181
14167
|
| Method or property | Signature | Returns |
|
|
14182
14168
|
| ------------------ | ------------------------------------- | -------------------------------------------------------------- |
|
|
14183
14169
|
| `translate` | Translator method | Rendered string |
|
|
14184
|
-
| `
|
|
14170
|
+
| `translateUnkeyed` | Translator method | Rendered string for a runtime key outside the typed key set |
|
|
14185
14171
|
| `load` | `({ locale? })` | `Promise` after the locale and configured fallbacks load |
|
|
14186
14172
|
| `setLocale` | `(locale)` | `Promise` after an atomic loaded-locale commit |
|
|
14187
14173
|
| `isLoaded` | `({ locale? })` | `boolean` |
|
|
14188
|
-
| `getSnapshot` | `()` |
|
|
14189
|
-
| `subscribe` | `(listener, { immediate?, signal? })` | Unsubscribe function
|
|
14190
|
-
| `serialize` | `()` | Loader-free `
|
|
14174
|
+
| `getSnapshot` | `()` | Current locale, referentially stable until it changes |
|
|
14175
|
+
| `subscribe` | `(listener, { immediate?, signal? })` | Unsubscribe function; listener receives the new locale |
|
|
14176
|
+
| `serialize` | `()` | Loader-free `SerializedI18n` for SSR transfer |
|
|
14191
14177
|
| `dispose` | `()` | `void` |
|
|
14192
14178
|
| `locale` | `Locale` | Current canonical locale |
|
|
14193
14179
|
| `disposed` | `boolean` | Disposal state |
|
|
@@ -14204,7 +14190,7 @@ i18n.translate('title');
|
|
|
14204
14190
|
function createReactiveI18n(i18n: I18n): ReactiveI18n;
|
|
14205
14191
|
```
|
|
14206
14192
|
|
|
14207
|
-
Bridges 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.
|
|
14193
|
+
Bridges 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.
|
|
14208
14194
|
|
|
14209
14195
|
`@vielzeug/ripple` is an optional peer dependency: install it only when you use this subpath.
|
|
14210
14196
|
|
|
@@ -14224,7 +14210,7 @@ await reactive.i18n.setLocale('fr');
|
|
|
14224
14210
|
| `i18n` | `I18n` | The underlying instance for imperative work (`setLocale`, `load`, disposal) |
|
|
14225
14211
|
| `locale` | `Readable` | Reactive locale: reading it inside a computed/template registers the dependency |
|
|
14226
14212
|
| `translate` | `(key, options?)` | Rendered string; re-evaluates whenever the locale changes |
|
|
14227
|
-
| `
|
|
14213
|
+
| `translateUnkeyed` | `(key, options?)` | Rendered string for a runtime key; re-evaluates whenever the locale changes |
|
|
14228
14214
|
|
|
14229
14215
|
---
|
|
14230
14216
|
|
|
@@ -14333,10 +14319,6 @@ type CatalogNode = Catalog | PluralMessage | string;
|
|
|
14333
14319
|
type Catalog = { readonly [key: string]: CatalogNode };
|
|
14334
14320
|
type Catalogs = Record;
|
|
14335
14321
|
|
|
14336
|
-
type TextPart = { readonly type: 'text'; readonly value: string };
|
|
14337
|
-
type ValuePart = { readonly type: 'value'; readonly value: V };
|
|
14338
|
-
type Part = TextPart | ValuePart;
|
|
14339
|
-
|
|
14340
14322
|
type MissingInfo = { readonly key: string; readonly locale: Locale; readonly name?: string };
|
|
14341
14323
|
type MissingHandler = (info: MissingInfo) => string;
|
|
14342
14324
|
type MissingStrategy = 'throw' | 'key' | MissingHandler;
|
|
@@ -14348,49 +14330,35 @@ type I18nOptions = {
|
|
|
14348
14330
|
readonly locale?: Locale;
|
|
14349
14331
|
readonly missing?: MissingStrategy;
|
|
14350
14332
|
} & (
|
|
14351
|
-
| { readonly catalogs: Catalogs; readonly loadCatalog?: CatalogLoader
|
|
14352
|
-
| { readonly catalogs?:
|
|
14353
|
-
| { readonly catalogs?: never; readonly loadCatalog: CatalogLoader; readonly state?: never }
|
|
14333
|
+
| { readonly catalogs: Catalogs; readonly loadCatalog?: CatalogLoader }
|
|
14334
|
+
| { readonly catalogs?: Catalogs; readonly loadCatalog: CatalogLoader }
|
|
14354
14335
|
);
|
|
14355
14336
|
|
|
14356
14337
|
type CatalogLoader = (locale: Locale) => Promise | C;
|
|
14357
14338
|
|
|
14358
|
-
type
|
|
14339
|
+
type SerializedI18n = {
|
|
14359
14340
|
readonly catalogs: Catalogs;
|
|
14360
14341
|
readonly locale: Locale;
|
|
14361
|
-
readonly version: 1;
|
|
14362
|
-
};
|
|
14363
|
-
|
|
14364
|
-
type I18nSnapshot = {
|
|
14365
|
-
readonly locale: Locale;
|
|
14366
|
-
readonly revision: number;
|
|
14367
|
-
readonly translator: Translator;
|
|
14368
14342
|
};
|
|
14369
14343
|
|
|
14370
14344
|
type I18n = Translator & {
|
|
14371
14345
|
readonly disposalSignal: AbortSignal;
|
|
14372
14346
|
dispose(): void;
|
|
14373
14347
|
readonly disposed: boolean;
|
|
14374
|
-
getSnapshot():
|
|
14348
|
+
getSnapshot(): Locale;
|
|
14375
14349
|
isLoaded(options?: { locale?: Locale }): boolean;
|
|
14376
14350
|
load(options?: { locale?: Locale }): Promise;
|
|
14377
|
-
serialize():
|
|
14351
|
+
serialize(): SerializedI18n;
|
|
14378
14352
|
setLocale(locale: Locale): Promise;
|
|
14379
|
-
subscribe(listener: (
|
|
14353
|
+
subscribe(listener: (locale: Locale) => void, options?: SubscribeOptions): () => void;
|
|
14380
14354
|
[Symbol.dispose](): void;
|
|
14381
14355
|
};
|
|
14382
14356
|
|
|
14383
14357
|
type Translator = {
|
|
14384
14358
|
readonly locale: Locale;
|
|
14385
|
-
parts(key: TextKey, options: TranslateOptions & { values: Record }): Array>;
|
|
14386
|
-
parts(key: PluralKey, options: PluralOptions & { values?: Record }): Array>;
|
|
14387
|
-
partsDynamic(
|
|
14388
|
-
key: string,
|
|
14389
|
-
options: (TranslateOptions | PluralOptions) & { values?: Record },
|
|
14390
|
-
): Array>;
|
|
14391
14359
|
translate(key: TextKey, options?: TranslateOptions): string;
|
|
14392
14360
|
translate(key: PluralKey, options: PluralOptions): string;
|
|
14393
|
-
|
|
14361
|
+
translateUnkeyed(key: string, options?: TranslateOptions | PluralOptions): string;
|
|
14394
14362
|
};
|
|
14395
14363
|
```
|
|
14396
14364
|
|
|
@@ -14400,35 +14368,21 @@ type TranslateOptions = { values?: Values };
|
|
|
14400
14368
|
type PluralOptions = TranslateOptions & { count: number; ordinal?: boolean };
|
|
14401
14369
|
type SubscribeOptions = { immediate?: boolean; signal?: AbortSignal };
|
|
14402
14370
|
|
|
14403
|
-
type
|
|
14404
|
-
? C extends
|
|
14405
|
-
? Prefix
|
|
14406
|
-
: C extends Catalog
|
|
14407
|
-
? {
|
|
14408
|
-
[K in string & keyof C]: MessageKey;
|
|
14409
|
-
}[string & keyof C]
|
|
14410
|
-
: never
|
|
14411
|
-
: never;
|
|
14412
|
-
|
|
14413
|
-
type TextKey = Depth extends readonly [unknown, ...infer Rest]
|
|
14414
|
-
? C extends string
|
|
14371
|
+
type CatalogPaths = Depth extends readonly [unknown, ...infer Rest]
|
|
14372
|
+
? C extends Leaf
|
|
14415
14373
|
? Prefix
|
|
14416
|
-
: C extends
|
|
14417
|
-
?
|
|
14418
|
-
|
|
14419
|
-
|
|
14420
|
-
|
|
14374
|
+
: C extends PluralMessage
|
|
14375
|
+
? never
|
|
14376
|
+
: C extends Catalog
|
|
14377
|
+
? {
|
|
14378
|
+
[K in string & keyof C]: CatalogPaths;
|
|
14379
|
+
}[string & keyof C]
|
|
14380
|
+
: never
|
|
14421
14381
|
: never;
|
|
14422
14382
|
|
|
14423
|
-
type
|
|
14424
|
-
|
|
14425
|
-
|
|
14426
|
-
: C extends Catalog
|
|
14427
|
-
? {
|
|
14428
|
-
[K in string & keyof C]: PluralKey;
|
|
14429
|
-
}[string & keyof C]
|
|
14430
|
-
: never
|
|
14431
|
-
: never;
|
|
14383
|
+
type MessageKey = CatalogPaths;
|
|
14384
|
+
type TextKey = CatalogPaths;
|
|
14385
|
+
type PluralKey = CatalogPaths;
|
|
14432
14386
|
|
|
14433
14387
|
type ValidationIssue = { key: string; locale: Locale; missing: Intl.LDMLPluralRule };
|
|
14434
14388
|
type CatalogComparison = {
|
|
@@ -14445,7 +14399,6 @@ type CatalogComparison = {
|
|
|
14445
14399
|
| `LinguaInvalidCatalogError` | Invalid catalog node or reserved key |
|
|
14446
14400
|
| `LinguaInvalidLocaleError` | Invalid BCP 47 locale tag |
|
|
14447
14401
|
| `LinguaInvalidPluralCountError` | Non-finite plural count |
|
|
14448
|
-
| `LinguaInvalidStateError` | Unsupported serialized state version |
|
|
14449
14402
|
| `LinguaMissingCatalogError` | No `loadCatalog` function or catalog source unavailable |
|
|
14450
14403
|
| `LinguaMissingKeyError` | Missing translation key when `missing: 'throw'` |
|
|
14451
14404
|
| `LinguaMissingValueError` | Missing interpolation value when `missing: 'throw'` |
|
|
@@ -14566,30 +14519,6 @@ const navKeys = catalogKeys(messages.nav);
|
|
|
14566
14519
|
// ['home', 'settings']
|
|
14567
14520
|
```
|
|
14568
14521
|
|
|
14569
|
-
## Render Framework Content
|
|
14570
|
-
|
|
14571
|
-
Use `parts()` when replacements are framework nodes, links, or other values that must not be stringified. `parts()` returns a discriminated union: `{ type: 'text', value: string }` for literal text and `{ type: 'value', value: V }` for interpolated values.
|
|
14572
|
-
|
|
14573
|
-
```ts
|
|
14574
|
-
import { createTranslator } from '@vielzeug/lingua';
|
|
14575
|
-
|
|
14576
|
-
const translator = createTranslator({ error: 'Try {retry} or {support}.' }, { locale: 'en' });
|
|
14577
|
-
|
|
14578
|
-
const retry = { href: '/retry', label: 'retry' };
|
|
14579
|
-
const support = { href: '/support', label: 'support' };
|
|
14580
|
-
|
|
14581
|
-
const result = translator.parts('error', { values: { retry, support } });
|
|
14582
|
-
// [
|
|
14583
|
-
// { type: 'text', value: 'Try ' },
|
|
14584
|
-
// { type: 'value', value: { href: '/retry', label: 'retry' } },
|
|
14585
|
-
// { type: 'text', value: ' or ' },
|
|
14586
|
-
// { type: 'value', value: { href: '/support', label: 'support' } },
|
|
14587
|
-
// { type: 'text', value: '.' },
|
|
14588
|
-
// ]
|
|
14589
|
-
```
|
|
14590
|
-
|
|
14591
|
-
Render returned array with framework fragment or list primitive. Give UI values consumer-owned keys before passing them to `parts()`; Lingua preserves value identity and never clones or mutates them.
|
|
14592
|
-
|
|
14593
14522
|
## Use a Fixed-Locale Translator
|
|
14594
14523
|
|
|
14595
14524
|
Use `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.
|
|
@@ -14620,16 +14549,16 @@ await i18n.setLocale('fr');
|
|
|
14620
14549
|
console.log(i18n.translate('navigation.settings'));
|
|
14621
14550
|
```
|
|
14622
14551
|
|
|
14623
|
-
Use 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
|
|
14552
|
+
Use 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.
|
|
14624
14553
|
|
|
14625
|
-
## Subscribe to
|
|
14554
|
+
## Subscribe to Locale Changes
|
|
14626
14555
|
|
|
14627
|
-
Subscribe when UI state must change with locale
|
|
14556
|
+
Subscribe when UI state must change with the locale. Every callback receives the newly committed locale; translate through the instance to read current strings.
|
|
14628
14557
|
|
|
14629
14558
|
```ts
|
|
14630
14559
|
const unsubscribe = i18n.subscribe(
|
|
14631
|
-
(
|
|
14632
|
-
console.log(locale,
|
|
14560
|
+
(locale) => {
|
|
14561
|
+
console.log(locale, i18n.translate('navigation.settings'));
|
|
14633
14562
|
},
|
|
14634
14563
|
{ immediate: true },
|
|
14635
14564
|
);
|
|
@@ -14641,7 +14570,7 @@ Pass `{ signal }` when an `AbortController` owns subscription lifetime.
|
|
|
14641
14570
|
|
|
14642
14571
|
## SSR State
|
|
14643
14572
|
|
|
14644
|
-
Serialize resolved catalogs on the server
|
|
14573
|
+
Serialize 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.
|
|
14645
14574
|
|
|
14646
14575
|
```ts
|
|
14647
14576
|
import { createI18n } from '@vielzeug/lingua';
|
|
@@ -14652,14 +14581,14 @@ const serverI18n = createI18n({
|
|
|
14652
14581
|
});
|
|
14653
14582
|
|
|
14654
14583
|
const state = serverI18n.serialize();
|
|
14655
|
-
const clientI18n = createI18n({ state });
|
|
14584
|
+
const clientI18n = createI18n({ catalogs: state.catalogs, locale: state.locale });
|
|
14656
14585
|
|
|
14657
14586
|
console.log(clientI18n.translate('title'));
|
|
14658
14587
|
serverI18n.dispose();
|
|
14659
14588
|
clientI18n.dispose();
|
|
14660
14589
|
```
|
|
14661
14590
|
|
|
14662
|
-
|
|
14591
|
+
The 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.
|
|
14663
14592
|
|
|
14664
14593
|
## Validation
|
|
14665
14594
|
|
|
@@ -14687,33 +14616,31 @@ const result = compareCatalogs({
|
|
|
14687
14616
|
|
|
14688
14617
|
## Framework Integration
|
|
14689
14618
|
|
|
14690
|
-
|
|
14619
|
+
`getSnapshot()` and `subscribe()` match external-store primitives directly: the snapshot is the locale string, referentially stable until the locale changes.
|
|
14691
14620
|
|
|
14692
14621
|
```ts [React]
|
|
14693
14622
|
import { useSyncExternalStore } from 'react';
|
|
14694
14623
|
|
|
14695
14624
|
import type { I18n } from '@vielzeug/lingua';
|
|
14696
14625
|
|
|
14697
|
-
export function
|
|
14698
|
-
|
|
14699
|
-
|
|
14700
|
-
return snapshot.translator;
|
|
14626
|
+
export function useLocale(i18n: I18n) {
|
|
14627
|
+
return useSyncExternalStore((onChange) => i18n.subscribe(onChange), i18n.getSnapshot, i18n.getSnapshot);
|
|
14701
14628
|
}
|
|
14702
14629
|
```
|
|
14703
14630
|
|
|
14704
14631
|
```ts [Vue 3]
|
|
14705
|
-
import {
|
|
14632
|
+
import { readonly, shallowRef } from 'vue';
|
|
14706
14633
|
|
|
14707
14634
|
import type { I18n } from '@vielzeug/lingua';
|
|
14708
14635
|
|
|
14709
|
-
export function
|
|
14710
|
-
const
|
|
14711
|
-
|
|
14712
|
-
|
|
14636
|
+
export function useLocale(i18n: I18n) {
|
|
14637
|
+
const locale = shallowRef(i18n.getSnapshot());
|
|
14638
|
+
|
|
14639
|
+
i18n.subscribe((next) => {
|
|
14640
|
+
locale.value = next;
|
|
14713
14641
|
});
|
|
14714
14642
|
|
|
14715
|
-
|
|
14716
|
-
return snapshot;
|
|
14643
|
+
return readonly(locale);
|
|
14717
14644
|
}
|
|
14718
14645
|
```
|
|
14719
14646
|
|
|
@@ -14722,21 +14649,21 @@ import { readable } from 'svelte/store';
|
|
|
14722
14649
|
|
|
14723
14650
|
import type { I18n } from '@vielzeug/lingua';
|
|
14724
14651
|
|
|
14725
|
-
export function
|
|
14726
|
-
return readable(i18n.getSnapshot()
|
|
14652
|
+
export function localeStore(i18n: I18n) {
|
|
14653
|
+
return readable(i18n.getSnapshot(), (set) => i18n.subscribe(set));
|
|
14727
14654
|
}
|
|
14728
14655
|
```
|
|
14729
14656
|
|
|
14730
14657
|
## Working with Other Vielzeug Libraries
|
|
14731
14658
|
|
|
14732
|
-
Bridge Lingua's
|
|
14659
|
+
Bridge Lingua's `getSnapshot()`/`subscribe()` pair directly when templates need reactive locale reads.
|
|
14733
14660
|
|
|
14734
14661
|
```ts
|
|
14735
14662
|
import { createRipple } from '@vielzeug/ripple';
|
|
14736
14663
|
|
|
14737
14664
|
const ripple = createRipple();
|
|
14738
14665
|
const i18nState = ripple.fromSubscribable(i18n);
|
|
14739
|
-
export const locale = ripple.computed(() => i18nState.value
|
|
14666
|
+
export const locale = ripple.computed(() => i18nState.value);
|
|
14740
14667
|
|
|
14741
14668
|
export const disposeLocaleBridge = () => ripple.dispose();
|
|
14742
14669
|
```
|
|
@@ -14748,9 +14675,7 @@ Use Courier loaders when locale catalogs come from HTTP rather than bundled modu
|
|
|
14748
14675
|
- Define plural messages with `{ plural: ... }` and no sibling metadata.
|
|
14749
14676
|
- Keep arrays and application metadata outside catalogs.
|
|
14750
14677
|
- Treat source catalog objects as immutable after construction.
|
|
14751
|
-
- Use `translateDynamic()` only for runtime-generated keys.
|
|
14752
14678
|
- Provide eager catalogs for translations required during initial render.
|
|
14753
|
-
- Give UI values keys before passing them to `parts()`.
|
|
14754
14679
|
- Keep loader functions out of SSR payloads.
|
|
14755
14680
|
- Dispose temporary instances after requests, tests, and route lifetimes.
|
|
14756
14681
|
- Use `missing: 'throw'` in development to catch missing keys and values early.
|
|
@@ -14764,7 +14689,7 @@ Use Courier loaders when locale catalogs come from HTTP rather than bundled modu
|
|
|
14764
14689
|
### REPL Examples
|
|
14765
14690
|
|
|
14766
14691
|
- Lazy Locale Catalog (id: `feature-resources`)
|
|
14767
|
-
-
|
|
14692
|
+
- Plural Messages (id: `plurals`)
|
|
14768
14693
|
- Static Translator (id: `static-translator`)
|
|
14769
14694
|
- Reactive Locale Store (id: `store`)
|
|
14770
14695
|
|
|
@@ -18039,6 +17964,333 @@ define('signup-form', {
|
|
|
18039
17964
|
|
|
18040
17965
|
---
|
|
18041
17966
|
|
|
17967
|
+
## @vielzeug/patchwork
|
|
17968
|
+
|
|
17969
|
+
**Category:** utilities
|
|
17970
|
+
|
|
17971
|
+
### Overview
|
|
17972
|
+
|
|
17973
|
+
## Why Patchwork?
|
|
17974
|
+
|
|
17975
|
+
Once two places hold the same document, sending the whole document is the lazy answer that
|
|
17976
|
+
scales worst: bandwidth grows with document size, not with what changed, and blind writes
|
|
17977
|
+
clobber concurrent edits. JSON Patch is the wire format for the honest answer, and Patchwork
|
|
17978
|
+
implements it with the two properties sync code actually needs: `apply` is **immutable with
|
|
17979
|
+
structural sharing** (untouched subtrees keep their object identity, so React and every memo
|
|
17980
|
+
layer work for free), and `diff` is **structural** (objects diff field-by-field, append-only
|
|
17981
|
+
arrays stay one operation, and inserts land at exactly the right index).
|
|
17982
|
+
|
|
17983
|
+
```ts
|
|
17984
|
+
import { apply, diff } from '@vielzeug/patchwork';
|
|
17985
|
+
|
|
17986
|
+
const patch = diff(before, after); // [{ op: 'replace', path: '/user/address/zip', value: '1010' }]
|
|
17987
|
+
const next = apply(before, patch); // before untouched; next.user.address is new, next.user.orders === before.user.orders
|
|
17988
|
+
```
|
|
17989
|
+
|
|
17990
|
+
A failed `test` operation is an ordinary answer in protocol code, not an exception:
|
|
17991
|
+
`tryApply` returns `{ ok: false, error: { index, path, reason } }`, so conflict handling is
|
|
17992
|
+
data you can log and reply to. Zero runtime dependencies, spec-exact pointers (`~0`/`~1`
|
|
17993
|
+
escaping, `-` append), and a browser-safe build.
|
|
17994
|
+
|
|
17995
|
+
## Installation
|
|
17996
|
+
|
|
17997
|
+
```sh [pnpm]
|
|
17998
|
+
pnpm add @vielzeug/patchwork
|
|
17999
|
+
```
|
|
18000
|
+
|
|
18001
|
+
```sh [npm]
|
|
18002
|
+
npm install @vielzeug/patchwork
|
|
18003
|
+
```
|
|
18004
|
+
|
|
18005
|
+
```sh [yarn]
|
|
18006
|
+
yarn add @vielzeug/patchwork
|
|
18007
|
+
```
|
|
18008
|
+
|
|
18009
|
+
## Quick Start
|
|
18010
|
+
|
|
18011
|
+
```ts
|
|
18012
|
+
import { apply, diff, tryApply } from '@vielzeug/patchwork';
|
|
18013
|
+
|
|
18014
|
+
const doc = { items: ['a'], title: 'Cart' };
|
|
18015
|
+
const patch = diff(doc, { items: ['a', 'b'], title: 'Wagen' });
|
|
18016
|
+
// [{ op: 'add', path: '/items/-', value: 'b' }, { op: 'replace', path: '/title', value: 'Wagen' }]
|
|
18017
|
+
|
|
18018
|
+
const next = apply(doc, patch); // doc untouched; next.title changed, next.items is a new array (it grew)
|
|
18019
|
+
|
|
18020
|
+
tryApply(doc, [{ op: 'test', path: '/title', value: 'Other' }, ...patch]);
|
|
18021
|
+
// { ok: false, error: { index: 0, reason: 'test', path: '/title', message: … } }
|
|
18022
|
+
```
|
|
18023
|
+
|
|
18024
|
+
## Features
|
|
18025
|
+
|
|
18026
|
+
- **`apply`**: immutable RFC 6902 — all six operations, copy-on-write with structural sharing.
|
|
18027
|
+
- **`tryApply`**: the same engine as data; a failed `test` or bad pointer returns a structured rejection with the failing operation index.
|
|
18028
|
+
- **`diff`**: per-field object patches, prefix/suffix-aligned arrays (appends, prepends, and middle inserts cost a single `add`), pointer-escaped keys.
|
|
18029
|
+
- **Pointer API**: `parsePointer`/`formatPointer` with `~0`/`~1` escaping and `getIn` for reads.
|
|
18030
|
+
- **Spec-exact edges**: `null` is a value not an absence, `replace` requires an existing target, array `add` inserts, `-` appends.
|
|
18031
|
+
- **Input isolation**: `add`/`copy` values are cloned in, so the caller's objects can never mutate a document afterwards.
|
|
18032
|
+
- **Hard JSON domain**: numbers, strings, booleans, null, arrays, objects — no functions, no prototypes, nothing to inherit.
|
|
18033
|
+
- **`@vielzeug/patchwork/merge`**: opt-in three-way merge — field-level reconciliation of diverged copies with `conflicts` as data.
|
|
18034
|
+
|
|
18035
|
+
## Documentation
|
|
18036
|
+
|
|
18037
|
+
- [Usage Guide](./usage.md)
|
|
18038
|
+
- [API Reference](./api.md)
|
|
18039
|
+
- [Examples](./examples.md)
|
|
18040
|
+
|
|
18041
|
+
## See Also
|
|
18042
|
+
|
|
18043
|
+
- [Tandem](/tandem/): transports patches over the wire in sync protocols.
|
|
18044
|
+
- [Forge](/forge/): tracks the dirty fields whose changes become patches.
|
|
18045
|
+
- [Vault](/vault/): schemas that define what a patchable document may contain.
|
|
18046
|
+
|
|
18047
|
+
### API Reference
|
|
18048
|
+
|
|
18049
|
+
## API Overview
|
|
18050
|
+
|
|
18051
|
+
| Symbol | Purpose | Execution | Common gotcha |
|
|
18052
|
+
| --------------- | ------------------------------------------------------ | --------- | -------------------------------------------------------------- |
|
|
18053
|
+
| `apply` | Immutable RFC 6902 application with structural sharing | Sync | Throws on unresolvable pointer or failed `test` |
|
|
18054
|
+
| `tryApply` | Same engine, rejection as data | Sync | `error.index` is the failing operation, not the document size |
|
|
18055
|
+
| `diff` | Structural patch from `from` to `to` | Sync | Patch values reference `to`; clone if `to` keeps mutating |
|
|
18056
|
+
| `getIn` | Pointer read | Sync | Returns `undefined` both for missing and for non-JSON descents |
|
|
18057
|
+
| `parsePointer` | Pointer → decoded tokens | Sync | Throws `PatchPathError` on pointers not starting with `/` |
|
|
18058
|
+
| `formatPointer` | Tokens → pointer | Sync | `[]` formats to `''` (the whole document) |
|
|
18059
|
+
|
|
18060
|
+
## Package Entry Point
|
|
18061
|
+
|
|
18062
|
+
```ts
|
|
18063
|
+
import { apply, diff, getIn, parsePointer, tryApply } from '@vielzeug/patchwork';
|
|
18064
|
+
import { merge } from '@vielzeug/patchwork/merge'; // three-way merge subpath
|
|
18065
|
+
```
|
|
18066
|
+
|
|
18067
|
+
## Functions
|
|
18068
|
+
|
|
18069
|
+
### apply
|
|
18070
|
+
|
|
18071
|
+
```ts
|
|
18072
|
+
function apply(doc: T, patch: JsonPatch): T;
|
|
18073
|
+
```
|
|
18074
|
+
|
|
18075
|
+
Applies every operation in order, copy-on-write: untouched subtrees keep their identity, and
|
|
18076
|
+
a fully no-op patch returns `doc` itself. `add` inserts into arrays (index may equal the
|
|
18077
|
+
length), sets/overwrites object members, and supports `-` append; `remove` and `replace`
|
|
18078
|
+
require the target to exist; `move` removes the `from` location then adds at `path`; `copy`
|
|
18079
|
+
adds a `structuredClone`; `test` compares structurally. Values from `add`/`copy` are cloned
|
|
18080
|
+
into the document.
|
|
18081
|
+
|
|
18082
|
+
Throws `PatchPathError` when a pointer does not resolve or an index is out of bounds, and
|
|
18083
|
+
`PatchTestError` when a `test` operation does not match.
|
|
18084
|
+
|
|
18085
|
+
### tryApply
|
|
18086
|
+
|
|
18087
|
+
```ts
|
|
18088
|
+
function tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult;
|
|
18089
|
+
```
|
|
18090
|
+
|
|
18091
|
+
Never throws for patch failures: returns `{ ok: true, doc }` or
|
|
18092
|
+
`{ ok: false, error: { index, path, reason: 'path' | 'test', message } }`, where `path` is the
|
|
18093
|
+
exact pointer that failed — for `move`/`copy`, whichever side (source or target) was bad.
|
|
18094
|
+
|
|
18095
|
+
### diff
|
|
18096
|
+
|
|
18097
|
+
```ts
|
|
18098
|
+
function diff(from: JsonValue, to: JsonValue): JsonPatch;
|
|
18099
|
+
```
|
|
18100
|
+
|
|
18101
|
+
Computes a patch that turns `from` into `to`. Objects diff per key; arrays align on their
|
|
18102
|
+
common prefix and suffix, recurse positionally through the middle, and emit ordered removals
|
|
18103
|
+
and indexed inserts around it (`-` only for true appends); anything else becomes one
|
|
18104
|
+
`replace` at the deepest shared pointer. The result always round-trips
|
|
18105
|
+
(`apply(from, diff(from, to))` deep-equals `to`) — verified by a seeded round-trip test.
|
|
18106
|
+
|
|
18107
|
+
### getIn / parsePointer / formatPointer
|
|
18108
|
+
|
|
18109
|
+
```ts
|
|
18110
|
+
function getIn(doc: JsonValue, pointer: JsonPointer): JsonValue | undefined;
|
|
18111
|
+
function parsePointer(pointer: JsonPointer): string[];
|
|
18112
|
+
function formatPointer(tokens: readonly string[]): JsonPointer;
|
|
18113
|
+
```
|
|
18114
|
+
|
|
18115
|
+
RFC 6901 throughout: `~1` decodes to `/`, `~0` to `~`; the empty pointer is the whole
|
|
18116
|
+
document. `parsePointer('x')` throws — pointers start with `/` or are empty.
|
|
18117
|
+
|
|
18118
|
+
### merge (subpath `@vielzeug/patchwork/merge`)
|
|
18119
|
+
|
|
18120
|
+
```ts
|
|
18121
|
+
function merge(base: JsonValue, local: JsonValue, remote: JsonValue, options?: MergeOptions): MergeResult;
|
|
18122
|
+
```
|
|
18123
|
+
|
|
18124
|
+
Reconciles two diverged copies of `base` field-by-field. Returns `{ doc, conflicts }`:
|
|
18125
|
+
`doc` applies both sides where they do not collide, and `conflicts` lists every location
|
|
18126
|
+
where both sides changed the base differently (`{ base, local, path, remote }`, with
|
|
18127
|
+
`undefined` marking a deleted or never-present side). `options.resolution` picks the winner
|
|
18128
|
+
(`'remote'` default; `'local'` available) — conflicts are reported either way. Arrays: pure
|
|
18129
|
+
appends concatenate (local first), pure truncations take the shorter, anything else
|
|
18130
|
+
conflicts as a whole array. Types `MergeConflict`, `MergeOptions`, and `MergeResult` are
|
|
18131
|
+
exported from the subpath.
|
|
18132
|
+
|
|
18133
|
+
## Types
|
|
18134
|
+
|
|
18135
|
+
| Type | Purpose |
|
|
18136
|
+
| ---------------- | --------------------------------------------------------------- |
|
|
18137
|
+
| `JsonValue` | The JSON domain: null, boolean, number, string, arrays, objects |
|
|
18138
|
+
| `JsonObject` | `{ [key: string]: JsonValue }` |
|
|
18139
|
+
| `JsonPointer` | A string RFC 6901 pointer |
|
|
18140
|
+
| `PatchOperation` | Union of the six RFC 6902 operations |
|
|
18141
|
+
| `JsonPatch` | `readonly PatchOperation[]` |
|
|
18142
|
+
| `ApplyResult` | `{ ok: true, doc } \| { ok: false, error: PatchErrorInfo }` |
|
|
18143
|
+
| `PatchErrorInfo` | `{ index, path, reason: 'path' \| 'test', message }` |
|
|
18144
|
+
|
|
18145
|
+
Individual operation types (`AddOperation`, `RemoveOperation`, `ReplaceOperation`,
|
|
18146
|
+
`MoveOperation`, `CopyOperation`, `TestOperation`) are exported for building typed patch
|
|
18147
|
+
builders.
|
|
18148
|
+
|
|
18149
|
+
## Errors
|
|
18150
|
+
|
|
18151
|
+
| Error | Thrown when |
|
|
18152
|
+
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
|
18153
|
+
| `PatchError` | Base class for every patchwork error |
|
|
18154
|
+
| `PatchPathError` | A pointer does not resolve, an index is out of bounds, or a pointer is malformed; `error.pointer` names the offending pointer |
|
|
18155
|
+
| `PatchTestError` | A `test` operation did not match the document |
|
|
18156
|
+
|
|
18157
|
+
### Usage Guide
|
|
18158
|
+
|
|
18159
|
+
## Basic Usage
|
|
18160
|
+
|
|
18161
|
+
A patch is just an array of operations — build them by hand or compute them with `diff`, then
|
|
18162
|
+
apply them immutably:
|
|
18163
|
+
|
|
18164
|
+
```ts
|
|
18165
|
+
import { apply, diff } from '@vielzeug/patchwork';
|
|
18166
|
+
|
|
18167
|
+
const cart = { items: [{ qty: 1, sku: 'a' }], meta: { rev: 7 }, total: '99' };
|
|
18168
|
+
const edited = { items: [{ qty: 3, sku: 'a' }], meta: { rev: 8 }, total: '99' };
|
|
18169
|
+
|
|
18170
|
+
const patch = diff(cart, edited);
|
|
18171
|
+
// [{ op: 'replace', path: '/items/0/qty', value: 3 }, { op: 'replace', path: '/meta/rev', value: 8 }]
|
|
18172
|
+
|
|
18173
|
+
const next = apply(cart, patch);
|
|
18174
|
+
next !== cart; // a new document
|
|
18175
|
+
next.total === cart.total; // untouched subtrees keep their identity, so memoized
|
|
18176
|
+
next.items !== cart.items; // selectors recompute only over the branches that changed
|
|
18177
|
+
```
|
|
18178
|
+
|
|
18179
|
+
`apply` returns the same reference when a patch is a no-op (`[]`, or a `replace` with an
|
|
18180
|
+
equal value), so `Object.is(before, after)` is a reliable "did anything change" check.
|
|
18181
|
+
|
|
18182
|
+
## Reading and Pointers
|
|
18183
|
+
|
|
18184
|
+
```ts
|
|
18185
|
+
import { formatPointer, getIn, parsePointer } from '@vielzeug/patchwork';
|
|
18186
|
+
|
|
18187
|
+
getIn(cart, '/items/0/sku'); // 'a'
|
|
18188
|
+
getIn(cart, '/items/9'); // undefined — reads never throw
|
|
18189
|
+
parsePointer('/a~1b/c~0d'); // ['a/b', 'c~d']
|
|
18190
|
+
formatPointer(['a/b', 'c~d']); // '/a~1b/c~0d'
|
|
18191
|
+
```
|
|
18192
|
+
|
|
18193
|
+
`null` is a value, not an absence: `getIn({ a: null }, '/a')` is `null`, while
|
|
18194
|
+
`getIn({ a: null }, '/b')` is `undefined`.
|
|
18195
|
+
|
|
18196
|
+
## Conflicts as Data
|
|
18197
|
+
|
|
18198
|
+
In collaborative code a rejected patch is a normal message, not a crash. `apply` throws
|
|
18199
|
+
(`PatchPathError` for unresolvable pointers, `PatchTestError` for failed `test` operations);
|
|
18200
|
+
`tryApply` returns the same outcome as data:
|
|
18201
|
+
|
|
18202
|
+
```ts
|
|
18203
|
+
import { tryApply } from '@vielzeug/patchwork';
|
|
18204
|
+
|
|
18205
|
+
const result = tryApply(doc, [
|
|
18206
|
+
{ op: 'test', path: '/rev', value: 41 }, // client last saw rev 41
|
|
18207
|
+
{ op: 'replace', path: '/title', value: 'New' },
|
|
18208
|
+
]);
|
|
18209
|
+
|
|
18210
|
+
if (!result.ok) {
|
|
18211
|
+
// { index: 0, path: '/rev', reason: 'test', message: … } — reply "conflict, rebase on rev 42"
|
|
18212
|
+
}
|
|
18213
|
+
```
|
|
18214
|
+
|
|
18215
|
+
Guarding a write with a leading `test` is the whole optimistic-concurrency protocol: the
|
|
18216
|
+
server `tryApply`s, and a failed test means someone else moved first.
|
|
18217
|
+
|
|
18218
|
+
## What diff Emits
|
|
18219
|
+
|
|
18220
|
+
- **Objects**: per-key `remove`s, `add`s, and recursive descent — changed fields cost one small operation each, regardless of document size.
|
|
18221
|
+
- **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.
|
|
18222
|
+
- **Different types or root changes**: one `replace` at the shared ancestor — patches stay short and always apply cleanly.
|
|
18223
|
+
|
|
18224
|
+
`diff` optimizes for apply-safety and small steady-state payloads (edit-one-field,
|
|
18225
|
+
append-one-row), which is exactly the traffic of form autosaves, live documents, and audit
|
|
18226
|
+
trails. It is not an attempt at minimal-edit-count: reordering an array yields positional
|
|
18227
|
+
replaces, which are correct, just not clever.
|
|
18228
|
+
|
|
18229
|
+
## Three-Way Merge (Subpath)
|
|
18230
|
+
|
|
18231
|
+
When two copies of a document diverge from a common ancestor, `@vielzeug/patchwork/merge`
|
|
18232
|
+
reconciles them field-by-field instead of one side overwriting the other:
|
|
18233
|
+
|
|
18234
|
+
```ts
|
|
18235
|
+
import { merge } from '@vielzeug/patchwork/merge';
|
|
18236
|
+
|
|
18237
|
+
const base = { price: 10, title: 'Doc', tags: ['a'] };
|
|
18238
|
+
const local = { price: 10, title: 'My edit', tags: ['a', 'mine'] };
|
|
18239
|
+
const remote = { price: 12, title: 'Doc', tags: ['a', 'theirs'] };
|
|
18240
|
+
|
|
18241
|
+
const { doc, conflicts } = merge(base, local, remote);
|
|
18242
|
+
// doc: { price: 12, title: 'My edit', tags: ['a', 'mine', 'theirs'] }
|
|
18243
|
+
// conflicts: [] — only same-field collisions conflict
|
|
18244
|
+
```
|
|
18245
|
+
|
|
18246
|
+
The policy is deliberately conservative: objects merge key-by-key to any depth, a delete
|
|
18247
|
+
beats an untouched copy, both sides only appending an array concatenates (local first), and
|
|
18248
|
+
both sides only truncating takes the shorter result. Anything else — a mid-list array edit,
|
|
18249
|
+
an append versus a truncate, different additions to the same key — is reported in
|
|
18250
|
+
`conflicts` and resolved by `options.resolution` (`'remote'` default, `'local'` opt-in),
|
|
18251
|
+
never guessed. Ship the merged doc back to either side as an ordinary patch with
|
|
18252
|
+
`diff(side, doc)`.
|
|
18253
|
+
|
|
18254
|
+
This module is policy, not RFC 6902: the core entry point stays spec-only on purpose.
|
|
18255
|
+
|
|
18256
|
+
## The JSON Domain
|
|
18257
|
+
|
|
18258
|
+
Documents are JSON: `null`, booleans, numbers, strings, arrays, and plain objects. `apply`
|
|
18259
|
+
clones every incoming `add`/`copy` value (`structuredClone`), so objects you built the patch
|
|
18260
|
+
from can be mutated freely afterwards without touching the document. `diff` treats the two
|
|
18261
|
+
documents read-only and never clones what it returns — `value`s in the patch point into `to`,
|
|
18262
|
+
so freeze `to` (or clone the patch) if you intend to keep mutating it.
|
|
18263
|
+
|
|
18264
|
+
## Error Handling
|
|
18265
|
+
|
|
18266
|
+
All errors extend `PatchError`. `apply` throws at the first failing operation and leaves
|
|
18267
|
+
nothing behind (it builds the next document copy-on-write, so a throw discards it).
|
|
18268
|
+
`PatchErrorInfo.path` names the pointer the failing operation targeted — for `move`/`copy`
|
|
18269
|
+
that is the `from` location when the source was missing.
|
|
18270
|
+
|
|
18271
|
+
## Best Practices
|
|
18272
|
+
|
|
18273
|
+
- Use `tryApply` at network boundaries and `apply` in pure local code — exceptions are for programmer errors, rejections are for protocol answers.
|
|
18274
|
+
- Prefix state-changing patches with a `{ op: 'test', path: '/rev', … }` operation instead of shipping whole documents; the patch is the lock.
|
|
18275
|
+
- Keep patches in your logs as data (they are JSON): replaying `apply` over an old snapshot reconstructs exactly what was sent.
|
|
18276
|
+
- 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.
|
|
18277
|
+
- 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.
|
|
18278
|
+
|
|
18279
|
+
### Examples
|
|
18280
|
+
|
|
18281
|
+
## Examples
|
|
18282
|
+
|
|
18283
|
+
- [Diff and Apply](./examples/diff-and-apply.md)
|
|
18284
|
+
- [Optimistic Sync with test Operations](./examples/optimistic-sync.md)
|
|
18285
|
+
|
|
18286
|
+
### REPL Examples
|
|
18287
|
+
|
|
18288
|
+
- Apply - Immutable patches and guarded test (id: `apply-basic`)
|
|
18289
|
+
- Diff - Structural patches (id: `diff-basic`)
|
|
18290
|
+
- Merge - Three-way field-level reconciliation (id: `merge-basic`)
|
|
18291
|
+
|
|
18292
|
+
---
|
|
18293
|
+
|
|
18042
18294
|
## @vielzeug/postmaster
|
|
18043
18295
|
|
|
18044
18296
|
**Category:** Async
|
|
@@ -18057,12 +18309,12 @@ async function createTodo(payload: { id: string; title: string }) {
|
|
|
18057
18309
|
}
|
|
18058
18310
|
|
|
18059
18311
|
// After
|
|
18060
|
-
import { createPostmaster,
|
|
18312
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
18061
18313
|
import { createIndexedDbPostmasterStore } from '@vielzeug/postmaster/indexeddb';
|
|
18062
18314
|
import { s } from '@vielzeug/spell';
|
|
18063
18315
|
|
|
18064
|
-
const jobs =
|
|
18065
|
-
createTodo: {
|
|
18316
|
+
const jobs = {
|
|
18317
|
+
createTodo: defineJob({
|
|
18066
18318
|
version: 1,
|
|
18067
18319
|
validate: s.object({ id: s.string(), title: s.string() }),
|
|
18068
18320
|
key: (p) => p.id,
|
|
@@ -18074,8 +18326,8 @@ const jobs = defineJobs({
|
|
|
18074
18326
|
signal,
|
|
18075
18327
|
});
|
|
18076
18328
|
},
|
|
18077
|
-
},
|
|
18078
|
-
}
|
|
18329
|
+
}),
|
|
18330
|
+
};
|
|
18079
18331
|
|
|
18080
18332
|
const store = createIndexedDbPostmasterStore({ name: 'my-app-outbox' });
|
|
18081
18333
|
const postmaster = createPostmaster({ jobs, store });
|
|
@@ -18130,11 +18382,11 @@ yarn add @vielzeug/postmaster @vielzeug/vault
|
|
|
18130
18382
|
Define typed jobs, create a durable store, enqueue work, and start the processor. Dispose both the processor and the store when the page lifetime ends.
|
|
18131
18383
|
|
|
18132
18384
|
```ts
|
|
18133
|
-
import { createPostmaster,
|
|
18385
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
18134
18386
|
import { createIndexedDbPostmasterStore } from '@vielzeug/postmaster/indexeddb';
|
|
18135
18387
|
|
|
18136
|
-
const jobs =
|
|
18137
|
-
createTodo: {
|
|
18388
|
+
const jobs = {
|
|
18389
|
+
createTodo: defineJob({
|
|
18138
18390
|
version: 1,
|
|
18139
18391
|
validate: (v: unknown) => v as { id: string; title: string },
|
|
18140
18392
|
key: (p) => p.id,
|
|
@@ -18147,8 +18399,8 @@ const jobs = defineJobs({
|
|
|
18147
18399
|
});
|
|
18148
18400
|
},
|
|
18149
18401
|
retry: { maxAttempts: 5, shouldRetry: () => true },
|
|
18150
|
-
},
|
|
18151
|
-
}
|
|
18402
|
+
}),
|
|
18403
|
+
};
|
|
18152
18404
|
|
|
18153
18405
|
const store = createIndexedDbPostmasterStore({ name: 'my-app-outbox' });
|
|
18154
18406
|
const postmaster = createPostmaster({ jobs, store });
|
|
@@ -18163,7 +18415,7 @@ await store.dispose();
|
|
|
18163
18415
|
|
|
18164
18416
|
## Features
|
|
18165
18417
|
|
|
18166
|
-
- `
|
|
18418
|
+
- `defineJob()`: Types one job definition; the payload type comes from the validator (or an explicit `defineJob`) and flows into `execute`, `key`, and `enqueue`.
|
|
18167
18419
|
- `createPostmaster()`: Processor with leased claims, heartbeat renewal, and crash recovery.
|
|
18168
18420
|
- `enqueue()`: Persist a job and wake the processor, with optional delayed eligibility via `availableAt`.
|
|
18169
18421
|
- `flush()`: Process every available job until the queue is empty.
|
|
@@ -18193,7 +18445,7 @@ await store.dispose();
|
|
|
18193
18445
|
|
|
18194
18446
|
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
18195
18447
|
| ---------------------------------- | -------------------------------------- | -------------- | ---------------------------------------------------------------------- |
|
|
18196
|
-
| `
|
|
18448
|
+
| `defineJob()` | Types one job definition | Sync | Configuration is validated by `createPostmaster()` |
|
|
18197
18449
|
| `createPostmaster()` | Processor with leased claims and retry | Sync | Store is borrowed, not disposed with the processor |
|
|
18198
18450
|
| `createIndexedDbPostmasterStore()` | Durable browser store | Sync | Skips corrupt records and reports each issue through `onCorruptRecord` |
|
|
18199
18451
|
| `createMemoryPostmasterStore()` | Deterministic in-memory store | Sync | Use for tests only |
|
|
@@ -18210,29 +18462,29 @@ await store.dispose();
|
|
|
18210
18462
|
|
|
18211
18463
|
## Factories
|
|
18212
18464
|
|
|
18213
|
-
### `
|
|
18465
|
+
### `defineJob()`
|
|
18214
18466
|
|
|
18215
18467
|
```ts
|
|
18216
|
-
function
|
|
18468
|
+
function defineJob(spec: JobDefinition): JobDefinition;
|
|
18217
18469
|
```
|
|
18218
18470
|
|
|
18219
|
-
|
|
18471
|
+
Types a single job definition. The payload type comes from `validate` when TypeScript can read it without context: a named validator, a `{ parse(value) }` validator object such as a Spell schema, or an inline arrow with an annotated `unknown` parameter (an annotated `execute` payload works the same way). Otherwise pass the type argument (`defineJob({ ... })`) to stay independent of property order; with neither, payloads stay `unknown`. `createPostmaster()` validates every registered definition (versions, `execute`/`key`, retry `maxAttempts`, migration ranges) when it is constructed.
|
|
18220
18472
|
|
|
18221
|
-
| Parameter | Type
|
|
18222
|
-
| --------- |
|
|
18223
|
-
| `
|
|
18473
|
+
| Parameter | Type | Description |
|
|
18474
|
+
| --------- | ------------------ | --------------------------------- |
|
|
18475
|
+
| `spec` | `JobDefinition` | Definition with contextual typing |
|
|
18224
18476
|
|
|
18225
|
-
**Returns:**
|
|
18477
|
+
**Returns:** the same definition, typed for payload inference.
|
|
18226
18478
|
|
|
18227
18479
|
**Example**
|
|
18228
18480
|
|
|
18229
18481
|
```ts
|
|
18230
|
-
import {
|
|
18482
|
+
import { defineJob } from '@vielzeug/postmaster';
|
|
18231
18483
|
|
|
18232
|
-
const jobs =
|
|
18233
|
-
createTodo: {
|
|
18484
|
+
const jobs = {
|
|
18485
|
+
createTodo: defineJob({
|
|
18234
18486
|
version: 1,
|
|
18235
|
-
validate: (v) => v as { id: string; title: string },
|
|
18487
|
+
validate: (v: unknown) => v as { id: string; title: string },
|
|
18236
18488
|
key: (p) => p.id,
|
|
18237
18489
|
execute: async (payload, { key, signal }) => {
|
|
18238
18490
|
await fetch('/api/todos', {
|
|
@@ -18242,8 +18494,8 @@ const jobs = defineJobs({
|
|
|
18242
18494
|
signal,
|
|
18243
18495
|
});
|
|
18244
18496
|
},
|
|
18245
|
-
},
|
|
18246
|
-
}
|
|
18497
|
+
}),
|
|
18498
|
+
};
|
|
18247
18499
|
```
|
|
18248
18500
|
|
|
18249
18501
|
---
|
|
@@ -18258,7 +18510,7 @@ Returns a Postmaster processor that claims, executes, retries, and dead-letters
|
|
|
18258
18510
|
|
|
18259
18511
|
| Parameter | Type | Description |
|
|
18260
18512
|
| ----------------------- | ----------------- | -------------------------------------------------- |
|
|
18261
|
-
| `options.jobs` | `J` |
|
|
18513
|
+
| `options.jobs` | `J` | Map of job name to `defineJob()` definition |
|
|
18262
18514
|
| `options.store` | `PostmasterStore` | Borrowed store; not disposed with the processor |
|
|
18263
18515
|
| `options.leaseDuration` | `number` | Lease duration in ms (default 30000, minimum 1000) |
|
|
18264
18516
|
| `options.clock` | `() => number` | Deterministic clock for tests (default `Date.now`) |
|
|
@@ -18288,7 +18540,7 @@ await store.dispose();
|
|
|
18288
18540
|
function createIndexedDbPostmasterStore(options: IndexedDbPostmasterStoreOptions): PostmasterStore;
|
|
18289
18541
|
```
|
|
18290
18542
|
|
|
18291
|
-
Returns a durable Postmaster store backed by Vault IndexedDB. Uses one internal table
|
|
18543
|
+
Returns a durable Postmaster store backed by Vault IndexedDB. Uses one internal `jobs` table keyed by id; all operations run inside Vault transactions. Persisted records are validated before use; invalid records are skipped so they cannot block valid work.
|
|
18292
18544
|
|
|
18293
18545
|
| Parameter | Type | Description |
|
|
18294
18546
|
| ------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------- |
|
|
@@ -18705,11 +18957,11 @@ Thrown when a job definition is missing, a version is incompatible, or a migrati
|
|
|
18705
18957
|
Define typed jobs, create a durable store, enqueue work, and start the processor. Dispose both handles when the owner ends.
|
|
18706
18958
|
|
|
18707
18959
|
```ts
|
|
18708
|
-
import { createPostmaster,
|
|
18960
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
18709
18961
|
import { createIndexedDbPostmasterStore } from '@vielzeug/postmaster/indexeddb';
|
|
18710
18962
|
|
|
18711
|
-
const jobs =
|
|
18712
|
-
createTodo: {
|
|
18963
|
+
const jobs = {
|
|
18964
|
+
createTodo: defineJob({
|
|
18713
18965
|
version: 1,
|
|
18714
18966
|
validate: (v: unknown) => v as { id: string; title: string },
|
|
18715
18967
|
key: (p) => p.id,
|
|
@@ -18721,8 +18973,8 @@ const jobs = defineJobs({
|
|
|
18721
18973
|
signal,
|
|
18722
18974
|
});
|
|
18723
18975
|
},
|
|
18724
|
-
},
|
|
18725
|
-
}
|
|
18976
|
+
}),
|
|
18977
|
+
};
|
|
18726
18978
|
|
|
18727
18979
|
const store = createIndexedDbPostmasterStore({ name: 'my-app-outbox' });
|
|
18728
18980
|
const postmaster = createPostmaster({ jobs, store });
|
|
@@ -18742,8 +18994,8 @@ The store is borrowed by `createPostmaster()` and is not disposed with the proce
|
|
|
18742
18994
|
Postmaster provides **at-least-once delivery**. A crash after the remote write but before local completion can repeat the job. Every job must derive a stable idempotency key, and handlers must send or otherwise enforce that key.
|
|
18743
18995
|
|
|
18744
18996
|
```ts
|
|
18745
|
-
const jobs =
|
|
18746
|
-
createTodo: {
|
|
18997
|
+
const jobs = {
|
|
18998
|
+
createTodo: defineJob({
|
|
18747
18999
|
version: 1,
|
|
18748
19000
|
validate: (v: unknown) => v as { id: string; title: string },
|
|
18749
19001
|
key: (p) => p.id,
|
|
@@ -18755,8 +19007,8 @@ const jobs = defineJobs({
|
|
|
18755
19007
|
signal,
|
|
18756
19008
|
});
|
|
18757
19009
|
},
|
|
18758
|
-
},
|
|
18759
|
-
}
|
|
19010
|
+
}),
|
|
19011
|
+
};
|
|
18760
19012
|
```
|
|
18761
19013
|
|
|
18762
19014
|
Never assume exactly-once execution. Design handlers so a repeated delivery is safe.
|
|
@@ -18767,12 +19019,12 @@ Courier performs immediate HTTP transport. Postmaster coordinates durable delive
|
|
|
18767
19019
|
|
|
18768
19020
|
```ts
|
|
18769
19021
|
import { createCourier, CourierNetworkError } from '@vielzeug/courier';
|
|
18770
|
-
import { createPostmaster,
|
|
19022
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
18771
19023
|
|
|
18772
19024
|
const courier = createCourier({ baseUrl: 'https://api.example.com' });
|
|
18773
19025
|
|
|
18774
|
-
const jobs =
|
|
18775
|
-
createTodo: {
|
|
19026
|
+
const jobs = {
|
|
19027
|
+
createTodo: defineJob({
|
|
18776
19028
|
version: 1,
|
|
18777
19029
|
validate: (v: unknown) => v as { id: string; title: string },
|
|
18778
19030
|
key: (p) => p.id,
|
|
@@ -18785,8 +19037,8 @@ const jobs = defineJobs({
|
|
|
18785
19037
|
});
|
|
18786
19038
|
},
|
|
18787
19039
|
retry: { maxAttempts: 5, shouldRetry: (error) => error instanceof CourierNetworkError },
|
|
18788
|
-
},
|
|
18789
|
-
}
|
|
19040
|
+
}),
|
|
19041
|
+
};
|
|
18790
19042
|
```
|
|
18791
19043
|
|
|
18792
19044
|
Postmaster does not import Courier. The integration happens in your job definitions.
|
|
@@ -18798,8 +19050,8 @@ Each job declares a `version` and an optional `validate` function. When a stored
|
|
|
18798
19050
|
```ts
|
|
18799
19051
|
import { s } from '@vielzeug/spell';
|
|
18800
19052
|
|
|
18801
|
-
const jobs =
|
|
18802
|
-
createTodo: {
|
|
19053
|
+
const jobs = {
|
|
19054
|
+
createTodo: defineJob({
|
|
18803
19055
|
version: 2,
|
|
18804
19056
|
validate: s.object({ id: s.string(), title: s.string(), priority: s.number().optional() }),
|
|
18805
19057
|
key: (p) => p.id,
|
|
@@ -18814,8 +19066,8 @@ const jobs = defineJobs({
|
|
|
18814
19066
|
signal,
|
|
18815
19067
|
});
|
|
18816
19068
|
},
|
|
18817
|
-
},
|
|
18818
|
-
}
|
|
19069
|
+
}),
|
|
19070
|
+
};
|
|
18819
19071
|
```
|
|
18820
19072
|
|
|
18821
19073
|
Unknown job names, unsupported versions, failed migrations, `undefined` migration output, and invalid migrated payloads move to dead-letter rather than being executed.
|
|
@@ -18838,8 +19090,8 @@ The callback may omit `id` when the persisted value has no usable identifier. Ha
|
|
|
18838
19090
|
Retries are opt-in and explicitly classified. No `retry` block means one attempt followed by dead-letter.
|
|
18839
19091
|
|
|
18840
19092
|
```ts
|
|
18841
|
-
const jobs =
|
|
18842
|
-
syncTodo: {
|
|
19093
|
+
const jobs = {
|
|
19094
|
+
syncTodo: defineJob({
|
|
18843
19095
|
version: 1,
|
|
18844
19096
|
validate: (v: unknown) => v as { id: string },
|
|
18845
19097
|
key: (p) => p.id,
|
|
@@ -18850,8 +19102,8 @@ const jobs = defineJobs({
|
|
|
18850
19102
|
maxAttempts: 5,
|
|
18851
19103
|
shouldRetry: (error) => error instanceof TypeError, // network errors only
|
|
18852
19104
|
},
|
|
18853
|
-
},
|
|
18854
|
-
}
|
|
19105
|
+
}),
|
|
19106
|
+
};
|
|
18855
19107
|
```
|
|
18856
19108
|
|
|
18857
19109
|
- `maxAttempts` means total executions, including the first.
|
|
@@ -18939,19 +19191,19 @@ controller.abort(); // stops tapping
|
|
|
18939
19191
|
Use the in-memory store for deterministic tests.
|
|
18940
19192
|
|
|
18941
19193
|
```ts
|
|
18942
|
-
import { createPostmaster,
|
|
19194
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
18943
19195
|
import { createMemoryPostmasterStore } from '@vielzeug/postmaster/testing';
|
|
18944
19196
|
|
|
18945
19197
|
const store = createMemoryPostmasterStore();
|
|
18946
19198
|
const postmaster = createPostmaster({
|
|
18947
|
-
jobs:
|
|
18948
|
-
send: {
|
|
19199
|
+
jobs: {
|
|
19200
|
+
send: defineJob({
|
|
18949
19201
|
version: 1,
|
|
18950
19202
|
validate: (v: unknown) => String(v),
|
|
18951
19203
|
key: (p) => p,
|
|
18952
19204
|
execute: async () => {},
|
|
18953
|
-
},
|
|
18954
|
-
}
|
|
19205
|
+
}),
|
|
19206
|
+
},
|
|
18955
19207
|
store,
|
|
18956
19208
|
});
|
|
18957
19209
|
|
|
@@ -18973,19 +19225,19 @@ Create the Postmaster after the component mounts, start processing, and dispose
|
|
|
18973
19225
|
|
|
18974
19226
|
```tsx [React]
|
|
18975
19227
|
import { createIndexedDbPostmasterStore } from '@vielzeug/postmaster/indexeddb';
|
|
18976
|
-
import { createPostmaster,
|
|
19228
|
+
import { createPostmaster, defineJob, type Postmaster } from '@vielzeug/postmaster';
|
|
18977
19229
|
import { useEffect } from 'react';
|
|
18978
19230
|
|
|
18979
|
-
const jobs =
|
|
18980
|
-
sync: {
|
|
19231
|
+
const jobs = {
|
|
19232
|
+
sync: defineJob({
|
|
18981
19233
|
version: 1,
|
|
18982
19234
|
validate: (v: unknown) => v as { id: string },
|
|
18983
19235
|
key: (p) => p.id,
|
|
18984
19236
|
execute: async (payload, { signal }) => {
|
|
18985
19237
|
await fetch(`/api/sync/${payload.id}`, { signal });
|
|
18986
19238
|
},
|
|
18987
|
-
},
|
|
18988
|
-
}
|
|
19239
|
+
}),
|
|
19240
|
+
};
|
|
18989
19241
|
|
|
18990
19242
|
export function OutboxProvider() {
|
|
18991
19243
|
useEffect(() => {
|
|
@@ -19006,19 +19258,19 @@ export function OutboxProvider() {
|
|
|
19006
19258
|
```vue [Vue 3]
|
|
19007
19259
|
|
|
19008
19260
|
import { createIndexedDbPostmasterStore } from '@vielzeug/postmaster/indexeddb';
|
|
19009
|
-
import { createPostmaster,
|
|
19261
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
19010
19262
|
import { onMounted, onUnmounted } from 'vue';
|
|
19011
19263
|
|
|
19012
|
-
const jobs =
|
|
19013
|
-
sync: {
|
|
19264
|
+
const jobs = {
|
|
19265
|
+
sync: defineJob({
|
|
19014
19266
|
version: 1,
|
|
19015
19267
|
validate: (v: unknown) => v as { id: string },
|
|
19016
19268
|
key: (p) => p.id,
|
|
19017
19269
|
execute: async (payload, { signal }) => {
|
|
19018
19270
|
await fetch(`/api/sync/${payload.id}`, { signal });
|
|
19019
19271
|
},
|
|
19020
|
-
},
|
|
19021
|
-
}
|
|
19272
|
+
}),
|
|
19273
|
+
};
|
|
19022
19274
|
|
|
19023
19275
|
let postmaster: ReturnType | undefined;
|
|
19024
19276
|
let store: ReturnType | undefined;
|
|
@@ -19041,19 +19293,19 @@ onUnmounted(() => {
|
|
|
19041
19293
|
```svelte [Svelte]
|
|
19042
19294
|
|
|
19043
19295
|
import { createIndexedDbPostmasterStore } from '@vielzeug/postmaster/indexeddb';
|
|
19044
|
-
import { createPostmaster,
|
|
19296
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
19045
19297
|
import { onMount } from 'svelte';
|
|
19046
19298
|
|
|
19047
|
-
const jobs =
|
|
19048
|
-
sync: {
|
|
19299
|
+
const jobs = {
|
|
19300
|
+
sync: defineJob({
|
|
19049
19301
|
version: 1,
|
|
19050
19302
|
validate: (v: unknown) => v as { id: string },
|
|
19051
19303
|
key: (p) => p.id,
|
|
19052
19304
|
execute: async (payload, { signal }) => {
|
|
19053
19305
|
await fetch(`/api/sync/${payload.id}`, { signal });
|
|
19054
19306
|
},
|
|
19055
|
-
},
|
|
19056
|
-
}
|
|
19307
|
+
}),
|
|
19308
|
+
};
|
|
19057
19309
|
|
|
19058
19310
|
onMount(() => {
|
|
19059
19311
|
const store = createIndexedDbPostmasterStore({ name: 'outbox' });
|
|
@@ -19076,12 +19328,12 @@ Use Courier inside job handlers for HTTP transport. Postmaster coordinates deliv
|
|
|
19076
19328
|
|
|
19077
19329
|
```ts
|
|
19078
19330
|
import { createCourier, CourierNetworkError } from '@vielzeug/courier';
|
|
19079
|
-
import { createPostmaster,
|
|
19331
|
+
import { createPostmaster, defineJob } from '@vielzeug/postmaster';
|
|
19080
19332
|
|
|
19081
19333
|
const courier = createCourier({ baseUrl: 'https://api.example.com' });
|
|
19082
19334
|
|
|
19083
|
-
const jobs =
|
|
19084
|
-
createTodo: {
|
|
19335
|
+
const jobs = {
|
|
19336
|
+
createTodo: defineJob({
|
|
19085
19337
|
version: 1,
|
|
19086
19338
|
validate: (v: unknown) => v as { id: string; title: string },
|
|
19087
19339
|
key: (p) => p.id,
|
|
@@ -19094,8 +19346,8 @@ const jobs = defineJobs({
|
|
|
19094
19346
|
});
|
|
19095
19347
|
},
|
|
19096
19348
|
retry: { maxAttempts: 5, shouldRetry: (e) => e instanceof CourierNetworkError },
|
|
19097
|
-
},
|
|
19098
|
-
}
|
|
19349
|
+
}),
|
|
19350
|
+
};
|
|
19099
19351
|
```
|
|
19100
19352
|
|
|
19101
19353
|
### Postmaster + Sentinel
|
|
@@ -19146,7 +19398,7 @@ The IndexedDB adapter is built on Vault. Use Vault directly for unrelated storag
|
|
|
19146
19398
|
|
|
19147
19399
|
### REPL Examples
|
|
19148
19400
|
|
|
19149
|
-
-
|
|
19401
|
+
- defineJob - Basic Outbox (id: `define-jobs`)
|
|
19150
19402
|
- delayedEnqueue - Delayed Eligibility (id: `delayed-enqueue`)
|
|
19151
19403
|
|
|
19152
19404
|
---
|
|
@@ -21979,7 +22231,7 @@ Component registration happens through side-effect imports such as `@vielzeug/re
|
|
|
21979
22231
|
|
|
21980
22232
|
Each entry below is a component with its own documentation page and registration subpath. Sub-element tags (`ore-accordion-item`, `ore-card-picker-item`, `ore-tab-item`, `ore-avatar-group`, and the rest) are documented on their parent's page and registered with it.
|
|
21981
22233
|
|
|
21982
|
-
**Content:** `ore-accordion`, `ore-avatar`, `ore-card`, `ore-card-picker`, `ore-carousel`, `ore-chat-message`, `ore-chat-panel`, `ore-code-window`, `ore-copy-command`, `ore-icon`, `ore-keyboard-key`, `ore-list`, `ore-marquee`, `ore-qr-code`, `ore-rank-list`, `ore-speech-player`, `ore-speed-reading`, `ore-stats`, `ore-table`, `ore-text`
|
|
22234
|
+
**Content:** `ore-accordion`, `ore-avatar`, `ore-card`, `ore-card-picker`, `ore-carousel`, `ore-chat-message`, `ore-chat-panel`, `ore-code-window`, `ore-copy-command`, `ore-icon`, `ore-keyboard-key`, `ore-list`, `ore-marquee`, `ore-prose`, `ore-qr-code`, `ore-rank-list`, `ore-speech-player`, `ore-speed-reading`, `ore-stats`, `ore-table`, `ore-text`
|
|
21983
22235
|
|
|
21984
22236
|
**Feedback:** `ore-alert`, `ore-badge`, `ore-chip`, `ore-cookie-banner`, `ore-password-strength`, `ore-progress`, `ore-pull-to-refresh`, `ore-skeleton`, `ore-state`, `ore-toast`, `ore-typing-indicator`
|
|
21985
22237
|
|
|
@@ -22128,7 +22380,7 @@ import type { OreButtonProps } from '@vielzeug/refine/button';
|
|
|
22128
22380
|
|
|
22129
22381
|
| Area | Components |
|
|
22130
22382
|
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
22131
|
-
| Content | `accordion`, `avatar`, `card`, `card-picker`, `carousel`, `chat-message`, `chat-panel`, `code-window`, `copy-command`, `icon`, `keyboard-key`, `list`, `marquee`, `qr-code`, `rank-list`, `speech-player`, `speed-reading`, `stats`, `table`, `text`
|
|
22383
|
+
| Content | `accordion`, `avatar`, `card`, `card-picker`, `carousel`, `chat-message`, `chat-panel`, `code-window`, `copy-command`, `icon`, `keyboard-key`, `list`, `marquee`, `prose`, `qr-code`, `rank-list`, `speech-player`, `speed-reading`, `stats`, `table`, `text` |
|
|
22132
22384
|
| Feedback | `alert`, `badge`, `chip`, `cookie-banner`, `password-strength`, `progress`, `pull-to-refresh`, `skeleton`, `state`, `toast`, `typing-indicator` |
|
|
22133
22385
|
| Inputs | `app-store-button`, `button`, `calendar`, `checkbox`, `color-picker`, `combobox`, `counter`, `datagrid`, `date-picker`, `file-input`, `input`, `message-composer`, `number-input`, `otp-input`, `qr-scanner`, `query-bar`, `radio`, `rating`, `select`, `slider`, `switch`, `textarea`, `time-picker` |
|
|
22134
22386
|
| Layout | `box`, `dock`, `grid`, `navbar`, `separator`, `sidebar` |
|
|
@@ -26400,6 +26652,328 @@ Call `toFilterPredicate` again whenever the query or corpus changes: the predica
|
|
|
26400
26652
|
|
|
26401
26653
|
---
|
|
26402
26654
|
|
|
26655
|
+
## @vielzeug/scribe
|
|
26656
|
+
|
|
26657
|
+
**Category:** utilities
|
|
26658
|
+
|
|
26659
|
+
### Overview
|
|
26660
|
+
|
|
26661
|
+
## Why Scribe?
|
|
26662
|
+
|
|
26663
|
+
Rendering Markdown someone else wrote is a security decision. The usual stack pairs a parser
|
|
26664
|
+
that happily passes raw HTML through with a sanitizer bolted on afterward — one forgotten
|
|
26665
|
+
`innerHTML` and the bolt is worthless. Scribe makes safety a property of construction instead:
|
|
26666
|
+
raw HTML is **not** part of the language, text reaches the DOM only through
|
|
26667
|
+
`createTextNode`/`createElement`, and no attribute is ever sourced from the document except
|
|
26668
|
+
policy-checked `href`/`src`. There is no sanitizer step to forget because there is no unsafe
|
|
26669
|
+
path to take.
|
|
26670
|
+
|
|
26671
|
+
```ts
|
|
26672
|
+
// Before: parser + sanitizer + escape hatch
|
|
26673
|
+
import { marked } from 'marked';
|
|
26674
|
+
import DOMPurify from 'dompurify';
|
|
26675
|
+
container.innerHTML = DOMPurify.sanitize(marked.parse(userText)); // two libs, one memory
|
|
26676
|
+
|
|
26677
|
+
// After: one fixed-profile pipeline, safe by construction
|
|
26678
|
+
import { parseProse, renderProseDom } from '@vielzeug/scribe';
|
|
26679
|
+
container.replaceChildren(renderProseDom(parseProse(userText))); // zero deps, no innerHTML
|
|
26680
|
+
```
|
|
26681
|
+
|
|
26682
|
+
The profile is a fixed, deterministic GFM-flavored subset — headings, lists, code, tables,
|
|
26683
|
+
emphasis, links, images, autolinks, strikethrough — with deliberate, documented limits: no
|
|
26684
|
+
raw HTML, reference links, setext headings, entities, or plugin system. Chat bubbles, archive
|
|
26685
|
+
publications, and documentation excerpts are exactly the prose this covers.
|
|
26686
|
+
|
|
26687
|
+
## Installation
|
|
26688
|
+
|
|
26689
|
+
```sh [pnpm]
|
|
26690
|
+
pnpm add @vielzeug/scribe
|
|
26691
|
+
```
|
|
26692
|
+
|
|
26693
|
+
```sh [npm]
|
|
26694
|
+
npm install @vielzeug/scribe
|
|
26695
|
+
```
|
|
26696
|
+
|
|
26697
|
+
```sh [yarn]
|
|
26698
|
+
yarn add @vielzeug/scribe
|
|
26699
|
+
```
|
|
26700
|
+
|
|
26701
|
+
## Quick Start
|
|
26702
|
+
|
|
26703
|
+
```ts
|
|
26704
|
+
import { parseProse, proseOutline, renderProseHtml } from '@vielzeug/scribe';
|
|
26705
|
+
|
|
26706
|
+
const doc = parseProse('# Setup\n\nRun **install** first.\n\n## Configure\n\nEdit the config.');
|
|
26707
|
+
|
|
26708
|
+
console.log(renderProseHtml(doc, { headingIds: true }));
|
|
26709
|
+
// Setup
|
|
26710
|
+
// Run install first.
|
|
26711
|
+
// Configure
|
|
26712
|
+
// Edit the config.
|
|
26713
|
+
|
|
26714
|
+
console.log(proseOutline(doc)); // TOC ids match the ids above, exactly
|
|
26715
|
+
```
|
|
26716
|
+
|
|
26717
|
+
## Features
|
|
26718
|
+
|
|
26719
|
+
- **`parseProse`**: frozen, serializable AST from a fixed GFM-flavored profile — no raw HTML, no plugins, deterministic output.
|
|
26720
|
+
- **`renderProseHtml`**: escaped HTML string for SSR, static sites, and tests.
|
|
26721
|
+
- **`renderProseDom`**: `DocumentFragment` built with DOM APIs only — markup-lookalike content renders as visible characters.
|
|
26722
|
+
- **`proseToText`**: plain text for notifications, search indexing, and previews.
|
|
26723
|
+
- **`proseOutline`**: top-level headings with slug ids that match the renderers exactly.
|
|
26724
|
+
- **Policy-checked links**: relative/`http`/`https`/`mailto` pass, `javascript:`/`data:` degrade to label text with a dev warning — never a crash, never an anchor.
|
|
26725
|
+
- **Hard limits**: oversized or pathologically nested input fails fast with `ScribeLimitError` instead of hanging.
|
|
26726
|
+
|
|
26727
|
+
## Documentation
|
|
26728
|
+
|
|
26729
|
+
- [Usage Guide](./usage.md)
|
|
26730
|
+
- [API Reference](./api.md)
|
|
26731
|
+
- [Examples](./examples.md)
|
|
26732
|
+
|
|
26733
|
+
## See Also
|
|
26734
|
+
|
|
26735
|
+
- [Refine](/refine/): `ore-prose` renders Markdown with this pipeline and Refine typography.
|
|
26736
|
+
- [Archive](/archive/): publishes the prose that Scribe renders.
|
|
26737
|
+
- [Spell](/spell/): validation for the structured payloads around the prose.
|
|
26738
|
+
|
|
26739
|
+
### API Reference
|
|
26740
|
+
|
|
26741
|
+
## API Overview
|
|
26742
|
+
|
|
26743
|
+
| Symbol | Purpose | Execution | Common gotcha |
|
|
26744
|
+
| ----------------- | -------------------------------------------- | --------- | ------------------------------------------------------------------- |
|
|
26745
|
+
| `parseProse` | Markdown string → frozen `ProseDoc` AST | Sync | Fixed profile: raw HTML, entities, reference links are literal text |
|
|
26746
|
+
| `renderProseHtml` | AST → escaped HTML string | Sync | No heading `id`s unless `headingIds: true` |
|
|
26747
|
+
| `renderProseDom` | AST → `DocumentFragment` built with DOM APIs | Sync | Needs a DOM; pass the doc, not its blocks |
|
|
26748
|
+
| `proseToText` | AST → plain text | Sync | Links keep labels, images keep alt text |
|
|
26749
|
+
| `proseOutline` | Headings with ids, renderer order | Sync | Nested headings count in the slug sequence, matching the renderer |
|
|
26750
|
+
|
|
26751
|
+
## Package Entry Point
|
|
26752
|
+
|
|
26753
|
+
| Import | Purpose |
|
|
26754
|
+
| ------------------ | -------------------------- |
|
|
26755
|
+
| `@vielzeug/scribe` | Complete public Scribe API |
|
|
26756
|
+
|
|
26757
|
+
## Functions
|
|
26758
|
+
|
|
26759
|
+
### `parseProse(markdown, options?)`
|
|
26760
|
+
|
|
26761
|
+
Parses the fixed GFM-flavored profile (see the Usage Guide) into a frozen `ProseDoc`.
|
|
26762
|
+
Link/image destinations are policy-checked here: relative URLs always pass, `data:` always
|
|
26763
|
+
fails, other schemes require membership in `options.linkProtocols` (default
|
|
26764
|
+
`['http', 'https', 'mailto']`). A rejected destination becomes the label/alt text plus a
|
|
26765
|
+
dev-only warning — parsing never throws for a bad URL.
|
|
26766
|
+
|
|
26767
|
+
```ts
|
|
26768
|
+
const doc = parseProse('Read the [guide](/scribe/).');
|
|
26769
|
+
```
|
|
26770
|
+
|
|
26771
|
+
- **Throws** `ScribeLimitError` beyond 200,000 characters or 32 nesting levels.
|
|
26772
|
+
|
|
26773
|
+
### `renderProseHtml(doc, options?)` → `string`
|
|
26774
|
+
|
|
26775
|
+
Escapes every dynamic value; emits only the fixed tag set. `options.headingIds` adds unique
|
|
26776
|
+
slug ids matching `proseOutline`.
|
|
26777
|
+
|
|
26778
|
+
### `renderProseDom(doc, options?)` → `DocumentFragment`
|
|
26779
|
+
|
|
26780
|
+
DOM construction only (`createTextNode`/`createElement`/`setAttribute`): content can never
|
|
26781
|
+
execute. Requires a browser environment. Same options and id behavior as the string renderer.
|
|
26782
|
+
|
|
26783
|
+
### `proseToText(doc)` → `string`
|
|
26784
|
+
|
|
26785
|
+
Plain text: blocks separated by blank lines, list markers preserved, links reduced to labels.
|
|
26786
|
+
For notifications, search indexing, and previews.
|
|
26787
|
+
|
|
26788
|
+
### `proseOutline(doc, options?)` → `readonly ProseOutlineEntry[]`
|
|
26789
|
+
|
|
26790
|
+
Headings as `{ level, text, id }` in document order — the same traversal and slug sequence the
|
|
26791
|
+
renderers use with `headingIds`, including headings nested in blockquotes and lists.
|
|
26792
|
+
`options.maxLevel` (1–6) filters entries without shifting the slug sequence, so ids keep
|
|
26793
|
+
matching the rendered document.
|
|
26794
|
+
|
|
26795
|
+
## Types
|
|
26796
|
+
|
|
26797
|
+
The AST is public: safe to branch on, cache, and cross worker boundaries (frozen, serializable).
|
|
26798
|
+
|
|
26799
|
+
| Type | Purpose |
|
|
26800
|
+
| --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
|
|
26801
|
+
| `ProseDoc` | `{ blocks }`: the parsed document |
|
|
26802
|
+
| `ProseBlock` | Union of block nodes (paragraph, heading, list …) |
|
|
26803
|
+
| `ProseInline` | Union of inline nodes (text, link, codeSpan …) |
|
|
26804
|
+
| `ProseParagraph`, `ProseHeading`, `ProseCodeBlock`, `ProseBlockquote`, `ProseList`, `ProseListItem`, `ProseThematicBreak`, `ProseTable`, `ProseTableCell` | Block variants |
|
|
26805
|
+
| `ProseText`, `ProseCodeSpan`, `ProseStrong`, `ProseEmphasis`, `ProseStrikethrough`, `ProseLink`, `ProseImage`, `ProseSoftBreak`, `ProseHardBreak` | Inline variants |
|
|
26806
|
+
| `ProseParseOptions`, `ProseRenderOptions`, `ProseOutlineOptions` | Option bags |
|
|
26807
|
+
| `ProseOutlineEntry`, `ProseHeadingLevel`, `ProseAlignment` | Outline entry, `1–6`, table alignment |
|
|
26808
|
+
|
|
26809
|
+
## Errors
|
|
26810
|
+
|
|
26811
|
+
| Error | Thrown by | Meaning |
|
|
26812
|
+
| ------------------ | -------------- | ----------------------------------------------- |
|
|
26813
|
+
| `ScribeError` | — (base class) | Narrow with `instanceof` for any scribe failure |
|
|
26814
|
+
| `ScribeLimitError` | `parseProse` | Input exceeds the size or nesting limit |
|
|
26815
|
+
|
|
26816
|
+
### Usage Guide
|
|
26817
|
+
|
|
26818
|
+
## Basic Usage
|
|
26819
|
+
|
|
26820
|
+
Parse Markdown into a frozen AST once, then render it as many times as you like into any of
|
|
26821
|
+
four shapes:
|
|
26822
|
+
|
|
26823
|
+
```ts
|
|
26824
|
+
import { parseProse, proseOutline, proseToText, renderProseDom, renderProseHtml } from '@vielzeug/scribe';
|
|
26825
|
+
|
|
26826
|
+
const doc = parseProse('# Hello\n\nShip **today**.');
|
|
26827
|
+
|
|
26828
|
+
renderProseHtml(doc); // string (SSR, VitePress, archive publications)
|
|
26829
|
+
renderProseDom(doc); // DocumentFragment (client replaces, refine ore-prose)
|
|
26830
|
+
proseToText(doc); // plain text (search, notifications, a11y)
|
|
26831
|
+
proseOutline(doc); // [{ level: 1, text: 'Hello', id: 'hello' }]
|
|
26832
|
+
```
|
|
26833
|
+
|
|
26834
|
+
`renderProseDom` builds nodes exclusively with `document.createElement` and
|
|
26835
|
+
`document.createTextNode` — the DOM path cannot inject markup at all. It requires a live
|
|
26836
|
+
`document`; in Node use `renderProseHtml`.
|
|
26837
|
+
|
|
26838
|
+
## The Language Profile
|
|
26839
|
+
|
|
26840
|
+
Scribe implements a fixed CommonMark + GFM subset — the same on every platform and every
|
|
26841
|
+
release:
|
|
26842
|
+
|
|
26843
|
+
| Feature | Notes |
|
|
26844
|
+
| ------------ | ------------------------------------------------------------------------------------------------------------------------------- |
|
|
26845
|
+
| Headings | ATX (`#`–`######`) only; setext underlines render literally |
|
|
26846
|
+
| Emphasis | `*`, `**`, `***`, `_`, `__` with CommonMark flanking rules (`snake_case` is safe); `~~strikethrough~~` |
|
|
26847
|
+
| Code | Fenced (``` / `~~~`, info string preserved as `lang`), indented (4 spaces), backtick spans |
|
|
26848
|
+
| Blocks | Paragraphs, blockquotes, thematic breaks, hard breaks (`two spaces` or `\`) |
|
|
26849
|
+
| Lists | `-`/`+`/`*` bullets and `1.` ordered; strict last-marker nesting; simplified tight/loose rule |
|
|
26850
|
+
| Tables | GFM pipes with alignment row; a table must start on its own line |
|
|
26851
|
+
| Links/images | Inline links with optional titles, images with alt text; angle-bracket URI and email (`mailto:`) autolinks; bare `http(s)` URLs |
|
|
26852
|
+
| Task lists | `[ ]`/`[x]` items render a **disabled** checkbox (never interactive) |
|
|
26853
|
+
|
|
26854
|
+
Deliberately absent: raw HTML and entities (rendered as inert text), reference link
|
|
26855
|
+
definitions, setext headings, lazy list continuation, definition lists, footnotes, math.
|
|
26856
|
+
|
|
26857
|
+
## HTML and DOM Rendering
|
|
26858
|
+
|
|
26859
|
+
### Headings with ids
|
|
26860
|
+
|
|
26861
|
+
```ts
|
|
26862
|
+
import { parseProse, renderProseHtml } from '@vielzeug/scribe';
|
|
26863
|
+
|
|
26864
|
+
const doc = parseProse('# Guide\n\n# Guide');
|
|
26865
|
+
|
|
26866
|
+
renderProseHtml(doc, { headingIds: true });
|
|
26867
|
+
// GuideGuide
|
|
26868
|
+
```
|
|
26869
|
+
|
|
26870
|
+
`proseOutline` runs the same slugger over the full doc, so its `id` values always match the
|
|
26871
|
+
ids the renderer emits for the same document.
|
|
26872
|
+
|
|
26873
|
+
### DOM vs HTML
|
|
26874
|
+
|
|
26875
|
+
Both renderers produce identical structures. Choose by surface:
|
|
26876
|
+
|
|
26877
|
+
```ts
|
|
26878
|
+
// Node / static site: a string you embed in a page
|
|
26879
|
+
const html = renderProseHtml(parseProse(source), { headingIds: true });
|
|
26880
|
+
|
|
26881
|
+
// Browser: real nodes for replaceChildren — no innerHTML, no sanitizer needed
|
|
26882
|
+
article.replaceChildren(renderProseDom(parseProse(source), { headingIds: true }));
|
|
26883
|
+
```
|
|
26884
|
+
|
|
26885
|
+
## Link Policy
|
|
26886
|
+
|
|
26887
|
+
Every link destination and image src passes a protocol allowlist **after** control-character
|
|
26888
|
+
stripping and numeric entity decoding (so `:javascript:` degrades like the direct form):
|
|
26889
|
+
|
|
26890
|
+
```ts
|
|
26891
|
+
import { parseProse, renderProseHtml } from '@vielzeug/scribe';
|
|
26892
|
+
|
|
26893
|
+
const doc = parseProse('[a](javascript:alert(1)) [b](https://ok.test) [c](/relative)');
|
|
26894
|
+
|
|
26895
|
+
renderProseHtml(doc);
|
|
26896
|
+
// a b c
|
|
26897
|
+
// ↑ rejected link degraded to its label text
|
|
26898
|
+
```
|
|
26899
|
+
|
|
26900
|
+
Default allowlist is `http`, `https`, `mailto`; `data:` can never be allowed
|
|
26901
|
+
(`data:image/svg+xml` carries scripts). Relative and protocol-relative (`//host`)
|
|
26902
|
+
destinations always pass — they carry no scheme. Override with:
|
|
26903
|
+
|
|
26904
|
+
```ts
|
|
26905
|
+
parseProse(source, { linkProtocols: ['https'] });
|
|
26906
|
+
```
|
|
26907
|
+
|
|
26908
|
+
Degradation keeps the link **label** (or image **alt**) as plain text — content is never
|
|
26909
|
+
silently dropped — and a dev-mode warning names the rejected destination.
|
|
26910
|
+
|
|
26911
|
+
## Outline and Plain Text
|
|
26912
|
+
|
|
26913
|
+
```ts
|
|
26914
|
+
import { parseProse, proseOutline, proseToText } from '@vielzeug/scribe';
|
|
26915
|
+
|
|
26916
|
+
const doc = parseProse('# Intro\n\nText\n\n## Setup\n\nMore text.');
|
|
26917
|
+
|
|
26918
|
+
proseOutline(doc); // [{ level: 1, text: 'Intro', id: 'intro' }, …]
|
|
26919
|
+
proseOutline(doc, { maxLevel: 2 }); // shallow TOC for sidebars
|
|
26920
|
+
proseToText(doc); // "Intro\nText\nSetup\nMore text." for search & alerts
|
|
26921
|
+
```
|
|
26922
|
+
|
|
26923
|
+
Outline `id`s are produced by the same slugger the renderer uses with `headingIds`, so TOC
|
|
26924
|
+
anchors resolve against the rendered HTML with no extra bookkeeping. `proseToText` keeps code
|
|
26925
|
+
content and drops formatting, links, and images.
|
|
26926
|
+
|
|
26927
|
+
## Error Handling
|
|
26928
|
+
|
|
26929
|
+
Only two throw paths exist:
|
|
26930
|
+
|
|
26931
|
+
```ts
|
|
26932
|
+
import { parseProse, ScribeError, ScribeLimitError } from '@vielzeug/scribe';
|
|
26933
|
+
|
|
26934
|
+
try {
|
|
26935
|
+
parseProse(megabyteOfMarkdown); // > 200_000 characters
|
|
26936
|
+
} catch (error) {
|
|
26937
|
+
if (error instanceof ScribeLimitError) console.error(error.reason, error.limit);
|
|
26938
|
+
}
|
|
26939
|
+
```
|
|
26940
|
+
|
|
26941
|
+
`ScribeError` is the base class; `ScribeLimitError` covers the input size cap and the
|
|
26942
|
+
nesting-depth cap (32). Anything malformed degrades to literal text instead of throwing —
|
|
26943
|
+
unclosed emphasis, dangling fences, and broken tables all render as readable prose.
|
|
26944
|
+
|
|
26945
|
+
## Refine Integration
|
|
26946
|
+
|
|
26947
|
+
`@vielzeug/refine` ships [``](/refine/components/prose), which wraps this
|
|
26948
|
+
pipeline with Refine theme tokens:
|
|
26949
|
+
|
|
26950
|
+
```html
|
|
26951
|
+
|
|
26952
|
+
```
|
|
26953
|
+
|
|
26954
|
+
It re-emits `ScribeError` as an `error` event and falls back to the source's plain text.
|
|
26955
|
+
|
|
26956
|
+
## Best Practices
|
|
26957
|
+
|
|
26958
|
+
1. **Parse once, render many.** The AST is frozen; keep it and re-render instead of reparsing the same source.
|
|
26959
|
+
2. **`headingIds` on both sides.** When you build a TOC with `proseOutline`, enable `headingIds` in the renderer, or the anchors match nothing.
|
|
26960
|
+
3. **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]`
|
|
26961
|
+
4. **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.
|
|
26962
|
+
|
|
26963
|
+
### Examples
|
|
26964
|
+
|
|
26965
|
+
## Examples
|
|
26966
|
+
|
|
26967
|
+
- [Parse and Render](./examples/parse-and-render.md)
|
|
26968
|
+
- [Safe Rendering for Untrusted Content](./examples/safe-rendering.md)
|
|
26969
|
+
|
|
26970
|
+
### REPL Examples
|
|
26971
|
+
|
|
26972
|
+
- Outline and plain text (id: `outline`)
|
|
26973
|
+
- Safe render of hostile input (id: `safe-render`)
|
|
26974
|
+
|
|
26975
|
+
---
|
|
26976
|
+
|
|
26403
26977
|
## @vielzeug/scroll
|
|
26404
26978
|
|
|
26405
26979
|
**Category:** ui-performance
|
|
@@ -28892,7 +29466,7 @@ intersection.dispose();
|
|
|
28892
29466
|
### `createWakeLock()`
|
|
28893
29467
|
|
|
28894
29468
|
```ts
|
|
28895
|
-
function createWakeLock(options?:
|
|
29469
|
+
function createWakeLock(options?: WindowSentinelOptions): WakeLockSentinel;
|
|
28896
29470
|
```
|
|
28897
29471
|
|
|
28898
29472
|
Returns a Sentinel-backed screen wake lock. `request()` acquires the lock; `release()` frees it. When the tab is hidden the browser auto-releases the lock; the Sentinel re-acquires it automatically on `visibilitychange` if the lock was active. Degrades silently when the Screen Wake Lock API is unavailable.
|
|
@@ -28927,7 +29501,7 @@ wakeLock.dispose();
|
|
|
28927
29501
|
### `createFullscreen()`
|
|
28928
29502
|
|
|
28929
29503
|
```ts
|
|
28930
|
-
function createFullscreen(options?:
|
|
29504
|
+
function createFullscreen(options?: WindowSentinelOptions): FullscreenSentinel;
|
|
28931
29505
|
```
|
|
28932
29506
|
|
|
28933
29507
|
Returns a Sentinel-backed fullscreen view. `request()` enters fullscreen for an element (default: the document element), `exit()` leaves it, and `toggle()` flips it. All degrade silently when the Fullscreen API is missing or the browser refuses (user-activation requirements). Disposing the sentinel exits fullscreen and stops tracking `fullscreenchange`.
|
|
@@ -30242,7 +30816,7 @@ try {
|
|
|
30242
30816
|
|
|
30243
30817
|
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
30244
30818
|
| ----------------------------- | ----------------------------------- | -------------- | ----------------------------------------------------------- |
|
|
30245
|
-
| `createLocalSource()` | Filter and paginate in-memory items | Sync | `params` replacement
|
|
30819
|
+
| `createLocalSource()` | Filter and paginate in-memory items | Sync | `params` replacement compares structurally |
|
|
30246
30820
|
| `createPageSource()` | Load numbered pages | Async | Construction is inert |
|
|
30247
30821
|
| `createCursorSource()` | Load server-issued cursor pages | Async | `after` and `before` cannot coexist initially |
|
|
30248
30822
|
| `createInfiniteSource()` | Append numbered pages | Async | `loadMore()` is a no-op while loading or exhausted |
|
|
@@ -30299,7 +30873,7 @@ source.setParams('Ada');
|
|
|
30299
30873
|
| `previous()` | `void` | Move backward when available |
|
|
30300
30874
|
| `setItems(items)` | `void` | Replace the collection and recompute state |
|
|
30301
30875
|
| `setPageSize(pageSize)` | `void` | Replace page size and reset to page one |
|
|
30302
|
-
| `setParams(params)` | `void` | Replace params and reset to page one
|
|
30876
|
+
| `setParams(params)` | `void` | Replace params structurally and reset to page one |
|
|
30303
30877
|
| `subscribe(listener)` | `() => void` | Register a state listener and return its unsubscribe function |
|
|
30304
30878
|
| `dispose()` | `void` | Stop notifications and reject later mutations |
|
|
30305
30879
|
|
|
@@ -30344,13 +30918,18 @@ await source.reload();
|
|
|
30344
30918
|
| `subscribe(listener)` | `() => void` | Register a state listener and return its unsubscribe function |
|
|
30345
30919
|
| `dispose()` | `void` | Abort work and stop notifications |
|
|
30346
30920
|
|
|
30347
|
-
`apply(update: PageSourceUpdate): Promise` compares params structurally
|
|
30348
|
-
|
|
30349
|
-
|
|
30350
|
-
|
|
30351
|
-
|
|
30352
|
-
preserve the requested value; use `setParams(undefined)` when `undefined` is a valid
|
|
30353
|
-
The update does not include page size; use `setPageSize()` separately.
|
|
30921
|
+
`apply(update: PageSourceUpdate): Promise` compares params structurally after a
|
|
30922
|
+
reference fast path, the same rule every params comparison in the package uses. Changed params use
|
|
30923
|
+
the supplied positive page without clamping, or page one when omitted. Unchanged params with a page
|
|
30924
|
+
use `goTo()` and clamp after the first successful load. An unchanged request does not refetch a
|
|
30925
|
+
committed result or duplicate an active request; it loads an inert source. Omitted or `undefined`
|
|
30926
|
+
params preserve the requested value; use `setParams(undefined)` when `undefined` is a valid
|
|
30927
|
+
replacement. The update does not include page size; use `setPageSize()` separately.
|
|
30928
|
+
|
|
30929
|
+
All async sources share a rollback rule: a failed current request reverts the requested page, size,
|
|
30930
|
+
params, and (for infinite feeds) continuation position to the last committed values, so navigation
|
|
30931
|
+
after a failure retries the same move. Superseded work never rolls anything back. Retry with
|
|
30932
|
+
`reload()`.
|
|
30354
30933
|
|
|
30355
30934
|
---
|
|
30356
30935
|
|
|
@@ -30688,7 +31267,7 @@ console.log(source.state.params);
|
|
|
30688
31267
|
source.dispose();
|
|
30689
31268
|
```
|
|
30690
31269
|
|
|
30691
|
-
A non-optional parameter type requires an initial `params` value.
|
|
31270
|
+
A non-optional parameter type requires an initial `params` value. Every params comparison is structural after a reference fast path, so a freshly built but equal filter object never refetches, from `setParams()` or `apply()`. Idle sources load on the next command; retry a failed request with `reload()`. See [Apply Page and Filter Together](#apply-page-and-filter-together).
|
|
30692
31271
|
|
|
30693
31272
|
While replacement parameters load, `state.params` continues to describe the committed items and `state.pendingParams` contains the requested value. Page-only navigation does not set `pendingParams`.
|
|
30694
31273
|
|
|
@@ -30706,7 +31285,7 @@ await source.last();
|
|
|
30706
31285
|
await source.setPageSize(50);
|
|
30707
31286
|
```
|
|
30708
31287
|
|
|
30709
|
-
After the first successful load, navigation is clamped to the known `pageCount`. Before that load, `goTo()` accepts any positive page because the total is unknown.
|
|
31288
|
+
After the first successful load, navigation is clamped to the known `pageCount`. Before that load, `goTo()` accepts any positive page because the total is unknown. `next()` on an inert source loads page one. A failed navigation command rolls back to the committed page, so retrying `next()` moves to the same next page instead of skipping ahead.
|
|
30710
31289
|
|
|
30711
31290
|
## Apply Page and Filter Together
|
|
30712
31291
|
|
|
@@ -30739,8 +31318,8 @@ try {
|
|
|
30739
31318
|
```
|
|
30740
31319
|
|
|
30741
31320
|
Parameters are compared structurally, so a freshly built object with the same contents does not
|
|
30742
|
-
refetch a committed result or duplicate active work. An inert source still loads
|
|
30743
|
-
request
|
|
31321
|
+
refetch a committed result or duplicate active work. An inert source still loads; retry a failed
|
|
31322
|
+
request with `reload()`. When parameters change,
|
|
30744
31323
|
`page` is validated but never clamped: the page count still describes the previous filter set, so
|
|
30745
31324
|
clamping against it would silently move the reader elsewhere. Omit `page` in that case and the
|
|
30746
31325
|
source returns to page one. When parameters are unchanged, `apply()` routes through `goTo()` and
|
|
@@ -32073,6 +32652,331 @@ const profile = Profile.parse(await courier.get('/profile'));
|
|
|
32073
32652
|
|
|
32074
32653
|
---
|
|
32075
32654
|
|
|
32655
|
+
## @vielzeug/tabula
|
|
32656
|
+
|
|
32657
|
+
**Category:** utilities
|
|
32658
|
+
|
|
32659
|
+
### Overview
|
|
32660
|
+
|
|
32661
|
+
## Why Tabula?
|
|
32662
|
+
|
|
32663
|
+
CSV is the format every spreadsheet, analytics tool, and finance department speaks — and the
|
|
32664
|
+
format most hand-rolled parsers get subtly wrong: an embedded comma in a quoted title, a
|
|
32665
|
+
double-quote escape, a CRLF that silently becomes part of a value. Tabula implements RFC 4180
|
|
32666
|
+
exactly, with one scanner behind every entry point, so paste-box input, uploaded files, and
|
|
32667
|
+
Node streams all parse with identical semantics.
|
|
32668
|
+
|
|
32669
|
+
```ts
|
|
32670
|
+
// Before: a join that dies on the first comma inside a product name
|
|
32671
|
+
const rows = orders.map((o) => [o.id, o.title, o.total].join(',')); // title: "Red, Metallic" → corrupt
|
|
32672
|
+
|
|
32673
|
+
// After: quoting, CRLF, and escaping are the library's problem
|
|
32674
|
+
import { parseRecords, recordsToCsv } from '@vielzeug/tabula';
|
|
32675
|
+
|
|
32676
|
+
const csv = recordsToCsv(orders); // every field quoted only when needed, round-trips exactly
|
|
32677
|
+
```
|
|
32678
|
+
|
|
32679
|
+
Records are plain objects, and `parseTypedRecords` hands them straight to a
|
|
32680
|
+
[Spell](/spell/) standard schema — strings in, typed rows out, with per-line issues aggregated
|
|
32681
|
+
into one error. The streaming reader processes chunks and blobs without ever buffering the
|
|
32682
|
+
whole document.
|
|
32683
|
+
|
|
32684
|
+
## Installation
|
|
32685
|
+
|
|
32686
|
+
```sh [pnpm]
|
|
32687
|
+
pnpm add @vielzeug/tabula
|
|
32688
|
+
```
|
|
32689
|
+
|
|
32690
|
+
```sh [npm]
|
|
32691
|
+
npm install @vielzeug/tabula
|
|
32692
|
+
```
|
|
32693
|
+
|
|
32694
|
+
```sh [yarn]
|
|
32695
|
+
yarn add @vielzeug/tabula
|
|
32696
|
+
```
|
|
32697
|
+
|
|
32698
|
+
## Quick Start
|
|
32699
|
+
|
|
32700
|
+
```ts
|
|
32701
|
+
import { parseRecords, recordsToCsv } from '@vielzeug/tabula';
|
|
32702
|
+
|
|
32703
|
+
const grid = parseRecords('id,total\n7,"1,200.00"\n8,99.50\n');
|
|
32704
|
+
// [{ id: '7', total: '1,200.00' }, { id: '8', total: '99.50' }]
|
|
32705
|
+
|
|
32706
|
+
console.log(recordsToCsv([{ a: 1, b: 'x,y' }]));
|
|
32707
|
+
// a,b
|
|
32708
|
+
// 1,"x,y"
|
|
32709
|
+
```
|
|
32710
|
+
|
|
32711
|
+
## Features
|
|
32712
|
+
|
|
32713
|
+
- **`parseGrid`**: RFC 4180 scanner into a string grid — BOM stripped, CRLF/CR/LF endings, `""` escapes, configurable delimiter.
|
|
32714
|
+
- **`parseRecords`**: first row as keys (or your own `headers`), short rows omit keys instead of inventing `undefined`.
|
|
32715
|
+
- **Delimiter auto-detection**: `,`, `;`, and tab are counted outside quotes on the first line — no content sniffing, and pinning `delimiter` skips it.
|
|
32716
|
+
- **`toCsv` / `recordsToCsv`**: quotes only when needed, `quoteAll` for spreadsheet paranoia, CRLF by default.
|
|
32717
|
+
- **`createCsvGridStream`**: a `TransformStream` of rows for uploads and Node streams; even delimiter auto-detection buffers at most one line.
|
|
32718
|
+
- **`parseTypedRecords`**: rows through any Spell/standard-schema validator — one `TabulaValidationError` with every row's line number and issues.
|
|
32719
|
+
- **One scanner everywhere**: `CsvScanner` is push-based; sync parse, streams, and typed parsing share the exact same state machine.
|
|
32720
|
+
|
|
32721
|
+
## Documentation
|
|
32722
|
+
|
|
32723
|
+
- [Usage Guide](./usage.md)
|
|
32724
|
+
- [API Reference](./api.md)
|
|
32725
|
+
- [Examples](./examples.md)
|
|
32726
|
+
|
|
32727
|
+
## See Also
|
|
32728
|
+
|
|
32729
|
+
- [Spell](/spell/): the schema engine behind `parseTypedRecords`.
|
|
32730
|
+
- [Archive](/archive/): stores the files these rows came from.
|
|
32731
|
+
- [Tempo](/tempo/): parse and serialize the dates that live in CSV columns.
|
|
32732
|
+
|
|
32733
|
+
### API Reference
|
|
32734
|
+
|
|
32735
|
+
## API Overview
|
|
32736
|
+
|
|
32737
|
+
| Symbol | Purpose | Execution | Common gotcha |
|
|
32738
|
+
| --------------------- | ---------------------------------------------------- | --------- | -------------------------------------------------------------------- |
|
|
32739
|
+
| `parseGrid` | RFC 4180 text → string grid | Sync | Blank lines skipped unless `skipEmptyLines: false` |
|
|
32740
|
+
| `parseRecords` | First row (or `headers`) as keys | Sync | Short rows omit keys; extra cells are dropped |
|
|
32741
|
+
| `toCsv` | Grid → CSV text | Sync | CRLF by default; pass `newline: '\n'` for LF output |
|
|
32742
|
+
| `recordsToCsv` | Records → CSV text with column union | Sync | Without `columns`, order comes from first-seen keys |
|
|
32743
|
+
| `createCsvGridStream` | `TransformStream` for chunked text | Async | The header row is emitted like any other row |
|
|
32744
|
+
| `parseTypedRecords` | Records through a standard schema | Sync | Async schemas throw; failures aggregate into `TabulaValidationError` |
|
|
32745
|
+
| `CsvScanner` | Push-based state machine behind every parser | Sync | Call `finish()` after the last `push()`; auto-detects when unpinned |
|
|
32746
|
+
|
|
32747
|
+
## Package Entry Point
|
|
32748
|
+
|
|
32749
|
+
```ts
|
|
32750
|
+
import { parseGrid, parseRecords, recordsToCsv, toCsv } from '@vielzeug/tabula';
|
|
32751
|
+
```
|
|
32752
|
+
|
|
32753
|
+
## Functions
|
|
32754
|
+
|
|
32755
|
+
### parseGrid
|
|
32756
|
+
|
|
32757
|
+
```ts
|
|
32758
|
+
function parseGrid(text: string, options?: TabulaParseOptions): string[][];
|
|
32759
|
+
```
|
|
32760
|
+
|
|
32761
|
+
Parses CSV text into rows of cells. A leading BOM is stripped; `\r\n`, `\r`, and `\n` all
|
|
32762
|
+
terminate records; `""` inside quoted fields is an escaped quote; quotes inside unquoted
|
|
32763
|
+
fields are literal (spreadsheet producers emit them constantly). `delimiter` must be a single
|
|
32764
|
+
character and defaults to auto-detection: the scanner counts `,`, `;`, and tab outside quotes on
|
|
32765
|
+
the first line and takes the winner (ties go to `,`).
|
|
32766
|
+
|
|
32767
|
+
### parseRecords
|
|
32768
|
+
|
|
32769
|
+
```ts
|
|
32770
|
+
function parseRecords(text: string, options?: TabulaRecordOptions): Record[];
|
|
32771
|
+
```
|
|
32772
|
+
|
|
32773
|
+
Reads the first row as headers unless `headers` is supplied (then the first row is data).
|
|
32774
|
+
Extra cells beyond the header are dropped; missing cells leave the key off the record.
|
|
32775
|
+
Empty `headers` throws `TabulaParseError`.
|
|
32776
|
+
|
|
32777
|
+
### toCsv
|
|
32778
|
+
|
|
32779
|
+
```ts
|
|
32780
|
+
function toCsv(rows: Iterable, options?: TabulaSerializeOptions): string;
|
|
32781
|
+
```
|
|
32782
|
+
|
|
32783
|
+
Serializes a grid. Fields are quoted only when they contain the delimiter, a quote, `\r`,
|
|
32784
|
+
`\n`, or leading/trailing spaces — or when `quoteAll` is set. `null`/`undefined` become empty
|
|
32785
|
+
cells; other values go through `String()`. Lines end with `\r\n` unless `newline` says
|
|
32786
|
+
otherwise.
|
|
32787
|
+
|
|
32788
|
+
### recordsToCsv
|
|
32789
|
+
|
|
32790
|
+
```ts
|
|
32791
|
+
function recordsToCsv(records: Iterable>, options?: TabulaRecordSerializeOptions): string;
|
|
32792
|
+
```
|
|
32793
|
+
|
|
32794
|
+
Writes a header row plus one row per record. Columns are `options.columns` or the first-seen
|
|
32795
|
+
union of record keys. Missing keys serialize as empty cells.
|
|
32796
|
+
|
|
32797
|
+
### createCsvGridStream
|
|
32798
|
+
|
|
32799
|
+
```ts
|
|
32800
|
+
function createCsvGridStream(options?: TabulaParseOptions): TransformStream;
|
|
32801
|
+
```
|
|
32802
|
+
|
|
32803
|
+
Transforms streamed text into completed rows. Until the first newline arrives (needed for
|
|
32804
|
+
delimiter auto-detection unless `delimiter` is pinned) input is buffered by the scanner; after
|
|
32805
|
+
that rows are emitted as they complete.
|
|
32806
|
+
|
|
32807
|
+
### parseTypedRecords
|
|
32808
|
+
|
|
32809
|
+
```ts
|
|
32810
|
+
function parseTypedRecords(
|
|
32811
|
+
text: string,
|
|
32812
|
+
schema: StandardSchemaV1, T>,
|
|
32813
|
+
options?: TabulaRecordOptions,
|
|
32814
|
+
): T[];
|
|
32815
|
+
```
|
|
32816
|
+
|
|
32817
|
+
Validates every record through `schema['~standard'].validate`. Valid rows accumulate;
|
|
32818
|
+
invalid rows produce a `TabulaRowError` with the row's 1-based physical line number, exactly
|
|
32819
|
+
as a spreadsheet would show it. All rows are attempted, then failures throw as one `TabulaValidationError`.
|
|
32820
|
+
|
|
32821
|
+
### CsvScanner
|
|
32822
|
+
|
|
32823
|
+
```ts
|
|
32824
|
+
class CsvScanner {
|
|
32825
|
+
constructor(options?: TabulaParseOptions);
|
|
32826
|
+
push(text: string, onRow: (row: string[], line: number) => void): void;
|
|
32827
|
+
finish(onRow: (row: string[], line: number) => void): void;
|
|
32828
|
+
}
|
|
32829
|
+
```
|
|
32830
|
+
|
|
32831
|
+
The push-based state machine every parser shares — split a fetch body however you like and
|
|
32832
|
+
semantics stay identical. Without a pinned `delimiter` it holds input until the first line
|
|
32833
|
+
completes, auto-detects, and starts emitting. `push` may be called with any chunk boundary,
|
|
32834
|
+
mid-quote included.
|
|
32835
|
+
Each row arrives with the 1-based physical line it started on (quoted newlines and blank
|
|
32836
|
+
lines included), which is what `TabulaRowError.line` reports.
|
|
32837
|
+
|
|
32838
|
+
## Types
|
|
32839
|
+
|
|
32840
|
+
| Type | Purpose |
|
|
32841
|
+
| ------------------------------ | -------------------------------------------------- |
|
|
32842
|
+
| `TabulaOptions` | `{ delimiter? }` shared by parsers and serializers |
|
|
32843
|
+
| `TabulaParseOptions` | `+ { skipEmptyLines? }` (default `true`) |
|
|
32844
|
+
| `TabulaRecordOptions` | `+ { headers? }` for headerless documents |
|
|
32845
|
+
| `TabulaSerializeOptions` | `{ delimiter?, quoteAll?, newline? }` |
|
|
32846
|
+
| `TabulaRecordSerializeOptions` | `+ { columns? }` for explicit column order |
|
|
32847
|
+
|
|
32848
|
+
## Errors
|
|
32849
|
+
|
|
32850
|
+
| Error | Thrown when |
|
|
32851
|
+
| ----------------------- | --------------------------------------------------------------------------------- |
|
|
32852
|
+
| `TabulaError` | Base class for every tabula error |
|
|
32853
|
+
| `TabulaParseError` | A request cannot be honored (`headers: []`, multi-char `delimiter`, async schema) |
|
|
32854
|
+
| `TabulaRowError` | One row failed schema validation (`line`, `issues`) |
|
|
32855
|
+
| `TabulaValidationError` | Typed parse finished with any invalid rows (`errors: TabulaRowError[]`) |
|
|
32856
|
+
|
|
32857
|
+
### Usage Guide
|
|
32858
|
+
|
|
32859
|
+
## Basic Usage
|
|
32860
|
+
|
|
32861
|
+
Everything is strings in, strings out — CSV has no types, and tabula does not pretend
|
|
32862
|
+
otherwise. Parse to a grid when you need positional access, or to records when the first row
|
|
32863
|
+
is a header:
|
|
32864
|
+
|
|
32865
|
+
```ts
|
|
32866
|
+
import { parseGrid, parseRecords } from '@vielzeug/tabula';
|
|
32867
|
+
|
|
32868
|
+
parseGrid('a,b\n"x,y",z\n');
|
|
32869
|
+
// [['a', 'b'], ['x,y', 'z']]
|
|
32870
|
+
|
|
32871
|
+
parseRecords('id,total\n7,"1,200.00"\n');
|
|
32872
|
+
// [{ id: '7', total: '1,200.00' }]
|
|
32873
|
+
```
|
|
32874
|
+
|
|
32875
|
+
A few parser behaviors worth knowing because every hand-rolled parser gets them wrong:
|
|
32876
|
+
|
|
32877
|
+
- A BOM is stripped, and `\r\n`, `\r`, and `\n` all end a record.
|
|
32878
|
+
- `""` inside a quoted field is an escaped quote; fields are quoted only as needed on output.
|
|
32879
|
+
- A row longer than the header is truncated to the header; a shorter row simply omits keys
|
|
32880
|
+
(no surprise `undefined` values in your records).
|
|
32881
|
+
- Blank lines are skipped by default; pass `skipEmptyLines: false` to keep them as `['']`.
|
|
32882
|
+
|
|
32883
|
+
## Delimiter Detection
|
|
32884
|
+
|
|
32885
|
+
Every parse entry point auto-detects the delimiter unless you pin one: the scanner counts `,`,
|
|
32886
|
+
`;`, and tab occurrences outside quotes on the first line and takes the winner (ties go to `,`).
|
|
32887
|
+
A paste box and an uploaded `.csv` both just work:
|
|
32888
|
+
|
|
32889
|
+
```ts
|
|
32890
|
+
import { parseGrid } from '@vielzeug/tabula';
|
|
32891
|
+
|
|
32892
|
+
parseGrid('a;b\n1;2\n'); // German Excel export: delimiter is ';'
|
|
32893
|
+
```
|
|
32894
|
+
|
|
32895
|
+
Pin `delimiter` whenever the source is known — it is faster (the parser never counts) and it
|
|
32896
|
+
makes a stray comma in a title harmless.
|
|
32897
|
+
|
|
32898
|
+
## Serializing
|
|
32899
|
+
|
|
32900
|
+
`toCsv` writes a grid; `recordsToCsv` writes records, taking the column order from explicit
|
|
32901
|
+
`columns` or from the first-seen key order. Fields are quoted only when they contain the
|
|
32902
|
+
delimiter, a quote, a newline, or leading/trailing spaces:
|
|
32903
|
+
|
|
32904
|
+
```ts
|
|
32905
|
+
import { recordsToCsv, toCsv } from '@vielzeug/tabula';
|
|
32906
|
+
|
|
32907
|
+
toCsv([['note'], ['said "hi"']]);
|
|
32908
|
+
// note\r\n"said ""hi"""
|
|
32909
|
+
|
|
32910
|
+
recordsToCsv([{ b: 2, a: 1 }], { columns: ['a', 'b'], newline: '\n' });
|
|
32911
|
+
// a,b\n1,2
|
|
32912
|
+
```
|
|
32913
|
+
|
|
32914
|
+
`null` and `undefined` serialize as empty cells; everything else goes through `String()`.
|
|
32915
|
+
Use `quoteAll: true` when the consumer is a spreadsheet import wizard that guesses column
|
|
32916
|
+
types from the first rows.
|
|
32917
|
+
|
|
32918
|
+
## Streaming
|
|
32919
|
+
|
|
32920
|
+
`createCsvGridStream` is a `TransformStream`: pipe a text stream through it
|
|
32921
|
+
and consume rows as they complete. Even when auto-detecting the delimiter it buffers at most
|
|
32922
|
+
one line, so gigabyte exports never touch memory:
|
|
32923
|
+
|
|
32924
|
+
```ts
|
|
32925
|
+
import { createCsvGridStream } from '@vielzeug/tabula';
|
|
32926
|
+
|
|
32927
|
+
const rows = file.stream().pipeThrough(new TextDecoderStream()).pipeThrough(createCsvGridStream());
|
|
32928
|
+
for await (const row of rows) consume(row);
|
|
32929
|
+
```
|
|
32930
|
+
|
|
32931
|
+
The header row is emitted like any other row — decide what to do with it at the consumer.
|
|
32932
|
+
|
|
32933
|
+
## Typed Rows
|
|
32934
|
+
|
|
32935
|
+
`parseTypedRecords` runs every record through a Spell (or any standard-schema) validator and
|
|
32936
|
+
aggregates failures: one `TabulaValidationError` carrying a `TabulaRowError` per bad row with
|
|
32937
|
+
its 1-based line number, so a broken export is reported in full rather than at the first bad
|
|
32938
|
+
cell.
|
|
32939
|
+
|
|
32940
|
+
```ts
|
|
32941
|
+
import { s } from '@vielzeug/spell';
|
|
32942
|
+
import { parseTypedRecords } from '@vielzeug/tabula';
|
|
32943
|
+
|
|
32944
|
+
const orderSchema = s.object({ id: s.string(), qty: s.coerce.number() });
|
|
32945
|
+
const orders = parseTypedRecords(text, orderSchema); // qty arrives as a number
|
|
32946
|
+
```
|
|
32947
|
+
|
|
32948
|
+
Schema validation must be synchronous; an async schema throws a `TypeError` immediately
|
|
32949
|
+
rather than half-parsing the file.
|
|
32950
|
+
|
|
32951
|
+
## Error Handling
|
|
32952
|
+
|
|
32953
|
+
All errors extend `TabulaError`. Parsing is deliberately forgiving of stray quotes
|
|
32954
|
+
(spreadsheet producers emit them constantly), so `TabulaParseError` fires only on requests
|
|
32955
|
+
that cannot be honored, such as `headers: []`. Row-level validation failures arrive as one
|
|
32956
|
+
`TabulaValidationError` whose `errors` lists a `TabulaRowError` per bad line — report those
|
|
32957
|
+
per line, not as one opaque message.
|
|
32958
|
+
|
|
32959
|
+
## Best Practices
|
|
32960
|
+
|
|
32961
|
+
- Pin `delimiter` and `quote` when the producer is known; auto-detect only for paste boxes and unknown uploads.
|
|
32962
|
+
- Feed user imports through `parseTypedRecords` with Spell schemas — CSV hands you strings, and the coercion is where bugs live.
|
|
32963
|
+
- Serialize with `recordsToCsv` and explicit `columns` for exports; key insertion order is accidental API otherwise.
|
|
32964
|
+
- For files larger than a few MB, stream: `createCsvGridStream` keeps memory flat and shares the exact scanner semantics of `parseGrid`.
|
|
32965
|
+
|
|
32966
|
+
### Examples
|
|
32967
|
+
|
|
32968
|
+
## Examples
|
|
32969
|
+
|
|
32970
|
+
- [Parse and Serialize](./examples/parse-and-serialize.md)
|
|
32971
|
+
- [Typed Import Pipeline](./examples/typed-imports.md)
|
|
32972
|
+
|
|
32973
|
+
### REPL Examples
|
|
32974
|
+
|
|
32975
|
+
- Parse - Delimiters, quoting, records (id: `parse-basic`)
|
|
32976
|
+
- Serialize - Safe quoting and delimiters (id: `serialize-basic`)
|
|
32977
|
+
|
|
32978
|
+
---
|
|
32979
|
+
|
|
32076
32980
|
## @vielzeug/tandem
|
|
32077
32981
|
|
|
32078
32982
|
**Category:** sync
|
|
@@ -32633,12 +33537,11 @@ bus.on('subject:updated', () => {
|
|
|
32633
33537
|
|
|
32634
33538
|
// After: tavern owns the protocol, the validation, the broadcasting.
|
|
32635
33539
|
const host = hostTavern({
|
|
32636
|
-
commands: {
|
|
32637
|
-
|
|
32638
|
-
|
|
32639
|
-
|
|
32640
|
-
|
|
32641
|
-
snapshot: () => store.read('doc-1'),
|
|
33540
|
+
commands: { rename: (args) => store.rename(docId, args[0] as string) },
|
|
33541
|
+
subject: {
|
|
33542
|
+
onChanged: (listener) => store.onUpdated(docId, listener),
|
|
33543
|
+
onRemoved: (listener) => store.onRemoved(docId, listener),
|
|
33544
|
+
snapshot: () => store.read(docId),
|
|
32642
33545
|
},
|
|
32643
33546
|
});
|
|
32644
33547
|
```
|
|
@@ -32675,33 +33578,36 @@ yarn add @vielzeug/tavern
|
|
|
32675
33578
|
```ts
|
|
32676
33579
|
import { hostTavern, joinTavern } from '@vielzeug/tavern';
|
|
32677
33580
|
|
|
32678
|
-
// Host:
|
|
33581
|
+
// Host: wire the command table and snapshot access for the shared subject.
|
|
32679
33582
|
const host = hostTavern({
|
|
32680
33583
|
commands: {
|
|
32681
|
-
|
|
32682
|
-
|
|
33584
|
+
rename: (args) => myStore.rename(docId, args[0] as string),
|
|
33585
|
+
append: (args) => myStore.append(docId, args[0] as string),
|
|
32683
33586
|
},
|
|
32684
|
-
|
|
32685
|
-
|
|
32686
|
-
|
|
32687
|
-
|
|
32688
|
-
snapshot: () => myStore.read('doc-1'),
|
|
33587
|
+
subject: {
|
|
33588
|
+
onChanged: (listener) => myStore.onUpdated(docId, listener),
|
|
33589
|
+
onRemoved: (listener) => myStore.onRemoved(docId, listener),
|
|
33590
|
+
snapshot: () => myStore.read(docId),
|
|
32689
33591
|
},
|
|
32690
33592
|
});
|
|
32691
33593
|
|
|
32692
|
-
// Produce a single-use invitation; deliver it out-of-band (QR, copy/paste).
|
|
32693
|
-
const
|
|
33594
|
+
// Produce a single-use invitation code; deliver it out-of-band (QR, copy/paste).
|
|
33595
|
+
const invitationCode = await host.createInvitationCode();
|
|
32694
33596
|
|
|
32695
|
-
// Guest: consume the invitation, produce an answer for the host.
|
|
32696
|
-
const {
|
|
32697
|
-
|
|
33597
|
+
// Guest: consume the invitation code, produce an answer code for the host.
|
|
33598
|
+
const { answerCode, guest, ready } = await joinTavern({
|
|
33599
|
+
invitationCode,
|
|
32698
33600
|
mount: (snapshot) => parseAndMount(snapshot),
|
|
32699
33601
|
name: 'Alex',
|
|
32700
33602
|
});
|
|
32701
|
-
await host.
|
|
33603
|
+
await host.acceptAnswerCode(answerCode);
|
|
32702
33604
|
|
|
32703
|
-
//
|
|
32704
|
-
|
|
33605
|
+
// `ready` settles once the first snapshot arrives and mounts: the mirror is live.
|
|
33606
|
+
await ready;
|
|
33607
|
+
|
|
33608
|
+
// The guest's commands run through the host's own table; their effect
|
|
33609
|
+
// arrives with the next snapshot, so a successful command needs no ack.
|
|
33610
|
+
guest.sendCommand('rename', ['Quarterly report']);
|
|
32705
33611
|
|
|
32706
33612
|
// Cleanup: hosting ends for every guest; onEnded fires exactly once on both sides.
|
|
32707
33613
|
host.dispose();
|
|
@@ -32711,9 +33617,9 @@ guest.dispose();
|
|
|
32711
33617
|
## Features
|
|
32712
33618
|
|
|
32713
33619
|
- **`hostTavern`**: host one subject: pairing, protocol validation, command application, coalesced snapshot broadcasts
|
|
32714
|
-
- **`joinTavern`**: join as a guest: consume the invitation, produce the answer, mirror the host's snapshots
|
|
32715
|
-
- **`TavernCommands`**: the host's command table: the same
|
|
32716
|
-
- **`
|
|
33620
|
+
- **`joinTavern`**: join as a guest: consume the invitation code, produce the answer code, mirror the host's snapshots
|
|
33621
|
+
- **`TavernCommands`**: the host's command table as a plain record of handlers: the same functions the host's own UI calls, so remote actions cannot bypass validation
|
|
33622
|
+
- **`ready` promise**: the join lifecycle is awaitable: `ready` resolves with the mounted mirror or rejects with why the session never came up
|
|
32717
33623
|
- **Coalesced snapshots**: bursts of local changes ship one snapshot per microtask, not one per change
|
|
32718
33624
|
- **`onEnded` fires exactly once**: on both handles: channel drops, subject removal, and explicit disposal share a single idempotent cleanup path
|
|
32719
33625
|
- **Typed errors**: `TavernPairingError` covers every unusable pasted code with the mesh failure chained as `cause`
|
|
@@ -32737,38 +33643,40 @@ guest.dispose();
|
|
|
32737
33643
|
| Symbol | Purpose | Execution | Common gotcha |
|
|
32738
33644
|
| --------------------- | ---------------------------------------------------------------------------- | ------------ | ---------------------------------------------------------------------------------- |
|
|
32739
33645
|
| `hostTavern()` | Host a subject: pairing, command validation, snapshot broadcast | Sync factory | Disposing ends hosting for every guest |
|
|
32740
|
-
| `joinTavern()` | Join a session: consume invitation, produce answer
|
|
33646
|
+
| `joinTavern()` | Join a session: consume invitation code, produce answer code | Async | The session lives only after the host accepts and the first snapshot mounts |
|
|
32741
33647
|
| `TavernHost` | Host handle: invitation, answer acceptance, kick, notice relay, presence tap | N/A | `dispose()` is idempotent; control-plane methods throw `TavernDisposedError` after |
|
|
32742
33648
|
| `TavernGuest` | Guest handle: command forwarding, rejection tap, disposal | N/A | `dispose()` fires `onEnded` exactly once |
|
|
32743
|
-
| `
|
|
32744
|
-
| `
|
|
32745
|
-
| `
|
|
32746
|
-
| `
|
|
32747
|
-
| `
|
|
33649
|
+
| `TavernJoinResult` | Join outcome: answer code, guest handle, and the `ready` promise | N/A | A `ready` nobody awaits never surfaces as an unhandled rejection |
|
|
33650
|
+
| `TavernHostEvent` | Host observability union for `tap()`: presence, warnings, dispose | N/A | Lifecycle transitions are `onEnded`, not events |
|
|
33651
|
+
| `TavernGuestEvent` | Guest observability union for `tap()`: rejections, warnings, dispose | N/A | The opening transition is `ready`, not an event |
|
|
33652
|
+
| `TavernCommands` | The host's command table: a record of handlers keyed by command name | N/A | A name the record does not hold rejects without applying |
|
|
33653
|
+
| `TavernSubject` | Snapshot reading, change and removal subscriptions | N/A | `snapshot` returning `null` skips the broadcast |
|
|
32748
33654
|
| `TavernError` | Base error for every Tavern failure | N/A | N/A |
|
|
32749
33655
|
| `TavernPairingError` | The consumer pasted the wrong kind of pairing code | N/A | N/A |
|
|
32750
33656
|
| `TavernDisposedError` | A stopped host or ended guest was used again | N/A | N/A |
|
|
32751
33657
|
|
|
32752
33658
|
## Package Entry Point
|
|
32753
33659
|
|
|
32754
|
-
| Import
|
|
32755
|
-
|
|
|
32756
|
-
| `@vielzeug/tavern`
|
|
33660
|
+
| Import | Purpose |
|
|
33661
|
+
| -------------------------- | ----------------------------------------------- |
|
|
33662
|
+
| `@vielzeug/tavern` | Complete public Tavern API |
|
|
33663
|
+
| `@vielzeug/tavern/testing` | Test seam: the fake WebRTC factory for sessions |
|
|
33664
|
+
|
|
33665
|
+
The `MeshPeer` type carried by host events and the `peers` getter is re-exported here, so a single import types everything.
|
|
32757
33666
|
|
|
32758
33667
|
## `hostTavern(options)`
|
|
32759
33668
|
|
|
32760
|
-
Creates a mesh host for one subject. Guest commands are validated against the wire shape (Tavern's own protocol)
|
|
33669
|
+
Creates a mesh host for one subject. Guest commands are validated against the wire shape (Tavern's own protocol) and checked against `commands`: a name the table does not hold rejects without applying, and a handler that throws rejects the guest with the error's message. Declaring `subject.id` makes the session _named_: every guest command must name that id as `sendCommand`'s `target`, and a command that omits or misses it rejects before the table runs. Local changes (via `subject.onChanged`) re-broadcast `subject.snapshot()`: coalesced on a microtask; `subject.onRemoved` ends hosting. Presence and transport warnings are reported through `tap()` as `TavernHostEvent`s, and the live peer list is the `peers` getter; hosting ending: from removal or `dispose()`: fires `onEnded` exactly once. `relayNotice` serializes through `serializeNotice` and broadcasts to every guest.
|
|
32761
33670
|
|
|
32762
33671
|
**Returns:** `TavernHost`: the host handle.
|
|
32763
33672
|
|
|
32764
|
-
| Option
|
|
32765
|
-
|
|
|
32766
|
-
| `commands
|
|
32767
|
-
| `
|
|
32768
|
-
| `
|
|
32769
|
-
| `
|
|
32770
|
-
| `
|
|
32771
|
-
| `subjects` | `TavernSubjects` | Snapshot reading, change and removal subscriptions |
|
|
33673
|
+
| Option | Type | Description |
|
|
33674
|
+
| ------------------ | ----------------------------- | ----------------------------------------------------------------------------- |
|
|
33675
|
+
| `commands?` | `TavernCommands` | The command table guest actions run through; omit for a read-only session |
|
|
33676
|
+
| `onEnded?` | `() => void` | Hosting ended: the subject was removed or `dispose()` ran. Fires exactly once |
|
|
33677
|
+
| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |
|
|
33678
|
+
| `serializeNotice?` | `(notice) => unknown \| null` | Serializes a local notice for `relayNotice`; null skips that notice |
|
|
33679
|
+
| `subject` | `TavernSubject` | Snapshot reading, change and removal subscriptions for the hosted subject |
|
|
32772
33680
|
|
|
32773
33681
|
**Example**
|
|
32774
33682
|
|
|
@@ -32777,239 +33685,196 @@ import { hostTavern } from '@vielzeug/tavern';
|
|
|
32777
33685
|
|
|
32778
33686
|
const host = hostTavern({
|
|
32779
33687
|
commands: {
|
|
32780
|
-
|
|
32781
|
-
|
|
33688
|
+
rename: (args) => myStore.rename(docId, args[0] as string),
|
|
33689
|
+
append: (args) => myStore.append(docId, args[0] as string),
|
|
32782
33690
|
},
|
|
32783
|
-
|
|
32784
|
-
|
|
32785
|
-
|
|
32786
|
-
|
|
32787
|
-
snapshot: () => myStore.read('doc-1'),
|
|
33691
|
+
subject: {
|
|
33692
|
+
onChanged: (listener) => myStore.onUpdated(docId, listener),
|
|
33693
|
+
onRemoved: (listener) => myStore.onRemoved(docId, listener),
|
|
33694
|
+
snapshot: () => myStore.read(docId),
|
|
32788
33695
|
},
|
|
32789
33696
|
});
|
|
32790
33697
|
```
|
|
32791
33698
|
|
|
32792
33699
|
### `TavernHost` members
|
|
32793
33700
|
|
|
32794
|
-
| Member |
|
|
32795
|
-
| ------------------------ |
|
|
32796
|
-
| `
|
|
32797
|
-
| `
|
|
32798
|
-
| `disposalSignal` | `AbortSignal`
|
|
32799
|
-
| `dispose()` | `void`
|
|
32800
|
-
| `disposed` | `boolean`
|
|
32801
|
-
| `kick(
|
|
32802
|
-
| `peers` | `readonly MeshPeer[]`
|
|
32803
|
-
| `relayNotice(
|
|
32804
|
-
| `tap(handler,
|
|
32805
|
-
| `[Symbol.dispose]()` | `void`
|
|
32806
|
-
|
|
32807
|
-
---
|
|
33701
|
+
| Member | Type | Behavior |
|
|
33702
|
+
| ------------------------ | -------------------------------- | ---------------------------------------------------------------------------------------- |
|
|
33703
|
+
| `acceptAnswerCode()` | `(code) => Promise` | Consumes a guest's answer code; resolves with the peer once the channel is open |
|
|
33704
|
+
| `createInvitationCode()` | `() => Promise` | Produces a single-use invitation code, QR-compact when the environment allows |
|
|
33705
|
+
| `disposalSignal` | `AbortSignal` | Aborted when hosting ends |
|
|
33706
|
+
| `dispose()` | `() => void` | Stops hosting: closes every channel and detaches all subscriptions; idempotent |
|
|
33707
|
+
| `disposed` | `boolean` | Whether hosting has ended |
|
|
33708
|
+
| `kick()` | `(peerId) => void` | Disconnects one guest; the guest observes it and fires `onEnded` |
|
|
33709
|
+
| `peers` | `readonly MeshPeer[]` | The guests currently connected |
|
|
33710
|
+
| `relayNotice()` | `(notice) => void` | Broadcasts `serializeNotice(notice)` to every guest. Dropped after hosting ended |
|
|
33711
|
+
| `tap()` | `(handler, opts?) => () => void` | Subscribes to `TavernHostEvent`s; handler errors are swallowed; detaches on abort or end |
|
|
33712
|
+
| `[Symbol.dispose]()` | `() => void` | Delegates to `dispose()`; enables `using` declarations |
|
|
32808
33713
|
|
|
32809
33714
|
## `joinTavern(options)`
|
|
32810
33715
|
|
|
32811
|
-
|
|
33716
|
+
Joins a session as a guest: decodes the invitation code, opens the mesh guest, and returns the answer code to show back. Snapshots mount through `mount` as they arrive; the first non-null mount settles `ready`. The session ends exactly once: from the channel dropping (`TavernError`), an early exit before mounting (`TavernDisposedError`), or disposal.
|
|
32812
33717
|
|
|
32813
|
-
**Returns:** `Promise
|
|
33718
|
+
**Returns:** `Promise>`: the answer code, the guest handle, and the `ready` promise. Rejects with `TavernPairingError` when the invitation code cannot be used.
|
|
32814
33719
|
|
|
32815
|
-
| Option | Type
|
|
32816
|
-
| ---------------- |
|
|
32817
|
-
| `
|
|
32818
|
-
| `mount` | `(snapshot
|
|
32819
|
-
| `name` | `string`
|
|
32820
|
-
| `
|
|
32821
|
-
| `
|
|
32822
|
-
| `
|
|
32823
|
-
| `onJoined?` | `(subject: Mounted) => void` | The mounted value once the first snapshot arrives |
|
|
32824
|
-
| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |
|
|
33720
|
+
| Option | Type | Description |
|
|
33721
|
+
| ---------------- | ------------------------------- | --------------------------------------------------------------------------------------- |
|
|
33722
|
+
| `invitationCode` | `string` | The invitation code the host produced |
|
|
33723
|
+
| `mount` | `(snapshot) => Mounted \| null` | Turns a received snapshot into the mounted mirror; null ignores it. Called per snapshot |
|
|
33724
|
+
| `name` | `string` | The guest's display name on the channel |
|
|
33725
|
+
| `onEnded?` | `(subject: Mounted) => void` | The channel ended after joining; receives the mounted subject for unmounting |
|
|
33726
|
+
| `onNotice?` | `(wire: unknown) => void` | Receives a notice the host relayed: re-emit it in the local UI |
|
|
33727
|
+
| `rtc?` | `MeshRtcFactory` | WebRTC factory: the injection point for tests and non-browser runtimes |
|
|
32825
33728
|
|
|
32826
33729
|
**Example**
|
|
32827
33730
|
|
|
32828
33731
|
```ts
|
|
32829
33732
|
import { joinTavern } from '@vielzeug/tavern';
|
|
32830
33733
|
|
|
32831
|
-
const {
|
|
32832
|
-
|
|
32833
|
-
mount: (snapshot) =>
|
|
33734
|
+
const { answerCode, guest, ready } = await joinTavern({
|
|
33735
|
+
invitationCode,
|
|
33736
|
+
mount: (snapshot) => mySchema.parse(snapshot),
|
|
32834
33737
|
name: 'Alex',
|
|
32835
|
-
onEnded: (subject) => unmountMirror(subject
|
|
32836
|
-
onJoined: (subject) => mountMirror(subject),
|
|
32837
|
-
});
|
|
32838
|
-
guest.tap((event) => {
|
|
32839
|
-
if (event.type === 'rejected') console.warn(event.commandId, event.message);
|
|
33738
|
+
onEnded: (subject) => unmountMirror(subject),
|
|
32840
33739
|
});
|
|
32841
|
-
|
|
32842
|
-
|
|
32843
|
-
guest.dispose();
|
|
33740
|
+
await host.acceptAnswerCode(answerCode);
|
|
33741
|
+
await ready; // the mirror is live
|
|
32844
33742
|
```
|
|
32845
33743
|
|
|
32846
|
-
### `
|
|
33744
|
+
### `TavernJoinResult` members
|
|
32847
33745
|
|
|
32848
|
-
| Member
|
|
32849
|
-
|
|
|
32850
|
-
| `
|
|
32851
|
-
| `
|
|
32852
|
-
| `
|
|
32853
|
-
| `sendCommand(subjectId, name, args)` | `void` | Forwards a command to the host. Throws `TavernDisposedError` if the session has ended |
|
|
32854
|
-
| `tap(handler, options?)` | `() => void` | Observes `TavernGuestEvent`s; returns an unsubscribe function |
|
|
32855
|
-
| `[Symbol.dispose]()` | `void` | Delegates to `dispose()`. Enables `using` declarations |
|
|
33746
|
+
| Member | Type | Behavior |
|
|
33747
|
+
| ------------ | ------------------ | ------------------------------------------------------------------------------------------------ |
|
|
33748
|
+
| `answerCode` | `string` | The answer code to show back to the host, QR-compact when the environment allows |
|
|
33749
|
+
| `guest` | `TavernGuest` | The guest handle |
|
|
33750
|
+
| `ready` | `Promise` | Resolves with the mounted subject on the first mount; rejects with why the session never came up |
|
|
32856
33751
|
|
|
32857
|
-
|
|
33752
|
+
### `TavernGuest` members
|
|
33753
|
+
|
|
33754
|
+
| Member | Type | Behavior |
|
|
33755
|
+
| -------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
|
33756
|
+
| `disposalSignal` | `AbortSignal` | Aborted when the session ends |
|
|
33757
|
+
| `dispose()` | `() => void` | Leaves the session; `onEnded` fires exactly once |
|
|
33758
|
+
| `disposed` | `boolean` | Whether the session has ended |
|
|
33759
|
+
| `sendCommand()` | `(name, args?, target?) => void` | Forwards a command to the host's table; `target` is required on a named session; throws `TavernDisposedError` after the session ended |
|
|
33760
|
+
| `tap()` | `(handler, opts?) => () => void` | Subscribes to `TavernGuestEvent`s; handler errors are swallowed; detaches on abort or end |
|
|
33761
|
+
| `[Symbol.dispose]()` | `() => void` | Delegates to `dispose()`; enables `using` declarations |
|
|
32858
33762
|
|
|
32859
33763
|
## Types
|
|
32860
33764
|
|
|
33765
|
+
### `TavernCommands`
|
|
33766
|
+
|
|
32861
33767
|
```ts
|
|
32862
|
-
|
|
32863
|
-
|
|
32864
|
-
|
|
32865
|
-
has(name: string): boolean;
|
|
32866
|
-
/** Applies the command; throwing rejects the guest with the error's message. */
|
|
32867
|
-
apply(name: string, args: readonly unknown[]): unknown;
|
|
32868
|
-
}
|
|
33768
|
+
type TavernCommand = (args: readonly unknown[]) => void;
|
|
33769
|
+
type TavernCommands = Record;
|
|
33770
|
+
```
|
|
32869
33771
|
|
|
32870
|
-
|
|
32871
|
-
|
|
32872
|
-
|
|
32873
|
-
|
|
32874
|
-
|
|
32875
|
-
interface
|
|
32876
|
-
|
|
32877
|
-
snapshot(): unknown;
|
|
32878
|
-
/** Subscribes to local changes of the hosted subject: the re-broadcast trigger. */
|
|
33772
|
+
The host's command table, keyed by name: the same functions the host's own UI calls, so guest actions follow exactly the same validation path as local ones. A missing key rejects the guest with `The host has no command named "..."`; a throwing handler rejects with its message. Omit the table entirely for a read-only session.
|
|
33773
|
+
|
|
33774
|
+
### `TavernSubject`
|
|
33775
|
+
|
|
33776
|
+
```ts
|
|
33777
|
+
interface TavernSubject {
|
|
33778
|
+
readonly id?: string;
|
|
32879
33779
|
onChanged(listener: () => void): () => void;
|
|
32880
|
-
/** Subscribes to the hosted subject's removal: hosting ends when it fires. */
|
|
32881
33780
|
onRemoved(listener: () => void): () => void;
|
|
33781
|
+
snapshot(): unknown;
|
|
32882
33782
|
}
|
|
33783
|
+
```
|
|
32883
33784
|
|
|
32884
|
-
|
|
32885
|
-
* Notice relay between host and guests. Notices cross the wire as opaque
|
|
32886
|
-
* values: each client translates locally.
|
|
32887
|
-
*/
|
|
32888
|
-
interface TavernNotices {
|
|
32889
|
-
/** Serializes a local notice for the wire; null skips this one. */
|
|
32890
|
-
toWire(notice: unknown): unknown | null;
|
|
32891
|
-
/** Re-emits a received wire notice locally. */
|
|
32892
|
-
fromWire(wire: unknown): void;
|
|
32893
|
-
}
|
|
32894
|
-
|
|
32895
|
-
/** Notable host moments reported through `TavernHost.tap`. */
|
|
32896
|
-
type TavernHostEvent =
|
|
32897
|
-
| { readonly peer: MeshPeer; readonly type: 'peer-joined' }
|
|
32898
|
-
| { readonly peer: MeshPeer; readonly reason?: string; readonly type: 'peer-left' }
|
|
32899
|
-
| { readonly error: unknown; readonly message: string; readonly type: 'warning' };
|
|
32900
|
-
|
|
32901
|
-
/** Notable guest moments reported through `TavernGuest.tap`. */
|
|
32902
|
-
type TavernGuestEvent =
|
|
32903
|
-
| { readonly commandId: string; readonly message: string; readonly type: 'rejected' }
|
|
32904
|
-
| { readonly error: unknown; readonly message: string; readonly type: 'warning' };
|
|
32905
|
-
|
|
32906
|
-
/** Options for `hostTavern`. */
|
|
32907
|
-
interface TavernHostOptions {
|
|
32908
|
-
commands: TavernCommands;
|
|
32909
|
-
notices?: TavernNotices;
|
|
32910
|
-
/** Hosting ended: the subject was removed or `dispose()` ran. Fires exactly once. */
|
|
32911
|
-
onEnded?(): void;
|
|
32912
|
-
rtc?: MeshRtcFactory;
|
|
32913
|
-
subjectId: string;
|
|
32914
|
-
subjects: TavernSubjects;
|
|
32915
|
-
}
|
|
32916
|
-
|
|
32917
|
-
/** Options for `joinTavern`. */
|
|
32918
|
-
interface TavernGuestOptions {
|
|
32919
|
-
invitationText: string;
|
|
32920
|
-
/** Mounts a received snapshot; the mounted value, or null to ignore. */
|
|
32921
|
-
mount(snapshot: unknown): Mounted | null;
|
|
32922
|
-
name: string;
|
|
32923
|
-
notices?: TavernNotices;
|
|
32924
|
-
onEnded?(subject: Mounted): void;
|
|
32925
|
-
onFailed?(reason: string): void;
|
|
32926
|
-
onJoined?(subject: Mounted): void;
|
|
32927
|
-
rtc?: MeshRtcFactory;
|
|
32928
|
-
}
|
|
33785
|
+
How the host reads and watches the single subject it shares. `onChanged` is the re-broadcast trigger; `onRemoved` ends hosting; `snapshot()` returns the JSON-serializable state to broadcast, or `null` while the subject is missing (the broadcast skips). A throwing `snapshot` is reported as a `warning` tap event instead of crashing the host. `id` is the subject's stable identity: declaring it puts every command under target verification: guests must pass the id as `sendCommand`'s `target`, and a missing or mismatched target rejects with `That command does not target the hosted subject.` before the command table runs. The target is a guest claim, not a proof: the guard catches misrouted commands, while handlers and the command table stay the authorization boundary. Omit `id` for anonymous sessions, where targets carry no meaning.
|
|
32929
33786
|
|
|
32930
|
-
|
|
32931
|
-
interface TavernHost {
|
|
32932
|
-
acceptAnswerText(text: string): Promise;
|
|
32933
|
-
createInvitationText(): Promise;
|
|
32934
|
-
readonly disposalSignal: AbortSignal;
|
|
32935
|
-
dispose(): void;
|
|
32936
|
-
readonly disposed: boolean;
|
|
32937
|
-
kick(peerId: string): void;
|
|
32938
|
-
readonly peers: readonly MeshPeer[];
|
|
32939
|
-
relayNotice(notice: unknown): void;
|
|
32940
|
-
tap(handler: (event: TavernHostEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;
|
|
32941
|
-
[Symbol.dispose](): void;
|
|
32942
|
-
}
|
|
33787
|
+
### `TavernHostEvent`
|
|
32943
33788
|
|
|
32944
|
-
|
|
32945
|
-
|
|
32946
|
-
|
|
32947
|
-
|
|
32948
|
-
|
|
32949
|
-
|
|
32950
|
-
|
|
32951
|
-
|
|
32952
|
-
|
|
32953
|
-
|
|
33789
|
+
| Variant | Fires when |
|
|
33790
|
+
| -------------------------------------- | ---------------------------------------------------------- |
|
|
33791
|
+
| `{ type: 'peer-joined'; peer }` | A guest's channel opened |
|
|
33792
|
+
| `{ type: 'peer-left'; peer; reason? }` | A guest's channel closed |
|
|
33793
|
+
| `{ type: 'warning'; message; error }` | A transport error or a throwing snapshot read was survived |
|
|
33794
|
+
| `{ type: 'dispose' }` | Hosting ended and the tap stream is about to clear |
|
|
33795
|
+
|
|
33796
|
+
### `TavernGuestEvent`
|
|
33797
|
+
|
|
33798
|
+
| Variant | Fires when |
|
|
33799
|
+
| ------------------------------------------ | ------------------------------------------------------ |
|
|
33800
|
+
| `{ type: 'rejected'; commandId; message }` | The host rejected a forwarded command |
|
|
33801
|
+
| `{ type: 'warning'; message; error }` | A transport error was survived |
|
|
33802
|
+
| `{ type: 'dispose' }` | The session ended and the tap stream is about to clear |
|
|
32954
33803
|
|
|
32955
33804
|
## Errors
|
|
32956
33805
|
|
|
32957
|
-
|
|
32958
|
-
|
|
32959
|
-
|
|
32960
|
-
|
|
32961
|
-
|
|
33806
|
+
### `TavernError`
|
|
33807
|
+
|
|
33808
|
+
Base class for every Tavern failure; `instanceof TavernError` narrows the whole hierarchy. Channel failures before the first snapshot reject `ready` with this class.
|
|
33809
|
+
|
|
33810
|
+
### `TavernPairingError`
|
|
33811
|
+
|
|
33812
|
+
The code the consumer pasted could not be used: garbage, the wrong kind, an expired invitation, or an answer the host refuses. The underlying `@vielzeug/mesh` failure is chained as `cause`.
|
|
33813
|
+
|
|
33814
|
+
### `TavernDisposedError`
|
|
32962
33815
|
|
|
32963
|
-
|
|
33816
|
+
A stopped host or ended guest was used again: control-plane calls throw it so leaked handles surface, and it rejects `ready` when the guest leaves before the first snapshot.
|
|
33817
|
+
|
|
33818
|
+
## Testing
|
|
33819
|
+
|
|
33820
|
+
`@vielzeug/tavern/testing` re-exports `createFakeRtc()` (and the `FakeRtc` type): an in-process fake WebRTC factory you pass as the `rtc` option of `hostTavern` and `joinTavern` to drive a real host/guest pair inside one test process, with no browser or network. Consuming this subpath keeps mesh, tavern's transport, out of your dev dependencies.
|
|
33821
|
+
|
|
33822
|
+
```ts
|
|
33823
|
+
import { hostTavern, joinTavern } from '@vielzeug/tavern';
|
|
33824
|
+
import { createFakeRtc } from '@vielzeug/tavern/testing';
|
|
33825
|
+
|
|
33826
|
+
const { rtc } = createFakeRtc();
|
|
33827
|
+
const host = hostTavern({ rtc, subject });
|
|
33828
|
+
const guest = await joinTavern({ invitationCode: await host.createInvitationCode(), mount, name, rtc });
|
|
33829
|
+
```
|
|
32964
33830
|
|
|
32965
33831
|
### Usage Guide
|
|
32966
33832
|
|
|
32967
33833
|
## Basic Usage
|
|
32968
33834
|
|
|
32969
|
-
Host one subject per session; guests join through the invitation/answer pair.
|
|
33835
|
+
Host one subject per session; guests join through the invitation/answer code pair. A session always carries exactly one subject: the guest handle needs no routing keys, and the host's command table is the single validation path for local and remote actions alike.
|
|
32970
33836
|
|
|
32971
33837
|
```ts
|
|
32972
33838
|
import { hostTavern, joinTavern } from '@vielzeug/tavern';
|
|
32973
33839
|
|
|
32974
33840
|
const host = hostTavern({
|
|
32975
|
-
commands: {
|
|
32976
|
-
|
|
32977
|
-
|
|
32978
|
-
|
|
32979
|
-
|
|
32980
|
-
snapshot: () => myStore.read('doc-1'),
|
|
33841
|
+
commands: { rename: (args) => myStore.rename(docId, args[0] as string) },
|
|
33842
|
+
subject: {
|
|
33843
|
+
onChanged: (listener) => myStore.onUpdated(docId, listener),
|
|
33844
|
+
onRemoved: (listener) => myStore.onRemoved(docId, listener),
|
|
33845
|
+
snapshot: () => myStore.read(docId),
|
|
32981
33846
|
},
|
|
32982
33847
|
});
|
|
32983
|
-
const
|
|
33848
|
+
const invitationCode = await host.createInvitationCode();
|
|
32984
33849
|
|
|
32985
|
-
const {
|
|
32986
|
-
|
|
33850
|
+
const { answerCode, guest, ready } = await joinTavern({
|
|
33851
|
+
invitationCode,
|
|
32987
33852
|
mount: (snapshot) => parseAndMount(snapshot),
|
|
32988
33853
|
name: 'Alex',
|
|
32989
33854
|
});
|
|
32990
|
-
await host.
|
|
33855
|
+
await host.acceptAnswerCode(answerCode);
|
|
33856
|
+
await ready;
|
|
32991
33857
|
|
|
32992
|
-
guest.sendCommand('
|
|
33858
|
+
guest.sendCommand('rename', ['Quarterly report']);
|
|
32993
33859
|
```
|
|
32994
33860
|
|
|
32995
33861
|
## Host a Subject
|
|
32996
33862
|
|
|
32997
|
-
The host validates every guest command
|
|
33863
|
+
The host validates every guest command against its command table: a name the table does not hold rejects without applying, and a handler that throws rejects the guest with its message. The snapshot re-broadcasts on every local change: coalesced on a microtask, so bursts of changes ship one snapshot, not many. `onEnded` fires exactly once when hosting ends, whether the subject was removed or the host was disposed: reset your session UI there instead of intercepting your own `onRemoved` seam.
|
|
32998
33864
|
|
|
32999
33865
|
```ts
|
|
33000
33866
|
import { hostTavern } from '@vielzeug/tavern';
|
|
33001
33867
|
|
|
33002
33868
|
const host = hostTavern({
|
|
33003
33869
|
commands: {
|
|
33004
|
-
|
|
33005
|
-
|
|
33870
|
+
rename: (args) => myStore.rename(docId, args[0] as string),
|
|
33871
|
+
append: (args) => myStore.append(docId, args[0] as string),
|
|
33006
33872
|
},
|
|
33007
33873
|
onEnded: () => updateSessionUi(), // hosting ended: subject removed or disposed
|
|
33008
|
-
|
|
33009
|
-
|
|
33010
|
-
|
|
33011
|
-
|
|
33012
|
-
snapshot: () => myStore.read('doc-1'),
|
|
33874
|
+
subject: {
|
|
33875
|
+
onChanged: (listener) => myStore.onUpdated(docId, listener),
|
|
33876
|
+
onRemoved: (listener) => myStore.onRemoved(docId, listener),
|
|
33877
|
+
snapshot: () => myStore.read(docId),
|
|
33013
33878
|
},
|
|
33014
33879
|
});
|
|
33015
33880
|
|
|
@@ -33021,9 +33886,9 @@ host.tap((event) => {
|
|
|
33021
33886
|
updatePeerList(host.peers); // always current inside a presence event
|
|
33022
33887
|
});
|
|
33023
33888
|
|
|
33024
|
-
const
|
|
33025
|
-
// Show the invitation (QR or copy/paste); the guest returns an answer code.
|
|
33026
|
-
await host.
|
|
33889
|
+
const invitationCode = await host.createInvitationCode();
|
|
33890
|
+
// Show the invitation code (QR or copy/paste); the guest returns an answer code.
|
|
33891
|
+
await host.acceptAnswerCode(answerCode);
|
|
33027
33892
|
|
|
33028
33893
|
// Kick a peer; the guest observes a disconnect and fires onEnded.
|
|
33029
33894
|
host.kick(peerId);
|
|
@@ -33031,59 +33896,90 @@ host.kick(peerId);
|
|
|
33031
33896
|
host.dispose(); // stop hosting: every guest disconnects
|
|
33032
33897
|
```
|
|
33033
33898
|
|
|
33899
|
+
Omit `commands` for a read-only session: guests mirror the subject, and every command rejects with `The host has no command named "..."`.
|
|
33900
|
+
|
|
33901
|
+
## Name the Subject to Guard Command Targets
|
|
33902
|
+
|
|
33903
|
+
A guest tab can mirror more than one subject, so a command alone does not say enough: it must name what it acts on. Declaring `subject.id` makes tavern verify that: every command needs the hosted subject's id as `sendCommand`'s third argument, and a missing or mismatched `target` rejects with a `rejected` tap event before the command table ever runs. Without `id`, the session stays anonymous and targets carry no meaning.
|
|
33904
|
+
|
|
33905
|
+
```ts
|
|
33906
|
+
const host = hostTavern({
|
|
33907
|
+
commands: { rename: (args) => myStore.rename(docId, args[0] as string) },
|
|
33908
|
+
subject: {
|
|
33909
|
+
id: docId, // named session: guests must target this id
|
|
33910
|
+
onChanged: (listener) => myStore.onUpdated(docId, listener),
|
|
33911
|
+
onRemoved: (listener) => myStore.onRemoved(docId, listener),
|
|
33912
|
+
snapshot: () => myStore.read(docId),
|
|
33913
|
+
},
|
|
33914
|
+
});
|
|
33915
|
+
|
|
33916
|
+
// Guest side: the mirror knows which subject it is mirroring.
|
|
33917
|
+
guest.sendCommand('rename', ['Quarterly report'], docId);
|
|
33918
|
+
```
|
|
33919
|
+
|
|
33920
|
+
The guard stops honest misrouting: a stray command meant for another subject in a guest tab fails loudly instead of silently mutating the hosted one. It cannot make a paired guest honest: the target is a claim, not a proof, so handlers must keep acting on their own subject and the command table remains the authorization boundary for what guests may do.
|
|
33921
|
+
|
|
33034
33922
|
## Join as a Guest
|
|
33035
33923
|
|
|
33036
|
-
Joining consumes the invitation and produces the answer code to show back. The session goes live once the host accepts the answer and the first snapshot
|
|
33924
|
+
Joining consumes the invitation code and produces the answer code to show back. The session goes live once the host accepts the answer and the first snapshot mounts: that transition settles the `ready` promise, so there is no race between the handshake and your code attaching handlers.
|
|
33037
33925
|
|
|
33038
33926
|
```ts
|
|
33039
33927
|
import { joinTavern } from '@vielzeug/tavern';
|
|
33040
33928
|
|
|
33041
|
-
const {
|
|
33042
|
-
|
|
33929
|
+
const { answerCode, guest, ready } = await joinTavern({
|
|
33930
|
+
invitationCode,
|
|
33043
33931
|
mount: (snapshot) => sanitizeAndMount(snapshot),
|
|
33044
33932
|
name: 'Alex',
|
|
33045
33933
|
onEnded: (subject) => unmountMirror(subject.id),
|
|
33046
|
-
onFailed: (reason) => showError(reason),
|
|
33047
|
-
onJoined: (subject) => mountMirror(subject),
|
|
33048
33934
|
});
|
|
33049
33935
|
guest.tap((event) => {
|
|
33050
33936
|
if (event.type === 'rejected') showToast(event.message); // event.commandId names the command it answers
|
|
33051
33937
|
if (event.type === 'warning') log.warn(event.message, event.error);
|
|
33052
33938
|
});
|
|
33053
33939
|
|
|
33054
|
-
|
|
33940
|
+
try {
|
|
33941
|
+
await ready; // resolves with the mounted mirror once the first snapshot arrives
|
|
33942
|
+
} catch (error) {
|
|
33943
|
+
showError(error.message); // the channel failed, the host closed it, or the guest left early
|
|
33944
|
+
}
|
|
33945
|
+
|
|
33946
|
+
guest.sendCommand('rename', ['New name']);
|
|
33055
33947
|
guest.dispose(); // leave; onEnded fires with the mounted subject exactly once
|
|
33056
33948
|
```
|
|
33057
33949
|
|
|
33058
|
-
The snapshot arrives as parsed JSON: `mount` receives `unknown` and should validate before trusting it. Returning `null` ignores the
|
|
33950
|
+
The snapshot arrives as parsed JSON: `mount` receives `unknown` and should validate before trusting it. It is called for every snapshot the host broadcasts. Returning `null` ignores one; the first non-null return becomes the mounted subject: it settles `ready` and is passed to `onEnded` when the session ends. A `ready` you never await is safe: its rejection is pre-handled and never surfaces as an unhandled rejection.
|
|
33059
33951
|
|
|
33060
33952
|
## Relay Notices
|
|
33061
33953
|
|
|
33062
|
-
|
|
33954
|
+
Notices are ephemeral out-of-band UI signals: a toast fired elsewhere, a comment added. Catalog keys rather than prose cross the wire, so each client translates locally. The host serializes its own notices with `serializeNotice` and relays them with `relayNotice`; guests receive them through `onNotice`.
|
|
33063
33955
|
|
|
33064
33956
|
```ts
|
|
33065
|
-
|
|
33066
|
-
|
|
33067
|
-
|
|
33068
|
-
|
|
33069
|
-
|
|
33070
|
-
|
|
33957
|
+
// Host side: forward local notices through the session.
|
|
33958
|
+
const host = hostTavern({
|
|
33959
|
+
/* ... */
|
|
33960
|
+
serializeNotice: (notice) => (isLocalNotice(notice) ? toWireShape(notice) : null),
|
|
33961
|
+
});
|
|
33962
|
+
host.relayNotice(localNotice); // null from serializeNotice skips this one
|
|
33071
33963
|
|
|
33072
|
-
//
|
|
33073
|
-
|
|
33964
|
+
// Guest side: re-emit received notices in the local UI.
|
|
33965
|
+
const { guest } = await joinTavern({
|
|
33966
|
+
/* ... */
|
|
33967
|
+
onNotice: (wire) => bus.emit('notify', wire),
|
|
33968
|
+
});
|
|
33074
33969
|
```
|
|
33075
33970
|
|
|
33076
|
-
**Echo guard**: a tab that both hosts and guests must prevent re-broadcasting a wire-originated notice back to its own guests. One boolean set during `
|
|
33971
|
+
**Echo guard**: a tab that both hosts and guests must prevent re-broadcasting a wire-originated notice back to its own guests: `onNotice` emits locally, the host's local subscription picks it up, and without a guard it would loop. One boolean set during `onNotice` and checked in `serializeNotice` is sufficient: the consumer owns this because only they know their local event system.
|
|
33077
33972
|
|
|
33078
33973
|
## Observe with tap()
|
|
33079
33974
|
|
|
33080
|
-
Both handles expose `tap()` for observability: presence and warnings on the host, rejections and warnings on the guest. Handler errors are swallowed, and the subscription detaches when its signal aborts or the session ends. Lifecycle
|
|
33975
|
+
Both handles expose `tap()` for observability: presence and warnings on the host, rejections and warnings on the guest. Handler errors are swallowed, and the subscription detaches when its signal aborts or the session ends. Lifecycle stays out of the observability stream: `ready` covers the opening transition on the guest, and `onEnded` covers the closing transition on both handles.
|
|
33081
33976
|
|
|
33082
33977
|
```ts
|
|
33083
33978
|
import type { TavernGuestEvent, TavernHostEvent } from '@vielzeug/tavern';
|
|
33084
33979
|
|
|
33085
33980
|
host.tap((event: TavernHostEvent) => {
|
|
33086
33981
|
if (event.type === 'warning') log.warn(event.message, event.error); // the original error, not just text
|
|
33982
|
+
if (event.type === 'dispose') log.info('hosting ended');
|
|
33087
33983
|
});
|
|
33088
33984
|
guest.tap((event: TavernGuestEvent) => {
|
|
33089
33985
|
if (event.type === 'rejected') log.info(`command ${event.commandId} rejected: ${event.message}`);
|
|
@@ -33092,13 +33988,13 @@ guest.tap((event: TavernGuestEvent) => {
|
|
|
33092
33988
|
|
|
33093
33989
|
## Handle Pairing Mistakes
|
|
33094
33990
|
|
|
33095
|
-
Every user-input pairing failure surfaces as `TavernPairingError` from both `
|
|
33991
|
+
Every user-input pairing failure surfaces as `TavernPairingError` from both `acceptAnswerCode` and `joinTavern`: a garbage code, the wrong code kind, an expired invitation, or an answer the host refuses. Catch it to show a helpful message instead of a raw error; the underlying mesh failure is chained as `cause` when you need it.
|
|
33096
33992
|
|
|
33097
33993
|
```ts
|
|
33098
33994
|
import { hostTavern, TavernPairingError } from '@vielzeug/tavern';
|
|
33099
33995
|
|
|
33100
33996
|
try {
|
|
33101
|
-
await host.
|
|
33997
|
+
await host.acceptAnswerCode(pastedCode);
|
|
33102
33998
|
} catch (error) {
|
|
33103
33999
|
if (error instanceof TavernPairingError) {
|
|
33104
34000
|
showToast(error.message); // "That code is an invitation, not a guest answer."
|
|
@@ -33110,16 +34006,15 @@ try {
|
|
|
33110
34006
|
|
|
33111
34007
|
## Working with Other Vielzeug Libraries
|
|
33112
34008
|
|
|
33113
|
-
Tavern builds on `@vielzeug/mesh` for the WebRTC transport, pairing codes, and QR-optimized codecs. You do not interact with mesh directly: tavern owns the protocol, but the `rtc` option accepts a `MeshRtcFactory` for testing or non-browser runtimes
|
|
34009
|
+
Tavern builds on `@vielzeug/mesh` for the WebRTC transport, pairing codes, and QR-optimized codecs. You do not interact with mesh directly: tavern owns the protocol, but the `rtc` option accepts a `MeshRtcFactory` for testing or non-browser runtimes. The peers carried by tap events and the {@link TavernHost.peers} getter are mesh types, re-exported by tavern so one import types everything.
|
|
33114
34010
|
|
|
33115
34011
|
```ts
|
|
33116
34012
|
import type { MeshRtcFactory } from '@vielzeug/mesh';
|
|
33117
34013
|
import { hostTavern } from '@vielzeug/tavern';
|
|
33118
34014
|
|
|
33119
34015
|
const host = hostTavern({
|
|
33120
|
-
// ... commands,
|
|
34016
|
+
// ... commands, subject
|
|
33121
34017
|
rtc: myTestRtcFactory, // inject an in-memory WebRTC fake
|
|
33122
|
-
subjectId: 'doc-1',
|
|
33123
34018
|
});
|
|
33124
34019
|
```
|
|
33125
34020
|
|
|
@@ -33127,11 +34022,12 @@ Pair `@vielzeug/ledger` on the host to give the commands tavern applies an undo
|
|
|
33127
34022
|
|
|
33128
34023
|
## Best Practices
|
|
33129
34024
|
|
|
33130
|
-
- Keep the command table the same
|
|
34025
|
+
- Keep the command table the same functions the host's own UI calls, so guest actions cannot bypass local validation.
|
|
33131
34026
|
- Return `null` from `snapshot` while the subject is missing: the broadcast simply skips.
|
|
33132
34027
|
- Reset host-side session UI in `onEnded`: it fires exactly once for subject removal and explicit disposal alike, so you never need to double-wire your own `onRemoved` seam.
|
|
34028
|
+
- Await `ready` before trusting the mirror: it names the exact reason a session never came up, and its rejection is safe to ignore when you do not care.
|
|
33133
34029
|
- Treat notices as catalog keys, not prose: each client translates locally.
|
|
33134
|
-
- Guard against notice echo if a tab can both host and guest: one boolean in `
|
|
34030
|
+
- Guard against notice echo if a tab can both host and guest: one boolean in `serializeNotice` is sufficient.
|
|
33135
34031
|
- Dispose guests and hosts when their screen unmounts; channels also clean up on disconnect through `onEnded`, which fires exactly once on both sides.
|
|
33136
34032
|
- Catch `TavernPairingError` separately from other errors: it means the pasted code could not be used, not that something is broken.
|
|
33137
34033
|
|
|
@@ -33208,18 +34104,17 @@ const text = format(reminder, {
|
|
|
33208
34104
|
## Features
|
|
33209
34105
|
|
|
33210
34106
|
- `parse()`: Requires an explicit ISO target: instant, zoned date-time, plain date-time, or plain date.
|
|
33211
|
-
- `toInstant()` / `
|
|
34107
|
+
- `toInstant()` / `toZoned()`: Convert wall-clock and absolute values with explicit timezone semantics.
|
|
33212
34108
|
- `shift()` / `difference()`: Apply DST-safe arithmetic across instant, zoned, and wall-clock inputs.
|
|
33213
|
-
- `contains()` / `clamp()`: Compare normalized ranges with optional calendar-unit precision.
|
|
33214
34109
|
- `startOf()` / `endOf()`: Resolve timezone-aware calendar boundaries, including configurable week starts.
|
|
33215
|
-
- `dateRange()` / `recurrence()`: Generate validated, lazy zoned calendar sequences.
|
|
33216
34110
|
- `format()` / `formatRelative()` / `formatDuration()`: Render localized values through `Intl`, including calendar-aware relative months and years.
|
|
33217
34111
|
- `formatTimer()`: Deterministic stopwatch clocks (`47:12`, `1:02:35`) for elapsed-time UI.
|
|
33218
|
-
-
|
|
34112
|
+
- `@vielzeug/tempo/cadence`: RFC 5545 RRULE engine — parse, lazy DST-correct expansion, and `RDATE`/`EXDATE` merging.
|
|
33219
34113
|
|
|
33220
34114
|
## Documentation
|
|
33221
34115
|
|
|
33222
34116
|
- [Usage Guide](./usage.md)
|
|
34117
|
+
- [Cadence (RRULE)](./cadence.md)
|
|
33223
34118
|
- [API Reference](./api.md)
|
|
33224
34119
|
- [Examples](./examples.md)
|
|
33225
34120
|
- [Migration Guide](./migration.md)
|
|
@@ -33238,20 +34133,20 @@ const text = format(reminder, {
|
|
|
33238
34133
|
| `parse()` | Parse ISO text to an explicit Temporal kind | Sync | `as` is required |
|
|
33239
34134
|
| `isValid()` | Narrow an unknown runtime value to `TimeInput` | Sync | Does not parse strings |
|
|
33240
34135
|
| `toInstant()` | Resolve a value as an absolute instant | Sync | Plain values require `timeZone` |
|
|
33241
|
-
| `
|
|
34136
|
+
| `toZoned()` | Project a value to a zone | Sync | Preserves instant, changes wall-clock fields |
|
|
33242
34137
|
| `shift()` / `difference()` | Timezone-aware arithmetic | Sync | Calendar operations require a timezone |
|
|
33243
34138
|
| `isBefore()` / `isAfter()` / `isSame()` | Compare absolute values or calendar units | Sync | Plain values require `timeZone` |
|
|
33244
|
-
| `contains()` / `clamp()` | Compare normalized ranges | Sync | Bounds normalize automatically |
|
|
33245
34139
|
| `startOf()` / `endOf()` | Resolve calendar boundaries | Sync | Weeks default to Monday |
|
|
33246
|
-
| `dateRange()` / `recurrence()` | Generate lazy zoned sequences | Sync | Steps and intervals must advance |
|
|
33247
|
-
| `classifyExpiry()` | Classify fixed elapsed-time thresholds | Sync | Months and years are rejected |
|
|
33248
34140
|
| `format()` family | Localized and machine formatting | Sync | Use `timeZone`, not `tz` |
|
|
33249
34141
|
|
|
33250
34142
|
## Package Entry Point
|
|
33251
34143
|
|
|
33252
|
-
| Import
|
|
33253
|
-
|
|
|
33254
|
-
| `@vielzeug/tempo`
|
|
34144
|
+
| Import | Purpose |
|
|
34145
|
+
| ------------------------- | ---------------------------------------------------------------------------------------- |
|
|
34146
|
+
| `@vielzeug/tempo` | Tempo utilities, errors, types, and shared `Temporal` namespace |
|
|
34147
|
+
| `@vielzeug/tempo/cadence` | RFC 5545 recurrence: `parseCadence`, `toCadence`, `expandCadence`, `resolveCadenceDates` |
|
|
34148
|
+
|
|
34149
|
+
Cadence has its own reference: [Cadence](./cadence.md).
|
|
33255
34150
|
|
|
33256
34151
|
## Core Functions
|
|
33257
34152
|
|
|
@@ -33324,24 +34219,24 @@ nowInstant();
|
|
|
33324
34219
|
|
|
33325
34220
|
---
|
|
33326
34221
|
|
|
33327
|
-
### `toInstant(input, options?)` / `
|
|
34222
|
+
### `toInstant(input, options?)` / `toZoned(input, options)`
|
|
33328
34223
|
|
|
33329
34224
|
```ts
|
|
33330
34225
|
toInstant(input: AbsoluteTime): Temporal.Instant;
|
|
33331
34226
|
toInstant(input: WallTime, options: { timeZone: string } & DisambiguationOptions): Temporal.Instant;
|
|
33332
|
-
|
|
34227
|
+
toZoned(input: TimeInput, options: { timeZone: string } & DisambiguationOptions): Temporal.ZonedDateTime;
|
|
33333
34228
|
```
|
|
33334
34229
|
|
|
33335
|
-
`toInstant()` resolves wall-clock values. `
|
|
34230
|
+
`toInstant()` resolves wall-clock values to an absolute instant. `toZoned()` projects any value into a required timezone, preserving the instant.
|
|
33336
34231
|
|
|
33337
34232
|
**Example:**
|
|
33338
34233
|
|
|
33339
34234
|
```ts
|
|
33340
|
-
import {
|
|
34235
|
+
import { parse, toInstant, toZoned } from '@vielzeug/tempo';
|
|
33341
34236
|
|
|
33342
34237
|
const local = parse('2026-11-01T01:30:00', { as: 'plainDateTime' });
|
|
33343
34238
|
const instant = toInstant(local, { disambiguation: 'later', timeZone: 'America/New_York' });
|
|
33344
|
-
|
|
34239
|
+
toZoned(instant, { timeZone: 'Europe/Berlin' });
|
|
33345
34240
|
```
|
|
33346
34241
|
|
|
33347
34242
|
---
|
|
@@ -33387,20 +34282,6 @@ Compare absolute instants or their containing calendar units.
|
|
|
33387
34282
|
|
|
33388
34283
|
---
|
|
33389
34284
|
|
|
33390
|
-
### `contains({ value, start, end, ...options })` / `clamp({ value, start, end, ...options })`
|
|
33391
|
-
|
|
33392
|
-
```ts
|
|
33393
|
-
contains(input: ContainsInput): boolean;
|
|
33394
|
-
clamp(input: ClampInput & { value: Temporal.ZonedDateTime }): Temporal.ZonedDateTime;
|
|
33395
|
-
clamp(input: ClampInput): Temporal.Instant;
|
|
33396
|
-
```
|
|
33397
|
-
|
|
33398
|
-
Normalizes reversed bounds, then checks or constrains the value.
|
|
33399
|
-
|
|
33400
|
-
**Returns:** `contains()` returns `boolean`; `clamp()` returns the normalized value or nearest bound.
|
|
33401
|
-
|
|
33402
|
-
---
|
|
33403
|
-
|
|
33404
34285
|
### `startOf()` / `endOf()`
|
|
33405
34286
|
|
|
33406
34287
|
```ts
|
|
@@ -33412,30 +34293,6 @@ Returns the first or last nanosecond of a timezone-aware calendar unit.
|
|
|
33412
34293
|
|
|
33413
34294
|
**Returns:** `Temporal.ZonedDateTime`.
|
|
33414
34295
|
|
|
33415
|
-
## Calendar Sequences
|
|
33416
|
-
|
|
33417
|
-
### `dateRange(start, end, step, options?)`
|
|
33418
|
-
|
|
33419
|
-
```ts
|
|
33420
|
-
dateRange(start: TimeInput, end: TimeInput, step: Temporal.DurationLike, options?: TimeZoneOptions): Generator;
|
|
33421
|
-
```
|
|
33422
|
-
|
|
33423
|
-
Returns an inclusive lazy zoned range and rejects steps that do not advance time.
|
|
33424
|
-
|
|
33425
|
-
**Returns:** `Generator`.
|
|
33426
|
-
|
|
33427
|
-
---
|
|
33428
|
-
|
|
33429
|
-
### `recurrence(start, rule, options?)`
|
|
33430
|
-
|
|
33431
|
-
```ts
|
|
33432
|
-
recurrence(start: TimeInput, rule: RecurrenceRule, options?: TimeZoneOptions): Generator;
|
|
33433
|
-
```
|
|
33434
|
-
|
|
33435
|
-
Returns a count- or date-limited lazy recurrence. Intervals must be positive safe integers; counts must be non-negative safe integers.
|
|
33436
|
-
|
|
33437
|
-
**Returns:** `Generator`.
|
|
33438
|
-
|
|
33439
34296
|
## Formatting
|
|
33440
34297
|
|
|
33441
34298
|
### `format(input, options?)`
|
|
@@ -33463,7 +34320,7 @@ format(parse('2026-03-21T10:15:30Z', { as: 'instant' }), {
|
|
|
33463
34320
|
```ts
|
|
33464
34321
|
formatInstant(input: TimeInput, options?: TimeZoneOptions): string;
|
|
33465
34322
|
formatZoned(input: TimeInput, options?: TimeZoneOptions): string;
|
|
33466
|
-
formatRelative(input:
|
|
34323
|
+
formatRelative(input: AbsoluteTime, options?: RelativeFormatOptions): string;
|
|
33467
34324
|
formatDuration(input: string | Temporal.DurationLike, options?: DurationFormatOptions): string;
|
|
33468
34325
|
formatTimer(input: string | Temporal.DurationLike, options?: TimerFormatOptions): string;
|
|
33469
34326
|
```
|
|
@@ -33482,34 +34339,15 @@ formatRangeParts(
|
|
|
33482
34339
|
): ReturnType;
|
|
33483
34340
|
```
|
|
33484
34341
|
|
|
33485
|
-
Return `Intl` parts or localized range strings using `FormatOptions`.
|
|
34342
|
+
Return `Intl` parts or localized range strings using `FormatOptions`. Range inputs are order-free: reversed bounds format like the sorted pair.
|
|
33486
34343
|
|
|
33487
|
-
### `parseDuration()`
|
|
34344
|
+
### `parseDuration()`
|
|
33488
34345
|
|
|
33489
34346
|
```ts
|
|
33490
34347
|
parseDuration(input: string | Temporal.DurationLike): Temporal.Duration;
|
|
33491
|
-
humanize(diff: TimeDiffResult, options?: { locale?: Intl.LocalesArgument }): string;
|
|
33492
|
-
```
|
|
33493
|
-
|
|
33494
|
-
`humanize()` localizes numbers only. Unit names remain English.
|
|
33495
|
-
|
|
33496
|
-
## Classification
|
|
33497
|
-
|
|
33498
|
-
### `classifyExpiry({ value, thresholds, relativeTo?, timeZone? })`
|
|
33499
|
-
|
|
33500
|
-
```ts
|
|
33501
|
-
classifyExpiry(input: ClassifyExpiryInput): K | null;
|
|
33502
34348
|
```
|
|
33503
34349
|
|
|
33504
|
-
|
|
33505
|
-
|
|
33506
|
-
### `timeDiff(a, b?, options?)`
|
|
33507
|
-
|
|
33508
|
-
```ts
|
|
33509
|
-
timeDiff(a: TimeInput, b?: TimeInput, options?: TimeZoneOptions): TimeDiffResult;
|
|
33510
|
-
```
|
|
33511
|
-
|
|
33512
|
-
Returns absolute calendar difference in its largest meaningful unit. Uses Temporal's calendar-aware `.since()` for correct month and year handling.
|
|
34350
|
+
Parses an ISO 8601 duration string or `Temporal.DurationLike` into a `Temporal.Duration`.
|
|
33513
34351
|
|
|
33514
34352
|
## Types
|
|
33515
34353
|
|
|
@@ -33517,7 +34355,6 @@ Returns absolute calendar difference in its largest meaningful unit. Uses Tempor
|
|
|
33517
34355
|
type AbsoluteTime = Temporal.Instant | Temporal.ZonedDateTime;
|
|
33518
34356
|
type WallTime = Temporal.PlainDate | Temporal.PlainDateTime;
|
|
33519
34357
|
type TimeInput = AbsoluteTime | WallTime;
|
|
33520
|
-
type RelativeTimeInput = AbsoluteTime;
|
|
33521
34358
|
type ParseAs = 'instant' | 'plainDate' | 'plainDateTime' | 'zonedDateTime';
|
|
33522
34359
|
type Disambiguation = 'compatible' | 'earlier' | 'later' | 'reject';
|
|
33523
34360
|
type CalendarUnit = 'day' | 'month' | 'week' | 'year';
|
|
@@ -33535,11 +34372,6 @@ type TempoUnit =
|
|
|
33535
34372
|
| 'second'
|
|
33536
34373
|
| 'week'
|
|
33537
34374
|
| 'year';
|
|
33538
|
-
type FixedDuration = Pick;
|
|
33539
|
-
type ExpiryThresholds = Record;
|
|
33540
|
-
type TimeDiffUnit = Exclude;
|
|
33541
|
-
type TimeDiffResult = { unit: TimeDiffUnit; value: number };
|
|
33542
|
-
|
|
33543
34375
|
interface TimeZoneOptions {
|
|
33544
34376
|
timeZone?: string;
|
|
33545
34377
|
}
|
|
@@ -33562,21 +34394,11 @@ interface CompareOptions extends TimeZoneOptions {
|
|
|
33562
34394
|
unit?: BoundaryUnit;
|
|
33563
34395
|
weekStartsOn?: WeekStartDay;
|
|
33564
34396
|
}
|
|
33565
|
-
interface ContainsInput extends CompareOptions {
|
|
33566
|
-
end: TimeInput;
|
|
33567
|
-
start: TimeInput;
|
|
33568
|
-
value: TimeInput;
|
|
33569
|
-
}
|
|
33570
|
-
interface ClampInput extends CompareOptions {
|
|
33571
|
-
end: TimeInput;
|
|
33572
|
-
start: TimeInput;
|
|
33573
|
-
value: TimeInput;
|
|
33574
|
-
}
|
|
33575
34397
|
type FormatOptions =
|
|
33576
34398
|
| { intl: Intl.DateTimeFormatOptions; locale?: Intl.LocalesArgument; pattern?: never; timeZone?: string }
|
|
33577
34399
|
| { intl?: never; locale?: Intl.LocalesArgument; pattern?: FormatPattern; timeZone?: string };
|
|
33578
34400
|
interface RelativeFormatOptions extends TimeZoneOptions {
|
|
33579
|
-
base?:
|
|
34401
|
+
base?: AbsoluteTime;
|
|
33580
34402
|
locale?: Intl.LocalesArgument;
|
|
33581
34403
|
numeric?: Intl.RelativeTimeFormatNumeric;
|
|
33582
34404
|
style?: Intl.RelativeTimeFormatStyle;
|
|
@@ -33585,26 +34407,18 @@ interface DurationFormatOptions {
|
|
|
33585
34407
|
locale?: Intl.LocalesArgument;
|
|
33586
34408
|
style?: 'digital' | 'long' | 'narrow' | 'short';
|
|
33587
34409
|
}
|
|
33588
|
-
interface ClassifyExpiryInput extends TimeZoneOptions {
|
|
33589
|
-
value: TimeInput;
|
|
33590
|
-
thresholds: ExpiryThresholds;
|
|
33591
|
-
relativeTo?: Temporal.Instant;
|
|
33592
|
-
}
|
|
33593
|
-
type RecurrenceRule = { frequency: 'daily' | 'monthly' | 'weekly' | 'yearly'; interval?: number } & (
|
|
33594
|
-
| { count: number; until?: TimeInput }
|
|
33595
|
-
| { count?: number; until: TimeInput }
|
|
33596
|
-
);
|
|
33597
34410
|
```
|
|
33598
34411
|
|
|
33599
34412
|
## Errors
|
|
33600
34413
|
|
|
33601
|
-
| Error | Trigger
|
|
33602
|
-
| ---------------------------- |
|
|
33603
|
-
| `TempoError` | Base Tempo error
|
|
33604
|
-
| `
|
|
33605
|
-
| `
|
|
33606
|
-
| `
|
|
33607
|
-
| `
|
|
34414
|
+
| Error | Trigger | Notable properties |
|
|
34415
|
+
| ---------------------------- | --------------------------------------- | --------------------------------------------- |
|
|
34416
|
+
| `TempoError` | Base Tempo error | `instanceof TempoError` narrows every subtype |
|
|
34417
|
+
| `CadenceError` | Cadence rule cannot be parsed/expanded | Also exported from `@vielzeug/tempo/cadence` |
|
|
34418
|
+
| `TempoInvalidInputError` | Invalid parse or duration input | Extends `TempoError` |
|
|
34419
|
+
| `TempoInvalidTzError` | Invalid IANA zone or offset | Extends `TempoError` |
|
|
34420
|
+
| `TempoMissingTzError` | Wall time without required `timeZone` | Extends `TempoError` |
|
|
34421
|
+
| `TempoUnsupportedInputError` | Non-Temporal input passed to conversion | Extends `TempoError` |
|
|
33608
34422
|
|
|
33609
34423
|
Every Tempo error thrown from `parse()`, `parseDuration()`, and timezone validation carries the original Temporal error on its `cause` property (ES2022). Inspect `err.cause` for root-cause details when debugging.
|
|
33610
34424
|
|
|
@@ -33638,10 +34452,10 @@ const birthday = parse('2026-03-21', { as: 'plainDate' });
|
|
|
33638
34452
|
|
|
33639
34453
|
## Convert Timezones
|
|
33640
34454
|
|
|
33641
|
-
Use `
|
|
34455
|
+
Use `toZoned()` to project a value into a display timezone. Use `toInstant()` only when resolving a wall-clock value.
|
|
33642
34456
|
|
|
33643
34457
|
```ts
|
|
33644
|
-
import {
|
|
34458
|
+
import { parse, toInstant, toZoned } from '@vielzeug/tempo';
|
|
33645
34459
|
|
|
33646
34460
|
const local = parse('2026-11-01T01:30:00', { as: 'plainDateTime' });
|
|
33647
34461
|
const firstOccurrence = toInstant(local, {
|
|
@@ -33649,48 +34463,28 @@ const firstOccurrence = toInstant(local, {
|
|
|
33649
34463
|
timeZone: 'America/New_York',
|
|
33650
34464
|
});
|
|
33651
34465
|
|
|
33652
|
-
const berlin =
|
|
34466
|
+
const berlin = toZoned(firstOccurrence, { timeZone: 'Europe/Berlin' });
|
|
33653
34467
|
```
|
|
33654
34468
|
|
|
33655
34469
|
## Calculate and Compare
|
|
33656
34470
|
|
|
33657
|
-
Use Tempo helpers when an operation must resolve timezones
|
|
34471
|
+
Use Tempo helpers when an operation must resolve timezones or compare calendar units. Use Temporal methods directly when values are already the exact kind and timezone you need.
|
|
33658
34472
|
|
|
33659
34473
|
```ts
|
|
33660
|
-
import {
|
|
34474
|
+
import { difference, isAfter, isBefore, isSame, parse, shift } from '@vielzeug/tempo';
|
|
33661
34475
|
|
|
33662
34476
|
const start = parse('2026-03-21T10:00:00Z', { as: 'instant' });
|
|
33663
34477
|
const end = parse('2026-03-21T12:00:00Z', { as: 'instant' });
|
|
33664
|
-
const value = parse('2026-03-21T13:00:00Z', { as: 'instant' });
|
|
33665
34478
|
|
|
33666
34479
|
const duration = difference({ end, largestUnit: 'hour', start });
|
|
33667
|
-
const
|
|
33668
|
-
|
|
34480
|
+
const isWithinWindow = isAfter(end, start) && isBefore(end, parse('2026-03-21T14:00:00Z', { as: 'instant' }));
|
|
34481
|
+
|
|
34482
|
+
const sameDay = isSame(start, end, { timeZone: 'UTC', unit: 'day' });
|
|
33669
34483
|
|
|
33670
34484
|
const local = parse('2026-03-08T01:30:00', { as: 'plainDateTime' });
|
|
33671
34485
|
const tomorrow = shift(local, { days: 1 }, { timeZone: 'America/New_York' });
|
|
33672
34486
|
```
|
|
33673
34487
|
|
|
33674
|
-
## Classify Expiry
|
|
33675
|
-
|
|
33676
|
-
Use fixed elapsed-time thresholds in milliseconds or larger units. Handle `null` as the unclassified state instead of adding a far-future catch-all.
|
|
33677
|
-
|
|
33678
|
-
```ts
|
|
33679
|
-
import { classifyExpiry, parse } from '@vielzeug/tempo';
|
|
33680
|
-
|
|
33681
|
-
const status = classifyExpiry({
|
|
33682
|
-
relativeTo: parse('2026-06-01T00:00:00Z', { as: 'instant' }),
|
|
33683
|
-
thresholds: {
|
|
33684
|
-
expired: { days: 0 },
|
|
33685
|
-
critical: { days: 3 },
|
|
33686
|
-
warning: { days: 14 },
|
|
33687
|
-
},
|
|
33688
|
-
value: parse('2026-06-04T00:00:00Z', { as: 'instant' }),
|
|
33689
|
-
});
|
|
33690
|
-
|
|
33691
|
-
const label = status ?? 'safe';
|
|
33692
|
-
```
|
|
33693
|
-
|
|
33694
34488
|
## Format Values
|
|
33695
34489
|
|
|
33696
34490
|
Use `format()` for UI, `formatInstant()` for transport, and `formatZoned()` for a zoned ISO string.
|
|
@@ -33718,33 +34512,18 @@ formatTimer({ milliseconds: 3_753_000 }); // '1:02:33'
|
|
|
33718
34512
|
formatTimer('PT5M', { hours: 'always' }); // '0:05:00'
|
|
33719
34513
|
```
|
|
33720
34514
|
|
|
33721
|
-
## Generate Calendar Sequences
|
|
33722
|
-
|
|
33723
|
-
Use zoned values when the sequence already has a timezone. Plain and instant starts require `timeZone`.
|
|
33724
|
-
|
|
33725
|
-
```ts
|
|
33726
|
-
import { dateRange, parse, recurrence } from '@vielzeug/tempo';
|
|
33727
|
-
|
|
33728
|
-
const start = parse('2026-03-01T09:00:00[America/New_York]', { as: 'zonedDateTime' });
|
|
33729
|
-
const end = parse('2026-03-03T09:00:00[America/New_York]', { as: 'zonedDateTime' });
|
|
33730
|
-
|
|
33731
|
-
const days = [...dateRange(start, end, { days: 1 })];
|
|
33732
|
-
const meetings = [...recurrence(start, { count: 4, frequency: 'weekly', interval: 2 })];
|
|
33733
|
-
```
|
|
33734
|
-
|
|
33735
|
-
Both functions advance with zoned calendar arithmetic. Non-advancing range steps, invalid recurrence intervals, and negative or fractional counts throw `TempoInvalidInputError`.
|
|
33736
|
-
|
|
33737
34515
|
## Testing
|
|
33738
34516
|
|
|
33739
|
-
Pin
|
|
34517
|
+
Pin reference instants so relative and boundary assertions stay deterministic.
|
|
33740
34518
|
|
|
33741
34519
|
```ts
|
|
33742
|
-
import {
|
|
34520
|
+
import { formatRelative, parse, startOf } from '@vielzeug/tempo';
|
|
33743
34521
|
|
|
33744
|
-
const
|
|
33745
|
-
const value = parse('2026-
|
|
34522
|
+
const base = parse('2026-06-01T00:00:00Z', { as: 'instant' });
|
|
34523
|
+
const value = parse('2026-06-04T00:00:00Z', { as: 'instant' });
|
|
33746
34524
|
|
|
33747
|
-
|
|
34525
|
+
formatRelative(value, { base, locale: 'en-US' }); // 'in 3 days'
|
|
34526
|
+
startOf(value, 'month').toString(); // '2026-06-01T00:00:00+00:00[UTC]'
|
|
33748
34527
|
```
|
|
33749
34528
|
|
|
33750
34529
|
## Framework Integration
|
|
@@ -33800,9 +34579,7 @@ const expiresAt = now({ timeZone: 'UTC' }).add({ minutes: 30 }).toInstant();
|
|
|
33800
34579
|
|
|
33801
34580
|
- Parse strings with their actual temporal meaning and pass `timeZone` when resolving plain values.
|
|
33802
34581
|
- Use `disambiguation` for DST overlap and gap handling.
|
|
33803
|
-
- Use Tempo helpers for timezone resolution
|
|
33804
|
-
- Use fixed duration units for expiry thresholds.
|
|
33805
|
-
- Reject non-advancing range and recurrence configuration.
|
|
34582
|
+
- Use Tempo helpers for timezone resolution and calendar units; use Temporal directly for already-normalized values.
|
|
33806
34583
|
- Store instants for transport and database values.
|
|
33807
34584
|
- Use `formatInstant()` for machine output and `format()` for user-facing text.
|
|
33808
34585
|
- Pass `timeZone` to `formatRelative()` when month and year boundaries must use a specific region.
|
|
@@ -33812,14 +34589,12 @@ const expiresAt = now({ timeZone: 'UTC' }).add({ minutes: 30 }).toInstant();
|
|
|
33812
34589
|
## Examples
|
|
33813
34590
|
|
|
33814
34591
|
- [DST-Safe Arithmetic](./examples/dst-safe-arithmetic.md)
|
|
33815
|
-
- [Date Ranges and Recurrence](./examples/date-ranges-and-recurrence.md)
|
|
33816
34592
|
- [Locale Formatting](./examples/locale-formatting.md)
|
|
33817
34593
|
- [Timezone Conversion](./examples/timezone-conversion.md)
|
|
33818
|
-
- [Expiry Classification](./examples/expiry-classification.md)
|
|
33819
34594
|
|
|
33820
34595
|
### REPL Examples
|
|
33821
34596
|
|
|
33822
|
-
- Timezone-Aware Arithmetic and
|
|
34597
|
+
- Timezone-Aware Arithmetic and Formatting (id: `meeting-duration`)
|
|
33823
34598
|
|
|
33824
34599
|
---
|
|
33825
34600
|
|
|
@@ -33831,7 +34606,7 @@ const expiresAt = now({ timeZone: 'UTC' }).add({ minutes: 30 }).toInstant();
|
|
|
33831
34606
|
|
|
33832
34607
|
## Why Vault?
|
|
33833
34608
|
|
|
33834
|
-
Vault gives browser and SQLite persistence one typed schema while keeping backend guarantees explicit. Use `KeyValueVaultStore` for portable CRUD and observation; choose IndexedDB or the opt-in SQLite subpath when you need atomic transactions or lazy iteration. Durable adapters require
|
|
34609
|
+
Vault gives browser and SQLite persistence one typed schema while keeping backend guarantees explicit. Use `KeyValueVaultStore` for portable CRUD and observation; choose IndexedDB or the opt-in SQLite subpath when you need atomic transactions or lazy iteration. Durable adapters require parsers so invalid stored data never enters typed code.
|
|
33835
34610
|
|
|
33836
34611
|
```ts
|
|
33837
34612
|
// Before
|
|
@@ -33850,10 +34625,10 @@ const theme = await store.get('preferences', 'theme');
|
|
|
33850
34625
|
| Typed schema and keys | | Application-defined | |
|
|
33851
34626
|
| Portable key-value store API | | | IndexedDB only |
|
|
33852
34627
|
| Explicit atomic transactions | IndexedDB + SQLite capability | | |
|
|
33853
|
-
| Required durable
|
|
34628
|
+
| Required durable parsers | | | |
|
|
33854
34629
|
| Driver-neutral SQLite | Opt-in subpath | | |
|
|
33855
34630
|
|
|
33856
|
-
**Use Vault when** you need typed browser persistence or application-owned SQLite with honest storage capabilities and required durable
|
|
34631
|
+
**Use Vault when** you need typed browser persistence or application-owned SQLite with honest storage capabilities and required durable parsers.
|
|
33857
34632
|
|
|
33858
34633
|
**Consider raw Web Storage when** you only persist one or two unstructured values. **Consider Dexie when** you need a broader IndexedDB ecosystem.
|
|
33859
34634
|
|
|
@@ -33873,7 +34648,7 @@ yarn add @vielzeug/vault
|
|
|
33873
34648
|
|
|
33874
34649
|
## Quick Start
|
|
33875
34650
|
|
|
33876
|
-
Define a schema, create a key-value store with
|
|
34651
|
+
Define a schema, create a key-value store with parsers, and dispose it with its owner.
|
|
33877
34652
|
|
|
33878
34653
|
```ts
|
|
33879
34654
|
import { s } from '@vielzeug/spell';
|
|
@@ -33884,7 +34659,7 @@ const PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'ligh
|
|
|
33884
34659
|
const store = createLocalStorage({
|
|
33885
34660
|
name: 'app-v2',
|
|
33886
34661
|
schema: { preferences: table('id') },
|
|
33887
|
-
|
|
34662
|
+
parsers: { preferences: PreferenceSchema },
|
|
33888
34663
|
});
|
|
33889
34664
|
|
|
33890
34665
|
try {
|
|
@@ -33898,12 +34673,12 @@ try {
|
|
|
33898
34673
|
## Features
|
|
33899
34674
|
|
|
33900
34675
|
- `table()` defines typed records with portable string or number keys.
|
|
33901
|
-
- Spell and other parser schemas work directly as
|
|
33902
|
-
- `/memory` returns a portable `DocumentVaultStore` with `batch()` and `iterate()`:
|
|
33903
|
-
- `/local-storage` and `/session-storage` return `KeyValueVaultStore`:
|
|
34676
|
+
- Spell and other parser schemas work directly as per-table parsers.
|
|
34677
|
+
- `/memory` returns a portable `DocumentVaultStore` with `batch()` and `iterate()`: parsers optional (in-memory, no trust boundary).
|
|
34678
|
+
- `/local-storage` and `/session-storage` return `KeyValueVaultStore`: parsers required.
|
|
33904
34679
|
- `observe()` emits current and changed table snapshots.
|
|
33905
34680
|
- `ttl` creates validated expiration durations.
|
|
33906
|
-
- `/indexeddb` and `/sqlite` return `DocumentVaultStore` with `batch()` and `iterate()`:
|
|
34681
|
+
- `/indexeddb` and `/sqlite` return `DocumentVaultStore` with `batch()` and `iterate()`: parsers required. `/memory` shares the same contract without parsers.
|
|
33907
34682
|
- `/indexeddb` accepts a `migrate` hook for schema upgrades the table schema cannot express.
|
|
33908
34683
|
- `pruneExpired()` removes stale TTL entries on demand.
|
|
33909
34684
|
- Bound helpers (`has`, `count`, `update`, `upsert`, `getMany`, `keys`, `deleteMany`) are available on every store and transaction context.
|
|
@@ -33925,28 +34700,27 @@ try {
|
|
|
33925
34700
|
|
|
33926
34701
|
## API Overview
|
|
33927
34702
|
|
|
33928
|
-
| Symbol | Purpose | Execution mode | Common gotcha
|
|
33929
|
-
| ------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------- |
|
|
33930
|
-
| `createMemory()` | In-memory document store | Async API | Import from `/memory`;
|
|
33931
|
-
| `createLocalStorage()` / `createSessionStorage()` | Web Storage-backed key-value stores | Async API |
|
|
33932
|
-
| `createIndexedDB()` | Browser document store with transactions and cursor iteration | Async API | Import from `/indexeddb`;
|
|
33933
|
-
| `createSQLite()` | Driver-neutral SQLite document store | Async API over a synchronous driver | Import from `/sqlite`;
|
|
33934
|
-
| `table()` | Typed record schema | Sync | The key field must be a string or finite number
|
|
33935
|
-
| `
|
|
33936
|
-
| `ttl` | Valid expiration durations | Sync | Durations must be positive |
|
|
34703
|
+
| Symbol | Purpose | Execution mode | Common gotcha |
|
|
34704
|
+
| ------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------- |
|
|
34705
|
+
| `createMemory()` | In-memory document store | Async API | Import from `/memory`; parsers optional |
|
|
34706
|
+
| `createLocalStorage()` / `createSessionStorage()` | Web Storage-backed key-value stores | Async API | Parsers required; available only where the corresponding Web API exists |
|
|
34707
|
+
| `createIndexedDB()` | Browser document store with transactions and cursor iteration | Async API | Import from `/indexeddb`; parsers required |
|
|
34708
|
+
| `createSQLite()` | Driver-neutral SQLite document store | Async API over a synchronous driver | Import from `/sqlite`; parsers required |
|
|
34709
|
+
| `table()` | Typed record schema | Sync | The key field must be a string or finite number |
|
|
34710
|
+
| `ttl` | Valid expiration durations | Sync | Durations must be positive |
|
|
33937
34711
|
|
|
33938
34712
|
## Package Entry Points
|
|
33939
34713
|
|
|
33940
34714
|
| Import | Purpose |
|
|
33941
34715
|
| --------------------------------- | ----------------------------------------------------------------------------- |
|
|
33942
|
-
| `@vielzeug/vault` | Adapter-free schemas, TTL, errors,
|
|
34716
|
+
| `@vielzeug/vault` | Adapter-free schemas, TTL, errors, parsers, derived helpers, and shared types |
|
|
33943
34717
|
| `@vielzeug/vault/memory` | `createMemory` |
|
|
33944
34718
|
| `@vielzeug/vault/local-storage` | `createLocalStorage` |
|
|
33945
34719
|
| `@vielzeug/vault/session-storage` | `createSessionStorage` |
|
|
33946
34720
|
| `@vielzeug/vault/indexeddb` | `createIndexedDB`, the `migrate` upgrade-hook types, and IndexedDB-only types |
|
|
33947
34721
|
| `@vielzeug/vault/sqlite` | `createSQLite`, the SQLite driver protocol types, and `TransactionContext` |
|
|
33948
34722
|
|
|
33949
|
-
## Schemas,
|
|
34723
|
+
## Schemas, Parsers, and TTL
|
|
33950
34724
|
|
|
33951
34725
|
### `table()`
|
|
33952
34726
|
|
|
@@ -33963,7 +34737,7 @@ Defines a typed table and its primary-key field.
|
|
|
33963
34737
|
| -------------------- | ---------------------------------------------------------------- |
|
|
33964
34738
|
| `key` | A record field whose values are `string` or finite `number` keys |
|
|
33965
34739
|
| `options.defaultTtl` | Per-table default TTL in milliseconds |
|
|
33966
|
-
| `options.indexes` | IndexedDB secondary index fields
|
|
34740
|
+
| `options.indexes` | IndexedDB-only secondary index fields (`getAllByIndex()`) |
|
|
33967
34741
|
|
|
33968
34742
|
**Returns:** A `SchemaEntry` describing the table.
|
|
33969
34743
|
|
|
@@ -33978,31 +34752,6 @@ const users = table('id', {
|
|
|
33978
34752
|
|
|
33979
34753
|
---
|
|
33980
34754
|
|
|
33981
|
-
### `validatorCodec()`
|
|
33982
|
-
|
|
33983
|
-
```ts
|
|
33984
|
-
function validatorCodec(validator: { parse(value: unknown): T }): RecordCodec;
|
|
33985
|
-
```
|
|
33986
|
-
|
|
33987
|
-
Wraps any object with a `parse(value): T` method as an identity-encoding `RecordCodec`. Parser schemas can also be passed directly in `codecs`; a Spell schema requires no adapter.
|
|
33988
|
-
|
|
33989
|
-
**Returns:** A `RecordCodec`.
|
|
33990
|
-
|
|
33991
|
-
```ts
|
|
33992
|
-
import { s } from '@vielzeug/spell';
|
|
33993
|
-
|
|
33994
|
-
const UserSchema = s.object({ id: s.number(), name: s.string() });
|
|
33995
|
-
const store = createLocalStorage({
|
|
33996
|
-
name: 'app',
|
|
33997
|
-
schema: { users: table('id') },
|
|
33998
|
-
codecs: { users: UserSchema },
|
|
33999
|
-
});
|
|
34000
|
-
```
|
|
34001
|
-
|
|
34002
|
-
Custom `RecordCodec` values validate writes by round-tripping `decode(encode(value))`. IndexedDB codecs must preserve declared indexed field names and values in their encoded object.
|
|
34003
|
-
|
|
34004
|
-
---
|
|
34005
|
-
|
|
34006
34755
|
### `ttl`
|
|
34007
34756
|
|
|
34008
34757
|
```ts
|
|
@@ -34027,7 +34776,7 @@ const cacheLifetime = ttl.minutes(5);
|
|
|
34027
34776
|
|
|
34028
34777
|
## Factories
|
|
34029
34778
|
|
|
34030
|
-
Durable factories (LocalStorage, SessionStorage, IndexedDB, SQLite) require `
|
|
34779
|
+
Durable factories (LocalStorage, SessionStorage, IndexedDB, SQLite) require `parsers`. Memory may omit them.
|
|
34031
34780
|
|
|
34032
34781
|
### `createMemory()`
|
|
34033
34782
|
|
|
@@ -34035,12 +34784,12 @@ Durable factories (LocalStorage, SessionStorage, IndexedDB, SQLite) require `cod
|
|
|
34035
34784
|
function createMemory(options: MemoryStoreOptions): DocumentVaultStore;
|
|
34036
34785
|
```
|
|
34037
34786
|
|
|
34038
|
-
Creates an in-memory document store with `batch()` and `iterate()`. `batch()` snapshots the declared tables and restores them when the callback throws.
|
|
34787
|
+
Creates an in-memory document store with `batch()` and `iterate()`. `batch()` snapshots the declared tables and restores them when the callback throws. Parsers are optional because memory values never cross a trust boundary.
|
|
34039
34788
|
|
|
34040
34789
|
| Parameter | Description |
|
|
34041
34790
|
| --------- | --------------------------- |
|
|
34042
34791
|
| `schema` | Tables created by `table()` |
|
|
34043
|
-
| `
|
|
34792
|
+
| `parsers` | Optional per-table parsers |
|
|
34044
34793
|
|
|
34045
34794
|
**Returns:** `DocumentVaultStore`.
|
|
34046
34795
|
|
|
@@ -34063,12 +34812,12 @@ function createLocalStorage(
|
|
|
34063
34812
|
): KeyValueVaultStore;
|
|
34064
34813
|
```
|
|
34065
34814
|
|
|
34066
|
-
Creates a namespaced `localStorage` store.
|
|
34815
|
+
Creates a namespaced `localStorage` store. Parsers are required.
|
|
34067
34816
|
|
|
34068
34817
|
| Parameter | Description |
|
|
34069
34818
|
| --------- | --------------------------- |
|
|
34070
34819
|
| `schema` | Tables created by `table()` |
|
|
34071
|
-
| `
|
|
34820
|
+
| `parsers` | Required per-table parsers |
|
|
34072
34821
|
| `name` | Required storage namespace |
|
|
34073
34822
|
|
|
34074
34823
|
A write that exceeds the browser quota rejects with `VaultQuotaError`.
|
|
@@ -34082,7 +34831,7 @@ import { createLocalStorage } from '@vielzeug/vault/local-storage';
|
|
|
34082
34831
|
const store = createLocalStorage({
|
|
34083
34832
|
name: 'app',
|
|
34084
34833
|
schema: { settings: table('id') },
|
|
34085
|
-
|
|
34834
|
+
parsers: { settings: SettingsSchema },
|
|
34086
34835
|
});
|
|
34087
34836
|
```
|
|
34088
34837
|
|
|
@@ -34109,7 +34858,7 @@ import { createSessionStorage } from '@vielzeug/vault/session-storage';
|
|
|
34109
34858
|
const store = createSessionStorage({
|
|
34110
34859
|
name: 'checkout',
|
|
34111
34860
|
schema: { cart: table('id') },
|
|
34112
|
-
|
|
34861
|
+
parsers: { cart: CartSchema },
|
|
34113
34862
|
});
|
|
34114
34863
|
```
|
|
34115
34864
|
|
|
@@ -34127,12 +34876,12 @@ function createIndexedDB(
|
|
|
34127
34876
|
): IndexedDbVaultStore;
|
|
34128
34877
|
```
|
|
34129
34878
|
|
|
34130
|
-
Creates an IndexedDB document store with atomic batches, lazy cursor iteration, and optional schema migrations.
|
|
34879
|
+
Creates an IndexedDB document store with atomic batches, lazy cursor iteration, and optional schema migrations. Parsers are required.
|
|
34131
34880
|
|
|
34132
34881
|
| Parameter | Description |
|
|
34133
34882
|
| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
34134
34883
|
| `schema` | Tables and IndexedDB secondary indexes |
|
|
34135
|
-
| `
|
|
34884
|
+
| `parsers` | Required per-table parsers |
|
|
34136
34885
|
| `name` | Required database name |
|
|
34137
34886
|
| `version` | Positive schema version; defaults to `1` |
|
|
34138
34887
|
| `migrate` | Synchronous `onupgradeneeded` callback. Object stores and schema-declared indexes are created automatically; use the hook only for deletes or record transforms |
|
|
@@ -34146,7 +34895,7 @@ import { createIndexedDB } from '@vielzeug/vault/indexeddb';
|
|
|
34146
34895
|
const store = createIndexedDB({
|
|
34147
34896
|
name: 'app',
|
|
34148
34897
|
schema: { users: table('id', { indexes: ['role'] }) },
|
|
34149
|
-
|
|
34898
|
+
parsers: { users: UserSchema },
|
|
34150
34899
|
});
|
|
34151
34900
|
|
|
34152
34901
|
const admins = await store.getAllByIndex('users', 'role', 'admin');
|
|
@@ -34160,12 +34909,12 @@ const admins = await store.getAllByIndex('users', 'role', 'admin');
|
|
|
34160
34909
|
function createSQLite(options: SQLiteVaultOptions): DocumentVaultStore;
|
|
34161
34910
|
```
|
|
34162
34911
|
|
|
34163
|
-
Creates a namespaced SQLite document store with atomic batches and keyset-paginated iteration.
|
|
34912
|
+
Creates a namespaced SQLite document store with atomic batches and keyset-paginated iteration. Parsers are required. It accepts an application-provided positional-parameter driver and never opens or imports a runtime driver.
|
|
34164
34913
|
|
|
34165
34914
|
| Parameter | Description |
|
|
34166
34915
|
| ---------------- | ---------------------------------------------------------- |
|
|
34167
34916
|
| `schema` | Tables created by `table()` |
|
|
34168
|
-
| `
|
|
34917
|
+
| `parsers` | Required per-table parsers |
|
|
34169
34918
|
| `database` | Caller-provided `SQLiteDatabase` connection |
|
|
34170
34919
|
| `name` | Namespace within the connection |
|
|
34171
34920
|
| `closeOnDispose` | Closes the connection during disposal; defaults to `false` |
|
|
@@ -34182,11 +34931,11 @@ const store = createSQLite({
|
|
|
34182
34931
|
database: new DatabaseSync(':memory:'),
|
|
34183
34932
|
name: 'tests',
|
|
34184
34933
|
schema: { users: table('id') },
|
|
34185
|
-
|
|
34934
|
+
parsers: { users: UserSchema },
|
|
34186
34935
|
});
|
|
34187
34936
|
```
|
|
34188
34937
|
|
|
34189
|
-
Node `DatabaseSync`, Bun `Database`, and Deno `jsr:@db/sqlite` `Database` satisfy the protocol.
|
|
34938
|
+
Node `DatabaseSync`, Bun `Database`, and Deno `jsr:@db/sqlite` `Database` satisfy the protocol. Records must be JSON-compatible values. During a `batch()` callback, calls on every Vault store sharing that connection reject; use `tx.*` instead.
|
|
34190
34939
|
|
|
34191
34940
|
## Store Capabilities
|
|
34192
34941
|
|
|
@@ -34217,7 +34966,7 @@ interface KeyValueVaultStore {
|
|
|
34217
34966
|
}
|
|
34218
34967
|
```
|
|
34219
34968
|
|
|
34220
|
-
The portable key-value store API is returned by Memory and Web Storage factories. `put()`, `update()`, and `upsert()` return the canonical value produced by
|
|
34969
|
+
The portable key-value store API is returned by Memory and Web Storage factories. `put()`, `update()`, and `upsert()` return the canonical value produced by the table parser. `observe()` emits the current table snapshot by default and then emits after mutations. Listener errors never break the snapshot stream; pass `onObserverError` to the factory to report them.
|
|
34221
34970
|
|
|
34222
34971
|
---
|
|
34223
34972
|
|
|
@@ -34304,29 +35053,29 @@ type KeyOf = K extends unknown
|
|
|
34304
35053
|
```
|
|
34305
35054
|
|
|
34306
35055
|
```ts
|
|
34307
|
-
type RecordCodec = {
|
|
34308
|
-
decode(value: unknown): T;
|
|
34309
|
-
encode(value: T): unknown;
|
|
34310
|
-
};
|
|
34311
|
-
|
|
34312
35056
|
type RecordParser = { parse(value: unknown): T };
|
|
34313
|
-
type CodecInput = RecordCodec | RecordParser;
|
|
34314
35057
|
|
|
34315
|
-
type
|
|
34316
|
-
[K in keyof S]:
|
|
35058
|
+
type TableParsers = {
|
|
35059
|
+
[K in keyof S]: RecordParser>;
|
|
34317
35060
|
};
|
|
34318
35061
|
|
|
35062
|
+
type ObserverErrorHandler = (error: unknown) => void;
|
|
35063
|
+
|
|
34319
35064
|
type MemoryStoreOptions = {
|
|
34320
35065
|
schema: S;
|
|
34321
|
-
|
|
35066
|
+
parsers?: TableParsers;
|
|
35067
|
+
onObserverError?: ObserverErrorHandler;
|
|
34322
35068
|
};
|
|
34323
35069
|
|
|
34324
35070
|
type DurableStoreOptions = {
|
|
34325
35071
|
schema: S;
|
|
34326
|
-
|
|
35072
|
+
parsers: TableParsers;
|
|
35073
|
+
onObserverError?: ObserverErrorHandler;
|
|
34327
35074
|
};
|
|
34328
35075
|
```
|
|
34329
35076
|
|
|
35077
|
+
Parsers validate writes and decode persisted values: `put()` stores the parser's canonical output, so a record that parses can always be read back. Records must be JSON-safe (use ISO strings for dates) to survive every adapter's serialization. Spell schemas satisfy `RecordParser` directly.
|
|
35078
|
+
|
|
34330
35079
|
```ts
|
|
34331
35080
|
type MigrationContext = {
|
|
34332
35081
|
db: IDBDatabase;
|
|
@@ -34379,13 +35128,13 @@ interface TransactionContext {
|
|
|
34379
35128
|
|
|
34380
35129
|
## Errors
|
|
34381
35130
|
|
|
34382
|
-
| Error | Trigger
|
|
34383
|
-
| --------------------- |
|
|
34384
|
-
| `VaultError` | Any Vault-originated validation, serialization, storage, or
|
|
34385
|
-
| `VaultDisposedError` | An operation after the store or observer hub is disposed
|
|
34386
|
-
| `VaultScopeError` | A `batch()` callback accesses a table outside its declared scope
|
|
34387
|
-
| `VaultQuotaError` | A LocalStorage or SessionStorage write exceeds the browser quota
|
|
34388
|
-
| `VaultMigrationError` | An IndexedDB migration callback throws
|
|
35131
|
+
| Error | Trigger |
|
|
35132
|
+
| --------------------- | ------------------------------------------------------------------------ |
|
|
35133
|
+
| `VaultError` | Any Vault-originated validation, serialization, storage, or parser error |
|
|
35134
|
+
| `VaultDisposedError` | An operation after the store or observer hub is disposed |
|
|
35135
|
+
| `VaultScopeError` | A `batch()` callback accesses a table outside its declared scope |
|
|
35136
|
+
| `VaultQuotaError` | A LocalStorage or SessionStorage write exceeds the browser quota |
|
|
35137
|
+
| `VaultMigrationError` | An IndexedDB migration callback throws |
|
|
34389
35138
|
|
|
34390
35139
|
Every listed error extends `VaultError`.
|
|
34391
35140
|
|
|
@@ -34393,7 +35142,7 @@ Every listed error extends `VaultError`.
|
|
|
34393
35142
|
|
|
34394
35143
|
## Basic Usage
|
|
34395
35144
|
|
|
34396
|
-
Create a key-value store with a schema and
|
|
35145
|
+
Create a key-value store with a schema and parsers, then write a typed row.
|
|
34397
35146
|
|
|
34398
35147
|
```ts
|
|
34399
35148
|
import { s } from '@vielzeug/spell';
|
|
@@ -34409,7 +35158,7 @@ const PreferenceSchema = s.object({ id: s.string(), theme: s.enum(['dark', 'ligh
|
|
|
34409
35158
|
const store = createLocalStorage({
|
|
34410
35159
|
name: 'app-v2',
|
|
34411
35160
|
schema: { preferences: table('id') },
|
|
34412
|
-
|
|
35161
|
+
parsers: { preferences: PreferenceSchema },
|
|
34413
35162
|
});
|
|
34414
35163
|
|
|
34415
35164
|
await store.put('preferences', { id: 'theme', theme: 'dark' });
|
|
@@ -34418,7 +35167,7 @@ console.log(await store.get('preferences', 'theme'));
|
|
|
34418
35167
|
|
|
34419
35168
|
## Create a Key-Value Store
|
|
34420
35169
|
|
|
34421
|
-
LocalStorage and SessionStorage return `KeyValueVaultStore`; Memory returns a `DocumentVaultStore` (it adds `batch()` and `iterate()`). They share portable string/number keys, bound helpers, fluent queries, TTL, and `observe()`. Memory may omit
|
|
35170
|
+
LocalStorage and SessionStorage return `KeyValueVaultStore`; Memory returns a `DocumentVaultStore` (it adds `batch()` and `iterate()`). They share portable string/number keys, bound helpers, fluent queries, TTL, and `observe()`. Memory may omit parsers; Web Storage requires them. Malformed storage envelopes are evicted lazily, while parser validation failures are surfaced without deleting persisted data.
|
|
34422
35171
|
|
|
34423
35172
|
The root entry is adapter-free. Import `createMemory` from `@vielzeug/vault/memory`, `createLocalStorage` from `@vielzeug/vault/local-storage`, or `createSessionStorage` from `@vielzeug/vault/session-storage`. Import each adapter from its focused subpath so unused backends stay out of the bundle.
|
|
34424
35173
|
|
|
@@ -34428,7 +35177,7 @@ Use a new storage name when upgrading from Vault 1. Old key and envelope formats
|
|
|
34428
35177
|
const store = createLocalStorage({
|
|
34429
35178
|
name: 'app-v2',
|
|
34430
35179
|
schema: { preferences: table('id') },
|
|
34431
|
-
|
|
35180
|
+
parsers: { preferences: PreferenceSchema },
|
|
34432
35181
|
});
|
|
34433
35182
|
```
|
|
34434
35183
|
|
|
@@ -34510,7 +35259,7 @@ const EventSchema = s.object({ id: s.number(), type: s.string() });
|
|
|
34510
35259
|
const db = createIndexedDB({
|
|
34511
35260
|
name: 'app-v2',
|
|
34512
35261
|
schema: { events: table('id') },
|
|
34513
|
-
|
|
35262
|
+
parsers: { events: EventSchema },
|
|
34514
35263
|
});
|
|
34515
35264
|
|
|
34516
35265
|
await db.batch(['events'], async (tx) => {
|
|
@@ -34538,7 +35287,7 @@ const store = createSQLite({
|
|
|
34538
35287
|
database,
|
|
34539
35288
|
name: 'app-v2',
|
|
34540
35289
|
schema: { events: table('id') },
|
|
34541
|
-
|
|
35290
|
+
parsers: { events: EventSchema },
|
|
34542
35291
|
});
|
|
34543
35292
|
|
|
34544
35293
|
await store.batch(['events'], async (tx) => {
|
|
@@ -34553,13 +35302,13 @@ SQLite stores serialize all access through the injected connection. `batch()` st
|
|
|
34553
35302
|
|
|
34554
35303
|
## Store SQLite Values and Observe Changes
|
|
34555
35304
|
|
|
34556
|
-
SQLite
|
|
35305
|
+
SQLite stores records as JSON, so records must be JSON-compatible: circular values, `bigint`, and functions fail serialization, and parsers should reject anything a schema cannot represent (use ISO strings for dates). Number and string primary keys remain distinct.
|
|
34557
35306
|
|
|
34558
35307
|
`observe()` sees mutations written through Vault stores sharing the same injected connection after a commit. It cannot detect direct SQL changes, writes from another process, or writes through another connection. The connection belongs to the caller by default; use `closeOnDispose: true` only when the store owns it.
|
|
34559
35308
|
|
|
34560
35309
|
## Handle IndexedDB Schema Migrations
|
|
34561
35310
|
|
|
34562
|
-
Declare IndexedDB indexes in the schema.
|
|
35311
|
+
Declare IndexedDB indexes in the schema; other adapters ignore them and `getAllByIndex()` is IndexedDB-only. Because writes store the parser's canonical output, indexed fields always match what readers see. Use `migrate` only for IndexedDB version upgrades and mirror Vault's fixed `value.` index path.
|
|
34563
35312
|
|
|
34564
35313
|
```ts
|
|
34565
35314
|
import { s } from '@vielzeug/spell';
|
|
@@ -34611,7 +35360,7 @@ Keep Ripple signals as application state and persist selected changes through Va
|
|
|
34611
35360
|
|
|
34612
35361
|
- Define one schema per storage namespace.
|
|
34613
35362
|
- Use string or finite-number primary keys only.
|
|
34614
|
-
- Provide
|
|
35363
|
+
- Provide parsers for every durable adapter; pass a Spell schema directly for validation or a bare `{ parse }` for passthrough.
|
|
34615
35364
|
- Use `observe()` for table snapshots.
|
|
34616
35365
|
- Use IndexedDB or SQLite for atomic work.
|
|
34617
35366
|
- Keep external asynchronous work outside `batch()` callbacks.
|
|
@@ -34637,7 +35386,7 @@ const SessionSchema = s.object({ id: s.string(), token: s.string() });
|
|
|
34637
35386
|
const store = createLocalStorage({
|
|
34638
35387
|
name: 'app-v2',
|
|
34639
35388
|
schema: { sessions: table('id', { defaultTtl: ttl.hours(1) }) },
|
|
34640
|
-
|
|
35389
|
+
parsers: { sessions: SessionSchema },
|
|
34641
35390
|
});
|
|
34642
35391
|
|
|
34643
35392
|
await store.put('sessions', { id: 'current', token: 'FAKE-TOKEN-FOR-DOCS' });
|
|
@@ -34661,7 +35410,7 @@ const EventSchema = s.object({ createdAt: s.number(), id: s.number(), type: s.st
|
|
|
34661
35410
|
const db = createIndexedDB({
|
|
34662
35411
|
name: 'events',
|
|
34663
35412
|
schema: { events: table('id', { indexes: ['type'] }) },
|
|
34664
|
-
|
|
35413
|
+
parsers: { events: EventSchema },
|
|
34665
35414
|
});
|
|
34666
35415
|
|
|
34667
35416
|
await db.batch(['events'], async (tx) => {
|
|
@@ -34694,7 +35443,7 @@ const store = createSQLite({
|
|
|
34694
35443
|
database,
|
|
34695
35444
|
name: 'app',
|
|
34696
35445
|
schema: { jobs: table('id') },
|
|
34697
|
-
|
|
35446
|
+
parsers: { jobs: JobSchema },
|
|
34698
35447
|
});
|
|
34699
35448
|
|
|
34700
35449
|
await store.batch(['jobs'], async (tx) => {
|
|
@@ -34773,7 +35522,7 @@ const db = createIndexedDB({
|
|
|
34773
35522
|
migrate({ db, oldVersion, tx }) {
|
|
34774
35523
|
// The 'users' store and its 'email' index already exist; drop a retired store.
|
|
34775
35524
|
if (oldVersion ('id', { indexes: ['email'] }) },
|
|
34776
|
-
|
|
35525
|
+
parsers: { users: UserSchema },
|
|
34777
35526
|
});
|
|
34778
35527
|
```
|
|
34779
35528
|
|
|
@@ -35285,6 +36034,8 @@ router.dispose();
|
|
|
35285
36034
|
- `createHashHistory()`: Runs browser routes on static hosts that cannot rewrite deep links.
|
|
35286
36035
|
- `createMemoryHistory()`: Runs routers in tests and non-browser environments.
|
|
35287
36036
|
- `subscribe()`: Reactive subscription to navigation state changes.
|
|
36037
|
+
- `createRouteSignals()`: Mirrors navigation into ripple readables.
|
|
36038
|
+
- `createQueryState()`: Typed reactive URL query params with merged, deduplicated writes.
|
|
35288
36039
|
|
|
35289
36040
|
## Documentation
|
|
35290
36041
|
|
|
@@ -35307,6 +36058,8 @@ router.dispose();
|
|
|
35307
36058
|
| -------------------------------------------- | --------------------------------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------ |
|
|
35308
36059
|
| `createRouter(options)` | Create a router from a route table | Sync | Initial navigation starts asynchronously in the constructor |
|
|
35309
36060
|
| `createRouteSignals(router)` | Mirror a router into ripple readables (name/params/query/state) | Sync | `router.getSnapshot()` alone is not ripple-reactive: use this bridge |
|
|
36061
|
+
| `createQueryState(router, spec, options?)` | Bind typed reactive URL query params (read + merged writes) | Sync (writes async) | A codec's default must be its param-absent state |
|
|
36062
|
+
| `param.string/number/boolean/pick/list` | Built-in query-param codecs | Sync (returns codec) | Unknown URL values decode to the default, never throw |
|
|
35310
36063
|
| `createBrowserHistory()` | Create the default browser history driver | Sync | Requires server-side SPA rewrites |
|
|
35311
36064
|
| `createHashHistory(options?)` | Create a static-host-safe hash history driver | Sync | Pass the same `base` to the history and router |
|
|
35312
36065
|
| `createHistoryForBase(base)` | Pick browser vs hash history for a deploy base | Sync | Returns the hash driver for any base other than `'/'` |
|
|
@@ -35603,7 +36356,7 @@ const controller = new AbortController();
|
|
|
35603
36356
|
const state = await router.load('/dashboard', { signal: controller.signal });
|
|
35604
36357
|
```
|
|
35605
36358
|
|
|
35606
|
-
Load a
|
|
36359
|
+
Load a router-internal URL into a `RouteState` including data loader results, without modifying router state or history. Follows declarative redirects (up to five hops). Returns `null` for unmatched URLs, except when a `notFound` route is configured: then the fallback route's state (with its `data` loaded) is returned instead.
|
|
35607
36360
|
|
|
35608
36361
|
Middleware is **not** executed: `load` is a data-only prefetch for SSR and pre-rendering where middleware side effects are not wanted. If your data loaders depend on `ctx.locals` set by middleware, use `navigate()` instead.
|
|
35609
36362
|
|
|
@@ -35688,16 +36441,6 @@ The guard fires when the router is leaving any route whose name appears in the `
|
|
|
35688
36441
|
|
|
35689
36442
|
**Returns:** `() => void`
|
|
35690
36443
|
|
|
35691
|
-
## `createPhaseMirror(options)`
|
|
35692
|
-
|
|
35693
|
-
Mirrors a domain state machine's phase into a `/:subject/:id/:phase` route segment: the shared routing approach for stepped flows (wizards, chapters, onboarding). Two-way, with the state machine as the sole source of truth:
|
|
35694
|
-
|
|
35695
|
-
- **Domain → URL**: every phase change lands on the phase's route, replacing so the browser back button exits the flow rather than stepping between phases.
|
|
35696
|
-
- **URL → domain**: a mismatched phase route is a revisit request (`requestRevisit`: the consumer owns its confirm dialog) when `canRevisit(current, target)` allows it, otherwise a bounce back to the actual phase. Reacts to the URL and to the domain loading, never to domain-led changes. The mirror stops following entirely when the route leaves the flow or names a different subject.
|
|
35697
|
-
- **Canonicalization**: the bare `detailRoute` URL redirects onto the current phase's route, so every arrival is shareable and reload-safe.
|
|
35698
|
-
|
|
35699
|
-
Options carry the router, the valid `phases`, both route names, and ripple `Readable`s for `currentPhase` and `subjectId` (`null` while the subject is missing). The mirror exposes `routePhase`, `revisitPhases` (readables), `phaseHref`, `followPhase`, `bounceIfMismatched` (the dialog cancel path), and `dispose()`.
|
|
35700
|
-
|
|
35701
36444
|
## `createRouteSignals(router)`
|
|
35702
36445
|
|
|
35703
36446
|
```ts
|
|
@@ -35712,6 +36455,49 @@ Mirrors a router into ripple readables so templates and computeds react to navig
|
|
|
35712
36455
|
|
|
35713
36456
|
**Returns:** `RouteSignals`: `name` (deepest matched route name, `null` while nothing matches), `params` (its path params), `query` (raw string-valued query params of the current location), and `state` (the full `RouteState`, for deriving further computeds).
|
|
35714
36457
|
|
|
36458
|
+
## `createQueryState(router, spec, options?)`
|
|
36459
|
+
|
|
36460
|
+
```ts
|
|
36461
|
+
import { createQueryState, param } from '@vielzeug/wayfinder';
|
|
36462
|
+
|
|
36463
|
+
const filters = createQueryState(router, {
|
|
36464
|
+
q: param.string(),
|
|
36465
|
+
page: param.number(1),
|
|
36466
|
+
sort: param.pick(['price', 'name'] as const, 'price'),
|
|
36467
|
+
inStock: param.boolean(),
|
|
36468
|
+
tags: param.list(),
|
|
36469
|
+
});
|
|
36470
|
+
|
|
36471
|
+
filters.params.page.value; // 1 when ?page is absent or malformed
|
|
36472
|
+
filters.query.value; // the whole typed view as one computed
|
|
36473
|
+
await filters.set({ page: 2 }); // merged write; default values are omitted from the URL
|
|
36474
|
+
await filters.reset(); // clear every declared param
|
|
36475
|
+
```
|
|
36476
|
+
|
|
36477
|
+
Binds a declared param schema to a router as reactive readables: reads recompute on every navigation, and writes merge into the current URL — params you did not declare, the hash, and the path are preserved. Each write issues one `router.navigate()` with `replace: true` by default (flip globally via `options.replace` or per write via `set(patch, { replace: false })`), so same-URL deduplication, back/forward, and leave guards keep working. Both option objects carry the router's full `NavigateOptions` and forward them untouched, so `viewTransition`, `force`, and `state` can be set for every write or overridden per write — for example `createQueryState(router, spec, { viewTransition: false })` keeps filter edits from animating on a router that transitions route changes. Setting a key outside the schema throws `WayfinderConfigError`.
|
|
36478
|
+
|
|
36479
|
+
The codec contract is one invariant: **the default is the param-absent state**. `param.number(1)` writes `?page=2` but clears the param at `1`, keeping URLs canonical and round-trips stable. Decoding is lenient on purpose: a malformed URL value falls back to the default instead of throwing, because URLs carry untrusted input.
|
|
36480
|
+
|
|
36481
|
+
Create query states once beside the router: their route signals live for the app lifetime, not the element's (same rule as `createRouteSignals`).
|
|
36482
|
+
|
|
36483
|
+
**Returns:** `QueryState`: `params` (per-key ripple `Readable`s), `query` (the full schema as one computed), `set(patch, options?)`, and `reset(options?)`.
|
|
36484
|
+
|
|
36485
|
+
---
|
|
36486
|
+
|
|
36487
|
+
## `param` codecs
|
|
36488
|
+
|
|
36489
|
+
| Codec | Absent or unknown decodes to | Wire format |
|
|
36490
|
+
| ------------------------------ | --------------------------------- | --------------------------------- |
|
|
36491
|
+
| `param.string(default?)` | `default` (`''` when omitted) | plain value |
|
|
36492
|
+
| `param.number(default?)` | `default` (`0` when omitted) | finite numeric string |
|
|
36493
|
+
| `param.boolean(default?)` | `default` (`false` when omitted) | `1`/`true` and `0`/`false` |
|
|
36494
|
+
| `param.pick(values, default?)` | `default`, or `undefined` if none | one of `values` |
|
|
36495
|
+
| `param.list()` | `[]` | repeated params (`tags=a&tags=b`) |
|
|
36496
|
+
|
|
36497
|
+
For anything else, supply a custom `ParamSpec` (`decode`, optional `default`, `encode`). Return `undefined` from `encode` to omit the param from the URL.
|
|
36498
|
+
|
|
36499
|
+
---
|
|
36500
|
+
|
|
35715
36501
|
## `redirectTo(target, options?)`
|
|
35716
36502
|
|
|
35717
36503
|
```ts
|
|
@@ -36199,35 +36985,6 @@ Thrown on middleware misuse: currently only when a middleware function calls its
|
|
|
36199
36985
|
|
|
36200
36986
|
Start with the [Overview](./index.md), then use this page for the day-to-day API.
|
|
36201
36987
|
|
|
36202
|
-
## Mirror a State Machine into the URL
|
|
36203
|
-
|
|
36204
|
-
A stepped flow's URL should name the step the domain is on: shareable, reload-safe, and never ahead of the truth. `createPhaseMirror` wires a `Router` to the domain phase as a ripple `Readable`, replacing (never pushing) so back exits the flow.
|
|
36205
|
-
|
|
36206
|
-
```ts
|
|
36207
|
-
import { createPhaseMirror } from '@vielzeug/wayfinder';
|
|
36208
|
-
import { signal } from '@vielzeug/ripple';
|
|
36209
|
-
|
|
36210
|
-
const currentPhase = signal(null);
|
|
36211
|
-
const subjectId = signal(null);
|
|
36212
|
-
|
|
36213
|
-
const mirror = createPhaseMirror({
|
|
36214
|
-
canRevisit: (current, target) => current === 'fight' && target === 'preparing',
|
|
36215
|
-
currentPhase,
|
|
36216
|
-
detailRoute: 'easyPathDetail',
|
|
36217
|
-
phases: ['story', 'preparing', 'fight'],
|
|
36218
|
-
phaseRoute: 'easyPathPhase',
|
|
36219
|
-
requestRevisit: (phase) => openConfirmDialog(phase),
|
|
36220
|
-
router,
|
|
36221
|
-
subjectId,
|
|
36222
|
-
});
|
|
36223
|
-
|
|
36224
|
-
mirror.routePhase.value; // the phase segment of the current route, or null
|
|
36225
|
-
mirror.phaseHref('preparing'); // anchor href for a tracker link
|
|
36226
|
-
mirror.dispose(); // stop mirroring
|
|
36227
|
-
```
|
|
36228
|
-
|
|
36229
|
-
The consumer supplies reactivity; the mirror never writes history. A Vue app bridges its reactive getters into ripple signals and disposes the mirror with its component scope.
|
|
36230
|
-
|
|
36231
36988
|
## Basic Usage
|
|
36232
36989
|
|
|
36233
36990
|
Create a deterministic router with memory history, wait for startup, and navigate by route name.
|
|
@@ -36612,7 +37369,7 @@ const controller = new AbortController();
|
|
|
36612
37369
|
const state = await router.load('/users/42', { signal: controller.signal });
|
|
36613
37370
|
```
|
|
36614
37371
|
|
|
36615
|
-
`load()` follows declarative redirects (up to five hops)
|
|
37372
|
+
`load()` follows declarative redirects (up to five hops) and accepts the same router-internal URLs as `url()`/`href()`. Middleware is not executed and its result is not reused by client navigation. When a `notFound` route is configured, an unmatched URL returns that fallback route's state; otherwise `load()` returns `null`.
|
|
36616
37373
|
|
|
36617
37374
|
## Preload Client Navigation
|
|
36618
37375
|
|
|
@@ -36680,6 +37437,39 @@ const user = state.matches.at(-1)?.data;
|
|
|
36680
37437
|
|
|
36681
37438
|
`waitFor` rejects immediately if the router is already in `status: 'error'`, and also rejects if `router.dispose()` is called while the promise is pending. Resolves immediately if the named route is already active and idle.
|
|
36682
37439
|
|
|
37440
|
+
## URL Query State
|
|
37441
|
+
|
|
37442
|
+
Filter controls need a two-way binding with the URL. `createQueryState` declares the schema once; reads are ripple readables and writes merge into the current URL without disturbing params it does not declare:
|
|
37443
|
+
|
|
37444
|
+
```ts
|
|
37445
|
+
import { computed } from '@vielzeug/ripple';
|
|
37446
|
+
import { createQueryState, param } from '@vielzeug/wayfinder';
|
|
37447
|
+
|
|
37448
|
+
const queryState = createQueryState(router, {
|
|
37449
|
+
q: param.string(),
|
|
37450
|
+
sort: param.pick(['newest', 'price'] as const, 'newest'),
|
|
37451
|
+
page: param.number(1),
|
|
37452
|
+
});
|
|
37453
|
+
|
|
37454
|
+
// reads react to every navigation (back/forward included)
|
|
37455
|
+
const visibleItems = computed(() => {
|
|
37456
|
+
const start = (queryState.params.page.value - 1) * pageSize;
|
|
37457
|
+
return sortedItems.value.slice(start, start + pageSize);
|
|
37458
|
+
});
|
|
37459
|
+
|
|
37460
|
+
// writes merge, replace the current entry by default, and dedupe same-URL navigations
|
|
37461
|
+
await queryState.set({ page: 1, q: term.value });
|
|
37462
|
+
```
|
|
37463
|
+
|
|
37464
|
+
Create the state once beside the router (its route signals live for the app lifetime). For a control the user is actively editing, keep a local signal for the keystroke and persist through an effect: the URL stays the persistence layer while same-URL deduplication keeps the echo silent:
|
|
37465
|
+
|
|
37466
|
+
```ts
|
|
37467
|
+
const search = signal(queryState.params.q.value); // initial value comes from the URL
|
|
37468
|
+
effect(() => void queryState.set({ q: search.value })); // persistence on every change
|
|
37469
|
+
```
|
|
37470
|
+
|
|
37471
|
+
A codec's default is its param-absent state, so `?page=1` never appears in a clean URL, and malformed values decode back to the default instead of breaking the view.
|
|
37472
|
+
|
|
36683
37473
|
## Testing
|
|
36684
37474
|
|
|
36685
37475
|
Use `createMemoryHistory` to test routers without a browser:
|