@vielzeug/codex 26.11.16 → 26.11.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/catalog.json +47 -48
- package/data/llms-full.txt +207 -236
- package/data/llms.txt +1 -1
- package/data/manifest.json +1 -1
- package/data/packages/archive.json +1 -1
- package/data/packages/lingua.json +2 -2
- package/data/packages/mesh.json +3 -3
- package/data/packages/scout.json +17 -20
- package/data/packages/tandem.json +3 -3
- package/data/packages/tavern.json +1 -1
- package/package.json +2 -2
package/data/llms.txt
CHANGED
package/data/manifest.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"apiSource": "// Public root surface of @vielzeug/archive: the browser-safe contract — the wire\n// schemas and the collection seam. The Cloudflare Worker itself\n// lives behind the `@vielzeug/archive/worker` subpath so client bundles never\n// resolve worker machinery.\nexport * from './collection';\nexport * from './contract';\nexport * from './errors';\n",
|
|
3
3
|
"docs": {
|
|
4
4
|
"index": "---\ntitle: Archive\ndescription: 'Community content publishing for Cloudflare Workers + D1: a hardened Worker core over per-collection payload schemas'\npackage: archive\ncategory: utilities\nkeywords: [cloudflare, worker, d1, community, publishing, content, catalog, gdpr]\nrelated: [spell, courier, rune]\nexports:\n [defineArchiveCollection, createArchiveWorker, createAuthWorker, archiveAuthHealthSchema, ArchiveDerivationError]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"archive\" />\n\n## Why Archive?\n\nYou can share content entries with ranked browsing, filters, likes and account\nerasure on Cloudflare Workers + D1. `defineArchiveCollection` supplies your JSON\npayload schema and indexing rules; the Worker supplies sessions, guards,\nidempotent publishing, cursors and rate limits.\n\n```ts\n// Before: each deployment repeats validation, indexing and route plumbing.\n\n// After: the deployment is one collection definition plus one factory call.\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { createArchiveWorker } from '@vielzeug/archive/worker';\nimport { s } from '@vielzeug/spell';\n\nconst notes = defineArchiveCollection({\n name: 'notes',\n contentVersion: 1,\n payloadSchema: s.object({ title: s.string().min(1).max(128) }),\n index: ({ title }) => ({ title, filter: null, tags: [] }),\n});\nexport default createArchiveWorker([notes]);\n```\n\n| Feature | Archive | Hand-rolled Worker | BaaS (Firebase/Supabase) |\n| ---------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------- |\n| Bundle size (core) | <PackageInfo package=\"archive\" type=\"size\" /> | Depends on deployment code | Depends on selected SDK |\n| Zero dependencies | No — Spell and jose | Depends on implementation | No — client SDK |\n| Content knowledge in the core | <ore-icon name=\"check\" size=\"16\"></ore-icon> none — one collection seam | <ore-icon name=\"x\" size=\"16\"></ore-icon> baked in | <ore-icon name=\"x\" size=\"16\"></ore-icon> rules everywhere |\n| Canonical fresh-database D1 schema | <ore-icon name=\"check\" size=\"16\"></ore-icon> in the package | Deployment-owned | Not a D1 backend |\n| Idempotent publish w/ tombstones | <ore-icon name=\"check\" size=\"16\"></ore-icon> built-in | <ore-icon name=\"x\" size=\"16\"></ore-icon> rebuild it | <ore-icon name=\"x\" size=\"16\"></ore-icon> rebuild it |\n| GDPR erasure / export endpoints | <ore-icon name=\"check\" size=\"16\"></ore-icon> built-in | <ore-icon name=\"x\" size=\"16\"></ore-icon> rebuild it | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> partial |\n| Strict DTO re-validation on read | <ore-icon name=\"check\" size=\"16\"></ore-icon> every entry | <ore-icon name=\"x\" size=\"16\"></ore-icon> optional | <ore-icon name=\"x\" size=\"16\"></ore-icon> optional |\n\n<div class=\"decision-callout\">\n\n**Use Archive when** an app needs a shareable, ranked, liked community space for\ncontent entries on Cloudflare Workers + D1, and can express its content as one strict\npayload schema.\n**Consider alternatives when** you need rich queries beyond filter/tag/search, live\ncollaboration, or a backend you do not control — Archive is deliberately one narrow,\nhardened surface.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/archive @vielzeug/spell\n```\n\n```sh [npm]\nnpm install @vielzeug/archive @vielzeug/spell\n```\n\n```sh [yarn]\nyarn add @vielzeug/archive @vielzeug/spell\n```\n\n:::\n\n## Quick Start\n\nA deployment is one collection definition plus one factory call. The definition\nbrings the payload schema and what to index; everything else — the emitted-entry\nenvelope, the content hash, the wire contract, the routes — is composed for you.\n\n```ts\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { createArchiveWorker } from '@vielzeug/archive/worker';\nimport { s } from '@vielzeug/spell';\n\n// The collection's payload: one strict schema is the whole content contract.\nconst payloadSchema = s.object({\n cuisine: s.enum(['italian', 'japanese']),\n ingredients: s.array(s.string().trim().min(1).max(64)).min(1).max(20),\n name: s.string().trim().min(1).max(32),\n});\n\nconst recipesCollection = defineArchiveCollection({\n canonicalize: (payload) => ({ ...payload, ingredients: [...payload.ingredients].sort() }),\n contentVersion: 1,\n filters: ['italian', 'japanese'],\n index: (payload) => ({\n filter: payload.cuisine,\n tags: [payload.ingredients.length <= 5 ? 'quick' : 'involved'],\n title: payload.name,\n }),\n name: 'recipes',\n payloadSchema,\n tags: ['quick', 'involved'],\n});\n\n// The whole Worker: routing, auth, guards, limits, SQL and DTO disciplines included.\nexport default createArchiveWorker([recipesCollection]);\n```\n\nThe browser side never imports worker machinery. The same collection's composed\nschemas parse what the routes emit:\n\n```ts\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { s } from '@vielzeug/spell';\n\nconst notes = defineArchiveCollection({\n name: 'notes',\n contentVersion: 1,\n payloadSchema: s.object({ title: s.string().min(1).max(128) }),\n index: ({ title }) => ({ title, filter: null, tags: [] }),\n});\nconst response = await fetch('/api/v1/collections/notes/entries?sort=liked');\nif (!response.ok) throw new Error('Archive unavailable');\nconst parsed = notes.contract.page.parse(await response.json());\nconsole.log(parsed.entries);\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `defineArchiveCollection` — the one content seam: payload schema, canonicalization, filter/tag/title derivation, union-typed vocabularies\n- `createArchiveWorker` — the whole routes/auth/limits/SQL stack from registered collections\n- `collection.contract` — entry, page, publish/update input schemas shared by client and Worker\n- `ARCHIVE_LIMITS` + `archiveHealthSchema` — the application bounds, advertised by health and validated on both sides\n- `archiveAuthHealthSchema` + `AUTH_SCHEMA_VERSION` — typed issuer readiness checked against the issuer DDL stamp\n- `archiveErrorResponseSchema` — the one error envelope, code-typed across the wire\n- `createAuthWorker` — scanner-safe confirmation, live session-version enforcement, durable budgets, metadata export and coordinated erasure\n- `AUTH_ISSUER_SERVICE` — signing-key retrieval and an uncached issuer check after local catalog JWT verification\n- `ArchiveDerivationError` — distinguishes faulty collection code from invalid submitted content\n- Moderation — reader reports, the operator soft-hide and the report queue, keyed on a verified `roles` claim\n- `worker.tap()` / `issuer.tap()` — typed sanitized runtime events; neither core logs by default\n- `migrations/` — canonical fresh-database DDL with the storage stamp health reads back; no upgrade framework\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md) — stand up a collection, deploy the Worker, wire the client.\n- [API Reference](./api.md) — every export, all three entry points, the full route table.\n- [Examples](./examples.md) — recipes from first deployment to GDPR erasure.\n- [Migration](./migration.md) — breaking changes after the first release and\n fresh-database scope.\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Spell](/spell/) — every payload schema here is a spell schema; the core composes envelopes from it.\n- [Courier](/courier/) — the HTTP client shape an app's frontend mirrors to consume these routes.\n- [Rune](/rune/) — the structured logger a deployment points `worker.tap()` events at.\n\n</div>\n\n<!-- markdownlint-enable MD060 MD033 MD025 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Archive: API Reference'\ndescription: 'Collection definitions, browser-safe wire schemas, Worker deployment, and identity issuance.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------------------------------------- | ------------------------------------------------------- | -------------- | --------------------------------------------------------------- |\n| `defineArchiveCollection` | Compose validation, indexing, identity and wire schemas | Sync | Invalid content derives to `null`; callback faults throw |\n| `createArchiveWorker` | Build the catalog Worker | Sync | Collection names must be unique |\n| `createAuthWorker` | Build the passwordless issuer | Sync | `AUTH_ARCHIVE` is required |\n| `worker.tap`, `issuer.tap` | Observe sanitized runtime outcomes | Sync | Neither core logs by default; observer exceptions are swallowed |\n| `ArchiveDerivationError` | Identify a collection implementation/runtime fault | Sync | Faults become sanitized 500s, not content-validation 422s |\n| `ARCHIVE_LIMITS` | Shared application bounds | Sync | Page bounds do not cap total exports |\n| `archiveErrorResponseSchema`, `archiveAuthHealthSchema` | Validate error and issuer-health responses | Sync | Unknown error codes and health states reject |\n| `ArchiveError`, `ArchiveDefinitionError` | Public base and invalid-definition errors | Sync | Thrown locally, not transmitted as error objects |\n| `sessionCookieValue` | Compose shared session-cookie attributes | Sync | Deployments must choose `secure` from their environment |\n| `isWellFormedText` | Check control characters and lone surrogates | Sync | Does not trim or impose a length bound |\n\n## Package Entry Point\n\n| Import | Purpose |\n| -------------------------- | --------------------------------------------------------------------------- |\n| `@vielzeug/archive` | Browser-safe collections, constants, schemas and errors |\n| `@vielzeug/archive/worker` | Catalog factory, issuer signing-key/session service binding and event types |\n| `@vielzeug/archive/auth` | Issuer factory and binding types |\n\n## Collections\n\n### `defineArchiveCollection`\n\nCreates a frozen collection and its contract; malformed names, versions or vocabularies throw `ArchiveDefinitionError`.\n\n```ts\nfunction defineArchiveCollection<\n P extends object,\n const C extends number,\n const F extends string = never,\n const T extends string = never,\n>(definition: ArchiveCollectionDefinition<P, C, F, T>): ArchiveCollection<P, C>;\n```\n\n| Parameter | Contract |\n| ----------------- | --------------------------------------------------------------------------- |\n| `name` | Lowercase `[a-z0-9-]{1,32}` |\n| `contentVersion` | Positive safe integer |\n| `payloadSchema` | Spell schema whose output is a stable JSON object |\n| `filters`, `tags` | Optional readonly arrays; omitted means empty vocabulary |\n| `canonicalize` | Optional pure, idempotent, schema-valid normalization |\n| `index` | Derive `filter`, `tags` and searchable `title` without mutating the payload |\n\n**Returns:** `ArchiveCollection<P, C>`.\n\n**Example:** define and derive one collection without Worker bindings.\n\n```ts\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { s } from '@vielzeug/spell';\n\nconst recipes = defineArchiveCollection({\n name: 'recipes',\n contentVersion: 1,\n payloadSchema: s.object({ name: s.string().min(1).max(32) }),\n index: (payload) => ({ filter: null, tags: [], title: payload.name }),\n});\nconst derived = await recipes.derive({ name: 'Rice' });\nif (derived === null) throw new Error('Invalid recipe');\nconsole.log(derived.contentHash);\n```\n\n| Method / property | Result |\n| -------------------------------------- | --------------------------------------------------- |\n| `derive(raw)` | `Promise<ArchiveDerivation \\| null>` |\n| `contract.entry` | Public entry schema |\n| `contract.ownedEntry`, `ownedEntries` | Owner view with `clientKey` and `hidden` |\n| `contract.page` | Entries and the forward cursor |\n| `contract.publishInput`, `updateInput` | Publish and revision-guarded update request schemas |\n| `filters`, `tags` | Frozen vocabulary snapshots |\n\n`derive` returns `null` for invalid JSON objects, schema-invalid input, invalid titles, too many tags and oversized canonical payloads. Unexpected schema, callback or hashing failures throw `ArchiveDerivationError`. Non-idempotent or schema-invalid canonicalization, unstable schema transformations, index mutation and out-of-vocabulary projections are also derivation faults. Routes map `null` to 422 `invalid-payload` and faults to a sanitized 500 `internal`.\nSchema output that is lossy or no longer JSON is a derivation fault, not invalid\nsubmitted content. Invalid index-result shapes also throw.\n\nConst generics preserve the content-version literal and infer filter/tag unions from vocabulary arrays without `as const`. `NoInfer` prevents `index` from widening those unions; omitted arrays infer `never`, permitting only `filter: null` and empty tags.\n\nObjects serialize with recursively sorted keys; arrays preserve order unless your canonicalizer changes it. SHA-256 hashes the core-owned `{contentVersion, payload}` envelope. Stored payloads are canonical by construction, so the emitted entry schemas embed the plain payload schema.\n\n`filter`, tags and searchable title are persisted projections, not computed during reads. Changing `index` or its vocabulary does not update stored rows. The active definition and persisted dataset must remain consistent; Archive has no projection-update or historical-schema API.\n\n## Worker and Maintenance\n\n### `createArchiveWorker`\n\nReturns the catalog request/scheduled handler and its observation side channel.\n\n```ts\nfunction createArchiveWorker<E extends ArchiveWorkerEnv>(\n collections: readonly ArchiveCollection[],\n): ArchiveWorkerHandler<E>;\n```\n\n**Returns:** `ArchiveWorkerHandler<E>`; duplicate names throw `ArchiveDefinitionError` at registration.\n\n**Example:** export a deployable Worker using the package's structural bindings.\n\n```ts\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { createArchiveWorker, type ArchiveWorkerEnv } from '@vielzeug/archive/worker';\nimport { s } from '@vielzeug/spell';\n\nconst notes = defineArchiveCollection({\n name: 'notes',\n contentVersion: 1,\n payloadSchema: s.object({ title: s.string().min(1).max(128) }),\n index: ({ title }) => ({ title, filter: null, tags: [] }),\n});\nexport default createArchiveWorker<ArchiveWorkerEnv>([notes]);\n```\n\n| Method | Contract |\n| --------------------------------- | -------------------------------------------------------------------------------- |\n| `fetch(request, env, ctx)` | Returns `Promise<Response>` |\n| `scheduled(controller, env, ctx)` | Sweeps expired retry keys and revocation tombstones; emits failures and rethrows |\n| `tap(handler, { signal? }?)` | Returns unsubscribe; a pre-aborted signal registers nothing |\n\n`AUTH_ISSUER_SERVICE` is a required `fetch`-shaped service binding to the issuer.\nThe catalog fetches signing keys from the configured `JWT_JWKS_URL` through that\nbinding, not through global `fetch`. The URL still selects the issuer's JWKS\nroute and must satisfy the environment's transport rules. Key requests use GET\nwithout a session cookie and do not follow redirects.\nThe catalog verifies the signed JWT locally, then asks the issuer to validate its\ncurrent account session version. JOSE caches signing keys; the catalog does not\ncache successful issuer session verdicts.\nIf the service exchange fails or exceeds its fixed 5000 ms timeout (body decoding\nincluded), the catalog returns `503 auth-unavailable`; the timeout does not cancel\nwork already started by the issuer.\n\nOnly anonymous entry lists can use the 30-second edge cache. Any `Cookie` or `Authorization` header disables caching, even if invalid or empty. Detail, metadata, private and error responses are `no-store`. Public reads do not verify sessions.\n\n---\n\n### `worker.tap`\n\nObserves typed request, scheduled and cache-failure events without affecting request behavior.\n\n```ts\ntap(handler: (event: ArchiveEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n```\n\n**Returns:** an unsubscribe function; abort detaches the observer. Diagnostics contain categories and trusted configuration field names, never raw errors, SQL, subjects, aliases, tokens or URLs.\n\n**Example:** observe a Worker and detach explicitly.\n\n```ts\nimport { createArchiveWorker, type ArchiveWorkerEnv } from '@vielzeug/archive/worker';\n\nconst worker = createArchiveWorker<ArchiveWorkerEnv>([]);\nconst stop = worker.tap((event) => console.log(JSON.stringify(event)));\nstop();\n```\n\n---\n\n## Identity Issuer\n\n### `createAuthWorker`\n\nReturns the passwordless email issuer with account export and coordinated erasure.\n\n```ts\nfunction createAuthWorker<E extends AuthWorkerEnv>(): AuthWorkerHandler<E>;\n```\n\n**Returns:** `AuthWorkerHandler<E>`.\n\n**Example:** export an issuer configured through deployment bindings.\n\n```ts\nimport { createAuthWorker, type AuthWorkerEnv } from '@vielzeug/archive/auth';\n\nexport default createAuthWorker<AuthWorkerEnv>();\n```\n\n| Method | Contract |\n| ---------------------------------- | ------------------------------------------------------------------------------- |\n| `fetch(request, env, ctx?)` | Returns `Promise<Response>` |\n| `scheduled(controller, env, ctx?)` | Removes expired links, closed send windows and unverified unreferenced accounts |\n| `tap(handler, { signal? }?)` | Observes typed `AuthEvent`; returns unsubscribe; pre-aborted signals are inert |\n\nMagic links expire after 15 minutes and work once. The durable per-email budget allows three sends per hour; consumption, expiration and send failure do not refund it. Ordinary sessions last at most 30 days. Operator sessions use `OPERATOR_SESSION_MAX_AGE_SECONDS` (3600 seconds, or 60 minutes). `OPERATOR_EMAILS` controls newly minted role claims.\n\nThe issuer-global admission budget is durable D1 state in `auth_sign_in_budget`:\n20 requests per 60-second window before account creation or email delivery.\nThis supplements, rather than replaces, the durable per-email budget. No external\nrate-limiter binding is required for either sign-in admission route; the budgets do not cover\n`POST /auth/verify`, the device approval and claim routes, or `GET /auth/session`, which deployments rate-limit at the\nedge. Edge rules should block rather than challenge `GET /auth/session`: clients\ncheck it with a `fetch`, which cannot solve a challenge interstitial. The verify\nGET is a browser navigation from the email link, so a challenge is solvable there.\nAdmission spends are not refunded after later database or email failures.\nRequest emails are trimmed and lowercased before validation. `SENDER_ADDRESS`\nmust already be canonical; `OPERATOR_EMAILS` entries are trimmed and lowercased\nbefore validation.\n\nFor isolated browser storage, device sign-in binds approval to a secret held by\nthe initiating app. Generate 32 random bytes, encode them as an unpadded base64url\nproof, and send the lowercase SHA-256 hex of its UTF-8 representation as\n`challenge`. The email approval page shows the first eight uppercase hex digits;\nthe app must show the same code and ask the user to compare them. Approval is\nan explicit POST and does not sign in the confirming browser. The app claims\nwith its proof; a pending claim returns 202 and an approved one returns 204 with\nthe normal session cookie. Claim returns 409 without consuming the proof if the\nrequest already carries a valid session, so it cannot replace that account.\nBoth requests require the marker and an allowed\norigin. The proof is a credential: do not log it; retain it only until claim,\ncancellation or expiration. Sign-out-all and account deletion revoke pending\napprovals. Existing browser sign-in is unchanged.\n\nSign-in requests create pending account rows with `lastSignInAt: null`. Successful\nredemption atomically claims the one-use link and stamps the account's sign-in\ntime. The sweep deletes expired links and closed per-user send windows, then\nunverified accounts with neither remaining links nor send-budget references.\nVerified accounts are retained until explicit account deletion.\n\n`OPERATOR_SESSION_MAX_AGE_SECONDS = 3600` is part of the browser-safe root\ncontract; `/auth` exports the factory and issuer binding types.\nThis duration applies to newly minted sessions; existing tokens keep their signed\nexpiration. Session-version revocation is still checked on every private request.\n\n`AUTH_JWT_PREVIOUS_PUBLIC_JWKS` optionally publishes retired public RS256 keys and verifies sessions minted before rotation; private members reject configuration. The package has no demo sign-in routes.\n\nOpening a magic link performs a safe GET that displays a click-confirmation page,\nnot redemption. Only a marked POST from an exact allowed origin or\n`PUBLIC_ORIGIN` consumes `{ token }` and returns 204 with the session cookie. The\nconfirmation page navigates to the fixed `${PUBLIC_ORIGIN}/signed-in` destination;\nyour application must serve that page because the issuer serves only the\nconfirmation endpoint. The POST is not a redirect. Confirmation responses are\n`no-store` with no-referrer and a restrictive CSP; inline script and styles\nrequire a fresh response nonce, with no\n`unsafe-inline`. The page removes the token from the address bar before rendering\nthe controls and loads no external assets. `APP_NAME` supplies escaped page and\nemail branding; the confirmation has keyboard focus, live status announcements,\n44-pixel minimum action heights, a warm near-white paper and copper light scheme,\na deep neutral dark scheme, serif headings, sans-serif body text and reduced-motion\nstyles. Without JavaScript, it links to `${PUBLIC_ORIGIN}/account` as “Request a\nnew sign-in link” but cannot redeem a link.\nGET displays confirmation for any syntactically valid token, including a used\ntoken; only POST establishes whether the link is still redeemable. POST accepts\nexactly `{ token }` and rejects query parameters. With valid issuer configuration,\ninvalid or missing GET tokens, duplicate token parameters and unsupported query\nparameters return HTTP 400 with branded HTML recovery, not a JSON error. POST\nerrors retain the JSON `ArchiveErrorResponse` schema and their HTTP status.\n\nThe button announces pending sign-in and blocks duplicate submissions. HTTP 410\nreplaces it with a new-link action; HTTP 400 also disables resubmission. Every\nfailure offers the fixed `${PUBLIC_ORIGIN}/account` recovery link labelled\n“Request a new sign-in link”. Like `/signed-in`, `/account` is a fixed reference\nissuer convention: the application must serve its sign-in entry there, not the issuer.\nRecovery is secondary while retry remains possible, and becomes the primary action\nfor invalid or expired links. It replaces the footer exit link to avoid duplicate\nnavigation. The initial “Back to app” footer links to `${PUBLIC_ORIGIN}/`.\nHTTP 429 delays manual retry using unsigned integer seconds or a syntactically valid\nHTTP-date `Retry-After`, rounded up\nand bounded to 1-300 seconds (30 seconds for missing or invalid values). HTTP 503\nand network failures offer explicit retry; no failure starts an automatic request.\nAll returned response bodies, including discarded stale responses, are cancelled\nwithout delaying recovery; cancellation failures are ignored. Each attempt aborts\nits controller on completion. Stalled requests abort after 15 seconds with a\ntimeout-specific message, distinct from connection failures. Leaving the page aborts its request and\nclears timers; bfcache restoration resumes only the remaining cooldown, not a\nrequest. Navigation after exact 204 success is fixed at\n`${PUBLIC_ORIGIN}/signed-in`; query input never controls either destination.\n\nThe issuer never logs directly. `tap` emits sanitized request and scheduled\noutcomes; observer failures are swallowed, abort detaches the observer and failed\nscheduled work emits then rethrows. `AuthDiagnostic` reports only a category.\n\n## HTTP Routes\n\nEvery route below is mounted under `/api/v1`. Mutation guards require an exact allowed `Origin` and `x-archive-request: 1`. Registered publishers pin `x-archive-publisher` to the identity captured when preparing private requests. The header is a freshness precondition, not authority.\n\n| Route | Contract |\n| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `GET /health` | Public catalog readiness; 200 `ok` or 503 `degraded` |\n| `POST /sign-out` | Catalog-local sign-out; `{ ok: true }` and expired session cookie, without issuer access |\n| `GET /collections/:collection` | Collection metadata |\n| `GET /collections/:collection/entries` | `author`, `filter`, `tag`, `search`, `sort`, `cursor`, `limit`; forward entry page |\n| `POST /collections/:collection/entries` | `{ clientKey, payload }`; 201 create or 200 replay |\n| `GET /collections/:collection/entries/:id` | Public entry; always `no-store` |\n| `PUT /collections/:collection/entries/:id` | Owner-only `{ expectedRevision, payload }` |\n| `DELETE /collections/:collection/entries/:id` | Owner or operator removal; 204 |\n| `PUT` / `DELETE /collections/:collection/entries/:id/like` | Like / unlike visible entries only; guarded write and response; like-state response |\n| `POST /collections/:collection/entries/:id/report` | `{ reason }`; idempotent per entry/reporter; 204 |\n| `PUT` / `DELETE /collections/:collection/entries/:id/hidden` | Operator hide / unhide; 204 |\n| `GET /collections/:collection/reports` | Operator page; `status=unresolved` (default) or `resolved`, `cursor`, `limit` |\n| `PUT /collections/:collection/reports/:id/resolved` | Operator resolves report by its unique report ID; idempotent 204 |\n| `DELETE /publishers/:id` | Operator erases Archive profile; not issuer account |\n| `GET /moderation-log` | Operator forward page; `cursor`, `limit` |\n| `GET` / `POST` / `PUT /me` | Identity, register with optional `{ name }`, rename with required `{ name }` |\n| `DELETE /me` | Profile-only cascade; 204; does not clear cookie |\n| `DELETE /me/account` | Revoke issuer/subject and atomically erase profile; 204; coordinated issuer-erasure seam |\n| `GET /me/publications?collection=…` | Owner entries including hidden state and retry keys |\n| `GET /me/likes` | Forward page `{ ids, cursor }`; `cursor`, `limit` |\n| `GET /me/likes?ids=…` | Subset lookup `{ ids }`; at most `likeStateIds` input IDs |\n| `GET /me/reports` | Own forward report page across collections; `cursor`, `limit` |\n| `GET /auth/health` | Public issuer readiness; typed `AuthHealth`, 200 `ok` or 503 `degraded`; no email or peer probe |\n| `GET /auth/session` | Internal issuer-session check for the catalog service binding; exact `{ ok: true }`, `no-store`, no PII; 401 for an invalid, stale or absent-account session |\n| `POST /auth/sign-out-all` | Requires marker, exact origin, session and captured `ACCOUNT_HEADER`; atomically increments `session_version`, deletes outstanding links, preserves account and catalog data; 200 `{ ok: true }` with an expired cookie only on durable success |\n| `GET /auth/jwks.json` | Active and configured retired public verification keys |\n| `POST /auth/sign-in` | `{ email }` (trimmed and lowercased); 202 `{ ok: true }` |\n| `POST /auth/device/sign-in` | `{ email, challenge }`; 64 lowercase SHA-256 hex digits; shared admission and email budgets; 202 `{ ok: true }` |\n| `GET /auth/device/approve?token=…` | Non-destructive confirmation page displaying the matching code; no cookie; expired/invalid signatures return 410 recovery HTML |\n| `POST /auth/device/approve` | `{ token }`; marker and allowed or public origin; atomically authorizes the proof; 204 without a cookie |\n| `POST /auth/device/claim` | `{ token: proof }`; marker and allowed origin; 202 `{ ok: false }` if not claimable, 204 with session cookie when claimed; 409 if the request has a valid session |\n| `GET /auth/verify?token=…` | Safe no-store click-confirmation HTML; with valid issuer configuration, invalid queries return 400 recovery HTML; no token consumption or session change |\n| `POST /auth/verify` | JSON `{ token }`, marker and exact allowed origin or `PUBLIC_ORIGIN`; consume once; 204 with session cookie |\n| `GET /auth/account` | `{ id, email, createdAt, lastSignInAt }`; no tokens or budget data |\n| `DELETE /auth/account` | Requires `ACCOUNT_HEADER` with the captured issuer account UUID; catalog `/me/account` via `AUTH_ARCHIVE`, require exact 204, then issuer user and cookie clear; 204 |\n\nForward pages are newest first with opaque context-bound keyset cursors. Keep the same query context when following a cursor; end at `cursor: null`. `maxPageSize` bounds each page, not the total number of liked IDs, reports or audit actions you can export. The subset-like query is not a page and cannot combine `ids` with `cursor` or `limit`.\n\nFull erasure creates an issuer/subject revocation tombstone for 30 days plus ten\nseconds and deletes the profile in the same transaction. Catalog authentication\nrejects that subject with 401 on ordinary private routes; registration also checks\nrevocation in SQL to prevent resurrection races. Only `DELETE /me/account` may\nbypass the issuer session lookup, and only to retry erasure with the original\nsigned session of the same principal while its existing revocation tombstone is\nvalid; JWT signature and claims are still verified. It is not a general\nstale-session exception: initial erasure validates the issuer session. The\nissuer-facing `DELETE /auth/account` always checks the current session version\nbefore calling the catalog, so retrying it after completed erasure returns 401\nbecause the account is absent.\nDirect profile-only `DELETE /me` allows later registration using the same session.\nThe sweep removes expired tombstones. Re-enrollment through the reference issuer\ncreates a fresh account UUID subject; an external issuer must issue a new subject\nto re-enroll during the revocation window.\n\nThe issuer stores `auth_users.session_version` as a safe non-negative integer,\ndefaulting to `0`. Every session JWT carries the current value as the required\n`sessionVersion` claim. Each ordinary issuer-authenticated route compares that\nclaim to the current account row; a mismatch is unauthenticated. `POST\n/api/v1/auth/sign-out-all` checks the captured issuer account UUID against the\nverified subject before atomically incrementing the version and deleting pending\nlinks. A changed account answers 409 `account-changed`; a failed request does not\nclear the cookie. This revokes all sessions, including the caller's, after a\nsuccessful response. Requests authorized before revocation may finish; there is\nno cross-database transactional or in-flight cancellation guarantee.\n\nThe catalog requires `AUTH_ISSUER_SERVICE`, a service binding to the issuer for\nboth JWKS retrieval and live session validation. Signing-key retrieval uses\n`JWT_JWKS_URL` through the binding, so it does not depend on a public same-zone\nWorker-to-Worker fetch. After local JWT signature/claims verification, it requests\n`GET /api/v1/auth/session` through that binding on every private request. Only a\nstrictly validated 401 `unauthenticated` remains a 401. Malformed, unexpected,\nprovider and 5xx responses become 503 `auth-unavailable`; there is no authority\ncache. Both service directions use a fixed 5000 ms timeout that includes body\ndecoding. The issuer's `/api/v1/auth/session` is an internal\nservice contract, not a frontend session API.\n\nIssuer readiness is independent of catalog readiness. `GET\n/api/v1/auth/health` returns `archiveAuthHealthSchema` as `AuthHealth`; its\nread-only probe checks configuration, a signing and verification key proof,\nbinding shapes, the singleton `auth_schema_meta` stamp against\n`AUTH_SCHEMA_VERSION`, and readability of expected tables, columns and triggers.\nIt does not write, send email or probe the catalog service. Responses are\nsanitized.\nConfiguration failure, database failure and schema mismatch return HTTP 503\nwith `status: 'degraded'` and the corresponding reason.\n\nEffective hide, unhide, operator removal and publisher erasure append audit rows atomically with the state transition. Concurrent idempotent no-ops append nothing. Audit rows contain opaque IDs, not names or content, and have no foreign keys so they outlive erasure. Resolving a report sets `resolvedAt`; it is not one of the four audit action kinds.\n\n## Constants and Schemas\n\n| Export | Value or parsed output |\n| ------------------------------------------------------------- | -------------------------------------------------------------------------- |\n| `ARCHIVE_CONTRACT_VERSION`, `ARCHIVE_SCHEMA_VERSION` | Both debut at `1`; wire and storage versions are independent |\n| `AUTH_SCHEMA_VERSION` | `1`; issuer DDL stamp checked by `/auth/health` |\n| `ARCHIVE_COLLECTION_NAME_PATTERN` | `/^[a-z0-9-]{1,32}$/` |\n| `ARCHIVE_OPERATOR_ROLE` | `'archive-operator'` |\n| `SESSION_COOKIE_NAME`, `SESSION_COOKIE_PATH` | `'archive_session'`, `'/api/v1'` |\n| `SESSION_MAX_AGE_SECONDS` | `2592000` |\n| `OPERATOR_SESSION_MAX_AGE_SECONDS` | `3600` (60 minutes); shared root contract |\n| `ACCOUNT_HEADER` | `'X-Archive-Account'`; required issuer-account UUID on coordinated erasure |\n| `PUBLISHER_HEADER`, `REQUEST_MARKER_HEADER` | `'x-archive-publisher'`, `'x-archive-request'` |\n| `ILL_FORMED_TEXT`, `isWellFormedText(value: string): boolean` | Reject control characters and lone UTF-16 surrogates |\n| `uuidSchema`, `isoTimestampSchema`, `hex64Schema` | UUID, ISO timestamp, lowercase SHA-256 hex strings |\n| `archiveAliasSchema` | Trimmed, well-formed alias of at most 24 characters |\n| `archiveAuthorSchema` | `{ id: string; name: string }` |\n| `archiveIdentitySchema` | `ArchiveIdentity` |\n| `archiveAccountSchema` | `ArchiveAccount`; issuer metadata, excluding private fields |\n| `archiveLimitsSchema` | All numeric `ARCHIVE_LIMITS` fields |\n| `archiveHealthSchema` | `ArchiveHealth` |\n| `archiveAuthHealthSchema` | `AuthHealth` |\n| `archiveErrorResponseSchema` | `ArchiveErrorResponse` |\n| `archiveOkSchema` | `{ ok: true }` |\n| `archiveCollectionMetaSchema` | `ArchiveCollectionMeta` |\n| `archiveLikedIdsSchema` | `{ ids: string[] }` subset response |\n| `archiveLikesPageSchema` | `ArchiveLikesPage` |\n| `archiveLikeStateSchema` | `{ id: string; likeCount: number; liked: boolean }` |\n| `archiveReportsSchema`, `archiveOwnReportsSchema` | `ArchiveReports`, `ArchiveOwnReports` |\n| `archiveModerationLogSchema` | `ArchiveModerationLog` |\n| `archiveSortSchema` | `ArchiveSort` |\n| `ARCHIVE_ERROR_CODES` | Values of `ArchiveErrorCode` below |\n| `ARCHIVE_MODERATION_ACTIONS` | `['hide', 'unhide', 'remove', 'erase-publisher']` |\n\n### `sessionCookieValue`\n\nComposes a session cookie using the shared security attributes.\n\n```ts\nfunction sessionCookieValue(token: string, options: { maxAgeSeconds: number; secure: boolean }): string;\n```\n\n| Parameter | Contract |\n| ----------------------- | -------------------------------------------- |\n| `token` | Session token, or empty string when clearing |\n| `options.maxAgeSeconds` | Cookie lifetime; `0` clears it |\n| `options.secure` | Include `Secure` for production HTTPS |\n\n**Returns:** the `Set-Cookie` value with `HttpOnly`, `SameSite=Strict`, the shared path and optional `Secure`.\n\n**Example:** clear the production cookie.\n\n```ts\nimport { sessionCookieValue } from '@vielzeug/archive';\n\nconst expiredCookie = sessionCookieValue('', { maxAgeSeconds: 0, secure: true });\nconsole.log(expiredCookie);\n```\n\n---\n\n### `isWellFormedText`\n\nChecks text for control characters and lone UTF-16 surrogates.\n\n```ts\nfunction isWellFormedText(value: string): boolean;\n```\n\n**Returns:** `true` when `ILL_FORMED_TEXT` does not match; it does not trim or impose bounds.\n\n**Example:** validate text independently of the alias schema.\n\n```ts\nimport { isWellFormedText } from '@vielzeug/archive';\n\nconsole.log(isWellFormedText('Rice'), isWellFormedText('\\u0000'));\n```\n\n### `ARCHIVE_LIMITS`\n\n`ARCHIVE_LIMITS` is frozen with these values:\n\n```ts\nconst limits = {\n aliasChars: 24,\n cursorChars: 1024,\n idempotencyRetentionMs: 172800000,\n likeStateIds: 50,\n maxPageSize: 50,\n maxPublications: 50,\n pageSize: 10,\n payloadBytes: 8192,\n publicCacheSeconds: 30,\n reportReasonChars: 256,\n requestBytes: 12288,\n searchChars: 64,\n searchTerms: 6,\n tagsPerEntry: 16,\n titleChars: 128,\n vocabChars: 64,\n};\n```\n\n## Types\n\nThe following definitions use `Schema` from `@vielzeug/spell`. Schema-derived aliases show their complete output shape.\n\n```ts\ninterface ArchiveIndexing<F extends string = string, T extends string = string> {\n filter: F | null;\n tags: readonly T[];\n title: string;\n}\ninterface ArchiveCollectionDefinition<\n P extends object,\n C extends number,\n F extends string = never,\n T extends string = never,\n> {\n canonicalize?(payload: P): P;\n contentVersion: C;\n filters?: readonly F[];\n index(payload: P): ArchiveIndexing<NoInfer<F>, NoInfer<T>>;\n name: string;\n payloadSchema: Schema<P, unknown>;\n tags?: readonly T[];\n}\ninterface ArchiveDerivation {\n canonicalJson: string;\n contentHash: string;\n contentVersion: number;\n filter: string | null;\n tags: readonly string[];\n title: string;\n}\ninterface ArchiveEntry<P = unknown, C extends number = number> {\n author: { id: string; name: string };\n contentHash: string;\n contentVersion: C;\n id: string;\n likeCount: number;\n payload: P;\n publishedAt: string;\n revision: number;\n schemaVersion: typeof ARCHIVE_CONTRACT_VERSION;\n updatedAt: string;\n}\ninterface ArchiveOwnedEntry<P = unknown, C extends number = number> extends ArchiveEntry<P, C> {\n clientKey: string;\n hidden: boolean;\n}\ninterface ArchiveContract<P = unknown, C extends number = number> {\n entry: Schema<ArchiveEntry<P, C>>;\n ownedEntries: Schema<{ entries: ArchiveOwnedEntry<P, C>[] }>;\n ownedEntry: Schema<ArchiveOwnedEntry<P, C>>;\n page: Schema<ArchivePage<ArchiveEntry<P, C>>>;\n publishInput: Schema<{ clientKey: string; payload: P }, unknown>;\n updateInput: Schema<{ expectedRevision: number; payload: P }, unknown>;\n}\ninterface ArchiveCollection<P extends object = object, C extends number = number> {\n readonly contentVersion: C;\n readonly contract: ArchiveContract<P, C>;\n readonly derive: (raw: unknown) => Promise<ArchiveDerivation | null>;\n readonly filters: readonly string[];\n readonly name: string;\n readonly tags: readonly string[];\n}\ninterface ArchivePage<T> {\n cursor: string | null;\n entries: readonly T[];\n}\ntype ArchiveSort = 'liked' | 'recent';\ntype ArchiveDerivationStage = 'canonicalize' | 'hash' | 'index' | 'schema';\ntype ArchiveIdentity = { id: string; name: string; operator: boolean } | null;\ntype ArchiveAccount = {\n id: string;\n email: string;\n createdAt: string;\n lastSignInAt: string | null;\n};\ntype ArchiveCollectionMeta = { filters: string[]; name: string; tags: string[] };\ntype ArchiveLikesPage = { cursor: string | null; ids: string[] };\ntype ArchiveErrorCode =\n | 'account-changed'\n | 'auth-unavailable'\n | 'bad-request'\n | 'conflict'\n | 'forbidden'\n | 'gone'\n | 'internal'\n | 'invalid-payload'\n | 'likes-disabled'\n | 'method-not-allowed'\n | 'not-found'\n | 'publisher-changed'\n | 'publishing-disabled'\n | 'quota'\n | 'rate-limited'\n | 'record-unavailable'\n | 'timeout'\n | 'too-large'\n | 'unauthenticated'\n | 'unavailable'\n | 'unsupported-media';\ntype ArchiveErrorResponse = {\n error: { code: ArchiveErrorCode; message: string; requestId: string };\n};\ntype ArchiveHealth = {\n dbSchemaVersion: number | null;\n features: { likes: boolean; publishing: boolean };\n limits: {\n aliasChars: number;\n cursorChars: number;\n idempotencyRetentionMs: number;\n likeStateIds: number;\n maxPageSize: number;\n maxPublications: number;\n pageSize: number;\n payloadBytes: number;\n publicCacheSeconds: number;\n reportReasonChars: number;\n requestBytes: number;\n searchChars: number;\n searchTerms: number;\n tagsPerEntry: number;\n titleChars: number;\n vocabChars: number;\n };\n schemaVersion: 1;\n status: 'ok' | 'degraded';\n reason: 'database-unavailable' | 'schema-mismatch' | null;\n};\ntype AuthHealth = {\n dbSchemaVersion: number | null;\n schemaVersion: 1;\n status: 'ok' | 'degraded';\n reason: 'configuration-unavailable' | 'database-unavailable' | 'schema-mismatch' | null;\n};\ntype ArchiveReports = {\n cursor: string | null;\n reports: {\n id: string;\n createdAt: string;\n entryId: string;\n entryTitle: string;\n reason: string;\n reporter: { id: string; name: string };\n resolvedAt: string | null;\n }[];\n};\ntype ArchiveOwnReports = {\n cursor: string | null;\n reports: {\n collection: string;\n createdAt: string;\n entryId: string;\n id: string;\n reason: string;\n resolvedAt: string | null;\n }[];\n};\ntype ArchiveModerationAction = 'hide' | 'unhide' | 'remove' | 'erase-publisher';\ntype ArchiveModerationLog = {\n cursor: string | null;\n actions: {\n id: string;\n action: ArchiveModerationAction;\n collection: string | null;\n createdAt: string;\n operatorId: string;\n targetId: string;\n }[];\n};\n```\n\nWorker subpath types model only the binding methods the catalog calls.\n\n```ts\ninterface D1Statement {\n all<T>(): Promise<{ results?: T[] }>;\n bind(...params: (string | number | null)[]): D1Statement;\n first<T>(): Promise<T | null>;\n run(): Promise<{ meta?: { changes?: number } }>;\n}\ninterface D1Like {\n batch(statements: D1Statement[]): Promise<{ meta?: { changes?: number } }[]>;\n prepare(sql: string): D1Statement;\n}\ninterface RateLimiterBinding {\n limit(input: { key: string }): Promise<{ success: boolean }>;\n}\ninterface ArchiveWorkerEnv {\n AUTH_ISSUER_SERVICE: AuthIssuerServiceBinding;\n ALLOWED_ORIGINS: string;\n APP_ENV: string;\n DB: D1Like;\n JWT_AUDIENCE: string;\n JWT_ISSUER: string;\n JWT_JWKS_URL: string;\n LIKES_ENABLED: string;\n PUBLISHING_ENABLED: string;\n RATE_LIMIT_KEY_SECRET: string;\n READ_LIMIT: RateLimiterBinding;\n WRITE_LIMIT: RateLimiterBinding;\n}\ninterface AuthIssuerServiceBinding {\n fetch(request: Request): Promise<Response>;\n}\ninterface ArchiveExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n}\ntype ArchiveDiagnostic =\n | { readonly kind: 'configuration'; readonly field: string }\n | { readonly kind: 'database' | 'record' | 'schema' | 'internal' | 'cache' | 'collection' };\ninterface ArchiveRequestEvent {\n code: ArchiveErrorCode | 'ok';\n diagnostic?: ArchiveDiagnostic;\n ms: number;\n requestId: string;\n route: string;\n status: number;\n type: 'request';\n}\ntype ArchiveScheduledEvent =\n | { removed: number; type: 'scheduled'; status: 'ok' }\n | { type: 'scheduled'; status: 'failed'; diagnostic: ArchiveDiagnostic };\ntype ArchiveEvent =\n | ArchiveRequestEvent\n | ArchiveScheduledEvent\n | { readonly type: 'cache-error'; readonly diagnostic: ArchiveDiagnostic };\ninterface ArchiveWorkerHandler<E extends ArchiveWorkerEnv = ArchiveWorkerEnv> {\n fetch(request: Request, env: E, ctx: ArchiveExecutionContext): Promise<Response>;\n scheduled?(controller: unknown, env: E, ctx: ArchiveExecutionContext): void | Promise<void>;\n tap(handler: (event: ArchiveEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n```\n\nScheduled `removed` counts the combined expired retry-key and revocation rows.\n\nAuth subpath types describe the sibling issuer and its required service binding.\n\n```ts\ninterface SendEmail {\n send(message: { from: string; html?: string; subject: string; text: string; to: string }): Promise<unknown>;\n}\ninterface AuthArchiveBinding {\n fetch(request: Request): Promise<Response>;\n}\ninterface AuthWorkerEnv {\n ALLOWED_ORIGINS: string;\n APP_ENV: string;\n APP_NAME: string;\n AUDIENCE: string;\n AUTH_ARCHIVE: AuthArchiveBinding;\n AUTH_DB: D1Like;\n AUTH_EMAIL: SendEmail;\n AUTH_ISSUER: string;\n AUTH_JWT_PREVIOUS_PUBLIC_JWKS?: string;\n AUTH_JWT_PRIVATE_JWK: string;\n OPERATOR_EMAILS: string;\n PUBLIC_ORIGIN: string;\n SENDER_ADDRESS: string;\n}\ninterface AuthWorkerHandler<E extends AuthWorkerEnv = AuthWorkerEnv> {\n fetch(request: Request, env: E, ctx?: ArchiveExecutionContext): Promise<Response>;\n scheduled(controller: unknown, env: E, ctx?: ArchiveExecutionContext): Promise<void>;\n tap(handler: (event: AuthEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\ntype AuthDiagnostic = {\n readonly kind: 'configuration' | 'database' | 'schema' | 'email' | 'catalog' | 'internal';\n};\ntype AuthEvent =\n | {\n readonly type: 'request';\n readonly requestId: string;\n readonly route:\n | '/auth/account'\n | '/auth/device/approve'\n | '/auth/device/claim'\n | '/auth/device/sign-in'\n | '/auth/health'\n | '/auth/jwks.json'\n | '/auth/session'\n | '/auth/sign-in'\n | '/auth/sign-out-all'\n | '/auth/verify'\n | 'unmatched';\n readonly status: number;\n readonly code: ArchiveErrorCode | 'ok';\n readonly ms: number;\n readonly diagnostic?: AuthDiagnostic;\n }\n | { readonly type: 'scheduled'; readonly status: 'ok'; readonly removed: number }\n | { readonly type: 'scheduled'; readonly status: 'failed'; readonly diagnostic: AuthDiagnostic };\n```\n\nIssuer scheduled `removed` counts expired token rows, closed per-user send windows\nand deleted unverified accounts. The singleton admission row is retained and its\nwindow resets atomically on a later sign-in request.\n\n## Errors\n\n| Exported class | Trigger | Properties |\n| ------------------------ | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |\n| `ArchiveError` | Base for public package errors | `name`, `message`, optional `cause` |\n| `ArchiveDefinitionError` | Invalid collection definition or duplicate registered collection names | Extends `ArchiveError` |\n| `ArchiveDerivationError` | Unexpected schema/canonicalization/index/hash fault or violated collection invariant | Extends `ArchiveError`; readonly `stage: ArchiveDerivationStage`; optional `cause` |\n\n`ArchiveError` and `ArchiveDefinitionError` accept `(message: string, opts?: ErrorOptions)`.\n`ArchiveDerivationError` accepts `(stage: ArchiveDerivationStage, message: string, opts?: ErrorOptions)`.\nIts message and cause are local diagnostics, not response content. Worker request\nfailures use the wire envelope, not these thrown classes. Internal `ApiError` and\n`AuthOperationError` are not exported.\n\nStored entries that fail the current wire schema return 503 `record-unavailable`.\nStored payloads are canonical by construction, so the emitted entry schemas embed\nthe plain payload schema: parsing a response re-runs that schema, and an\nexception from one of its callbacks becomes a sanitized 500.\n\nThe complete public error signatures are:\n\n```ts\nclass ArchiveError extends Error {\n constructor(message: string, opts?: ErrorOptions);\n}\nclass ArchiveDefinitionError extends ArchiveError {}\nclass ArchiveDerivationError extends ArchiveError {\n readonly stage: ArchiveDerivationStage;\n constructor(stage: ArchiveDerivationStage, message: string, opts?: ErrorOptions);\n}\n```\n\nCatalog rate-limit responses use `Retry-After: 60`; configure catalog limiter periods to 60 seconds. Issuer admission/send-budget responses instead carry seconds until their durable window reopens. Health's degraded response is the health DTO, not an error envelope: schema mismatch reports the observed version; database unavailability reports `dbSchemaVersion: null`.\n",
|
|
5
|
+
"api": "---\ntitle: 'Archive: API Reference'\ndescription: 'Collection definitions, browser-safe wire schemas, Worker deployment, and identity issuance.'\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------------------------------------- | ------------------------------------------------------- | -------------- | --------------------------------------------------------------- |\n| `defineArchiveCollection` | Compose validation, indexing, identity and wire schemas | Sync | Invalid content derives to `null`; callback faults throw |\n| `createArchiveWorker` | Build the catalog Worker | Sync | Collection names must be unique |\n| `createAuthWorker` | Build the passwordless issuer | Sync | `AUTH_ARCHIVE` is required |\n| `worker.tap`, `issuer.tap` | Observe sanitized runtime outcomes | Sync | Neither core logs by default; observer exceptions are swallowed |\n| `ArchiveDerivationError` | Identify a collection implementation/runtime fault | Sync | Faults become sanitized 500s, not content-validation 422s |\n| `ARCHIVE_LIMITS` | Shared application bounds | Sync | Page bounds do not cap total exports |\n| `archiveErrorResponseSchema`, `archiveAuthHealthSchema` | Validate error and issuer-health responses | Sync | Unknown error codes and health states reject |\n| `ArchiveError`, `ArchiveDefinitionError` | Public base and invalid-definition errors | Sync | Thrown locally, not transmitted as error objects |\n| `sessionCookieValue` | Compose shared session-cookie attributes | Sync | Deployments must choose `secure` from their environment |\n| `isWellFormedText` | Check control characters and lone surrogates | Sync | Does not trim or impose a length bound |\n\n## Package Entry Point\n\n| Import | Purpose |\n| -------------------------- | --------------------------------------------------------------------------- |\n| `@vielzeug/archive` | Browser-safe collections, constants, schemas and errors |\n| `@vielzeug/archive/worker` | Catalog factory, issuer signing-key/session service binding and event types |\n| `@vielzeug/archive/auth` | Issuer factory and binding types |\n\n## Collections\n\n### `defineArchiveCollection`\n\nCreates a frozen collection and its contract; malformed names, versions or vocabularies throw `ArchiveDefinitionError`.\n\n```ts\nfunction defineArchiveCollection<\n P extends object,\n const C extends number,\n const F extends string = never,\n const T extends string = never,\n>(definition: ArchiveCollectionDefinition<P, C, F, T>): ArchiveCollection<P, C>;\n```\n\n| Parameter | Contract |\n| ----------------- | --------------------------------------------------------------------------- |\n| `name` | Lowercase `[a-z0-9-]{1,32}` |\n| `contentVersion` | Positive safe integer |\n| `payloadSchema` | Spell schema whose output is a stable JSON object |\n| `filters`, `tags` | Optional readonly arrays; omitted means empty vocabulary |\n| `canonicalize` | Optional pure, idempotent, schema-valid normalization |\n| `index` | Derive `filter`, `tags` and searchable `title` without mutating the payload |\n\n**Returns:** `ArchiveCollection<P, C>`.\n\n**Example:** define and derive one collection without Worker bindings.\n\n```ts\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { s } from '@vielzeug/spell';\n\nconst recipes = defineArchiveCollection({\n name: 'recipes',\n contentVersion: 1,\n payloadSchema: s.object({ name: s.string().min(1).max(32) }),\n index: (payload) => ({ filter: null, tags: [], title: payload.name }),\n});\nconst derived = await recipes.derive({ name: 'Rice' });\nif (derived === null) throw new Error('Invalid recipe');\nconsole.log(derived.contentHash);\n```\n\n| Method / property | Result |\n| -------------------------------------- | --------------------------------------------------- |\n| `derive(raw)` | `Promise<ArchiveDerivation \\| null>` |\n| `contract.entry` | Public entry schema |\n| `contract.ownedEntry`, `ownedEntries` | Owner view with `clientKey` and `hidden` |\n| `contract.page` | Entries and the forward cursor |\n| `contract.publishInput`, `updateInput` | Publish and revision-guarded update request schemas |\n| `filters`, `tags` | Frozen vocabulary snapshots |\n\n`derive` returns `null` for invalid JSON objects, schema-invalid input, invalid titles, too many tags and oversized canonical payloads. Unexpected schema, callback or hashing failures throw `ArchiveDerivationError`. Non-idempotent or schema-invalid canonicalization, unstable schema transformations, index mutation and out-of-vocabulary projections are also derivation faults. Routes map `null` to 422 `invalid-payload` and faults to a sanitized 500 `internal`.\nSchema output that is lossy or no longer JSON is a derivation fault, not invalid\nsubmitted content. Invalid index-result shapes also throw.\n\nConst generics preserve the content-version literal and infer filter/tag unions from vocabulary arrays without `as const`. `NoInfer` prevents `index` from widening those unions; omitted arrays infer `never`, permitting only `filter: null` and empty tags.\n\nObjects serialize with recursively sorted keys; arrays preserve order unless your canonicalizer changes it. SHA-256 hashes the core-owned `{contentVersion, payload}` envelope. Stored payloads are canonical by construction, so the emitted entry schemas embed the plain payload schema.\n\n`filter`, tags and searchable title are persisted projections, not computed during reads. Changing `index` or its vocabulary does not update stored rows. The active definition and persisted dataset must remain consistent; Archive has no projection-update or historical-schema API.\n\n## Worker and Maintenance\n\n### `createArchiveWorker`\n\nReturns the catalog request/scheduled handler and its observation side channel.\n\n```ts\nfunction createArchiveWorker<E extends ArchiveWorkerEnv>(\n collections: readonly ArchiveCollection[],\n): ArchiveWorkerHandler<E>;\n```\n\n**Returns:** `ArchiveWorkerHandler<E>`; duplicate names throw `ArchiveDefinitionError` at registration.\n\n**Example:** export a deployable Worker using the package's structural bindings.\n\n```ts\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { createArchiveWorker, type ArchiveWorkerEnv } from '@vielzeug/archive/worker';\nimport { s } from '@vielzeug/spell';\n\nconst notes = defineArchiveCollection({\n name: 'notes',\n contentVersion: 1,\n payloadSchema: s.object({ title: s.string().min(1).max(128) }),\n index: ({ title }) => ({ title, filter: null, tags: [] }),\n});\nexport default createArchiveWorker<ArchiveWorkerEnv>([notes]);\n```\n\n| Method | Contract |\n| --------------------------------- | -------------------------------------------------------------------------------- |\n| `fetch(request, env, ctx)` | Returns `Promise<Response>` |\n| `scheduled(controller, env, ctx)` | Sweeps expired retry keys and revocation tombstones; emits failures and rethrows |\n| `tap(handler, { signal? }?)` | Returns unsubscribe; a pre-aborted signal registers nothing |\n\n`AUTH_ISSUER_SERVICE` is a required `fetch`-shaped service binding to the issuer.\nThe catalog fetches signing keys from the configured `JWT_JWKS_URL` through that\nbinding, not through global `fetch`. The URL still selects the issuer's JWKS\nroute and must satisfy the environment's transport rules. Key requests use GET\nwithout a session cookie and do not follow redirects.\nThe catalog verifies the signed JWT locally, then asks the issuer to validate its\ncurrent account session version. JOSE caches signing keys; the catalog does not\ncache successful issuer session verdicts.\nIf the service exchange fails or exceeds its fixed 5000 ms timeout (body decoding\nincluded), the catalog returns `503 auth-unavailable`; the timeout does not cancel\nwork already started by the issuer.\n\nOnly anonymous entry lists can use the 30-second edge cache. Any `Cookie` or `Authorization` header disables caching, even if invalid or empty. Detail, metadata, private and error responses are `no-store`. Public reads do not verify sessions.\n\n---\n\n### `worker.tap`\n\nObserves typed request, scheduled and cache-failure events without affecting request behavior.\n\n```ts\ntap(handler: (event: ArchiveEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n```\n\n**Returns:** an unsubscribe function; abort detaches the observer. Diagnostics contain categories and trusted configuration field names, never raw errors, SQL, subjects, aliases, tokens or URLs.\n\n**Example:** observe a Worker and detach explicitly.\n\n```ts\nimport { createArchiveWorker, type ArchiveWorkerEnv } from '@vielzeug/archive/worker';\n\nconst worker = createArchiveWorker<ArchiveWorkerEnv>([]);\nconst stop = worker.tap((event) => console.log(JSON.stringify(event)));\nstop();\n```\n\n---\n\n## Identity Issuer\n\n### `createAuthWorker`\n\nReturns the passwordless email issuer with account export and coordinated erasure.\n\n```ts\nfunction createAuthWorker<E extends AuthWorkerEnv>(): AuthWorkerHandler<E>;\n```\n\n**Returns:** `AuthWorkerHandler<E>`.\n\n**Example:** export an issuer configured through deployment bindings.\n\n```ts\nimport { createAuthWorker, type AuthWorkerEnv } from '@vielzeug/archive/auth';\n\nexport default createAuthWorker<AuthWorkerEnv>();\n```\n\n| Method | Contract |\n| ---------------------------------- | ------------------------------------------------------------------------------- |\n| `fetch(request, env, ctx?)` | Returns `Promise<Response>` |\n| `scheduled(controller, env, ctx?)` | Removes expired links, closed send windows and unverified unreferenced accounts |\n| `tap(handler, { signal? }?)` | Observes typed `AuthEvent`; returns unsubscribe; pre-aborted signals are inert |\n\nMagic links expire after 15 minutes and work once. The durable per-email budget allows three sends per hour; consumption, expiration and send failure do not refund it. Ordinary sessions last at most 30 days. Operator sessions use `OPERATOR_SESSION_MAX_AGE_SECONDS` (3600 seconds, or 60 minutes). `OPERATOR_EMAILS` controls newly minted role claims.\n\nThe issuer-global admission budget is durable D1 state in `auth_sign_in_budget`:\n20 requests per 60-second window before account creation or email delivery.\nThis supplements, rather than replaces, the durable per-email budget. No external\nrate-limiter binding is required for either sign-in admission route; the budgets do not cover\n`POST /auth/verify`, the device approval and claim routes, or `GET /auth/session`, which deployments rate-limit at the\nedge. Edge rules should block rather than challenge `GET /auth/session`: clients\ncheck it with a `fetch`, which cannot solve a challenge interstitial. The verify\nGET is a browser navigation from the email link, so a challenge is solvable there.\nAdmission spends are not refunded after later database or email failures.\nRequest emails are trimmed and lowercased before validation. `SENDER_ADDRESS`\nmust already be canonical; `OPERATOR_EMAILS` entries are trimmed and lowercased\nbefore validation.\n\nFor isolated browser storage, device sign-in binds approval to a secret held by\nthe initiating app. Generate 32 random bytes, encode them as an unpadded base64url\nproof, and send the lowercase SHA-256 hex of its UTF-8 representation as\n`challenge`. The email approval page shows the first eight uppercase hex digits;\nthe app must show the same code and ask the user to compare them. Approval is\nan explicit POST and does not sign in the confirming browser. The app claims\nwith its proof; a pending claim returns 202 and an approved one returns 204 with\nthe normal session cookie. Claim returns 409 without consuming the proof if the\nrequest already carries a valid session, so it cannot replace that account.\nBoth requests require the marker and an allowed\norigin. The proof is a credential: do not log it; retain it only until claim,\ncancellation or expiration. Sign-out-all and account deletion revoke pending\napprovals. Existing browser sign-in is unchanged.\n\nSign-in requests create pending account rows with `lastSignInAt: null`. Successful\nredemption atomically claims the one-use link and stamps the account's sign-in\ntime. The sweep deletes expired links and closed per-user send windows, then\nunverified accounts with neither remaining links nor send-budget references.\nVerified accounts are retained until explicit account deletion.\n\n`OPERATOR_SESSION_MAX_AGE_SECONDS = 3600` is part of the browser-safe root\ncontract; `/auth` exports the factory and issuer binding types.\nThis duration applies to newly minted sessions; existing tokens keep their signed\nexpiration. Session-version revocation is still checked on every private request.\n\n`AUTH_JWT_PREVIOUS_PUBLIC_JWKS` optionally publishes retired public RS256 keys and verifies sessions minted before rotation; private members reject configuration. The package has no demo sign-in routes.\n\nOpening a magic link performs a safe GET that displays a click-confirmation page,\nnot redemption. Only a marked POST from an exact allowed origin or\n`PUBLIC_ORIGIN` consumes `{ token }` and returns 204 with the session cookie. The\nconfirmation page navigates to the fixed `${PUBLIC_ORIGIN}/signed-in` destination;\nyour application must serve that page because the issuer serves only the\nconfirmation endpoint. The POST is not a redirect. Confirmation responses are\n`no-store` with no-referrer and a restrictive CSP; inline script and styles\nrequire a fresh response nonce, with no\n`unsafe-inline`. The page removes the token from the address bar before rendering\nthe controls and loads no external assets. `APP_NAME` supplies escaped page and\nemail branding; the confirmation has keyboard focus, live status announcements,\n44-pixel minimum action heights, a warm near-white paper and copper light scheme,\na deep neutral dark scheme, serif headings, sans-serif body text and reduced-motion\nstyles. Without JavaScript, it links to `${PUBLIC_ORIGIN}/account` as “Request a\nnew sign-in link” but cannot redeem a link.\nGET displays confirmation for any syntactically valid token, including a used\ntoken; only POST establishes whether the link is still redeemable. POST accepts\nexactly `{ token }` and rejects query parameters. With valid issuer configuration,\ninvalid or missing GET tokens, duplicate token parameters and unsupported query\nparameters return HTTP 400 with branded HTML recovery, not a JSON error. POST\nerrors retain the JSON `ArchiveErrorResponse` schema and their HTTP status.\n\nThe button announces pending sign-in and blocks duplicate submissions. HTTP 410\nreplaces it with a new-link action; HTTP 400 also disables resubmission. Every\nfailure offers the fixed `${PUBLIC_ORIGIN}/account` recovery link labelled\n“Request a new sign-in link”. Like `/signed-in`, `/account` is a fixed reference\nissuer convention: the application must serve its sign-in entry there, not the issuer.\nRecovery is secondary while retry remains possible, and becomes the primary action\nfor invalid or expired links. It replaces the footer exit link to avoid duplicate\nnavigation. The initial “Back to app” footer links to `${PUBLIC_ORIGIN}/`.\nHTTP 429 delays manual retry using unsigned integer seconds or a syntactically valid\nHTTP-date `Retry-After`, rounded up\nand bounded to 1-300 seconds (30 seconds for missing or invalid values). HTTP 503\nand network failures offer explicit retry; no failure starts an automatic request.\nAll returned response bodies, including discarded stale responses, are cancelled\nwithout delaying recovery; cancellation failures are ignored. Each attempt aborts\nits controller on completion. Stalled requests abort after 15 seconds with a\ntimeout-specific message, distinct from connection failures. Leaving the page aborts its request and\nclears timers; bfcache restoration resumes only the remaining cooldown, not a\nrequest. Navigation after exact 204 success is fixed at\n`${PUBLIC_ORIGIN}/signed-in`; query input never controls either destination.\n\nThe issuer never logs directly. `tap` emits sanitized request and scheduled\noutcomes; observer failures are swallowed, abort detaches the observer and failed\nscheduled work emits then rethrows. `AuthDiagnostic` reports only a category.\n\n## HTTP Routes\n\nEvery route below is mounted under `/api/v1`. Mutation guards require an exact allowed `Origin` and `x-archive-request: 1`. Registered publishers pin `x-archive-publisher` to the identity captured when preparing private requests. The header is a freshness precondition, not authority.\n\n| Route | Contract |\n| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `GET /health` | Public catalog readiness; 200 `ok` or 503 `degraded` |\n| `POST /sign-out` | Catalog-local sign-out; `{ ok: true }` and expired session cookie, without issuer access |\n| `GET /collections/:collection` | Collection metadata |\n| `GET /collections/:collection/entries` | `author`, `filter`, `tag`, `search`, `sort`, `cursor`, `limit`; forward entry page |\n| `POST /collections/:collection/entries` | `{ clientKey, payload }`; 201 create or 200 replay |\n| `GET /collections/:collection/entries/:id` | Public entry; always `no-store` |\n| `PUT /collections/:collection/entries/:id` | Owner-only `{ expectedRevision, payload }` |\n| `DELETE /collections/:collection/entries/:id` | Owner or operator removal; 204 |\n| `PUT` / `DELETE /collections/:collection/entries/:id/like` | Like / unlike visible entries only; guarded write and response; like-state response |\n| `POST /collections/:collection/entries/:id/report` | `{ reason }`; idempotent per entry/reporter; 204 |\n| `PUT` / `DELETE /collections/:collection/entries/:id/hidden` | Operator hide / unhide; 204 |\n| `GET /collections/:collection/reports` | Operator page; `status=unresolved` (default) or `resolved`, `cursor`, `limit` |\n| `PUT /collections/:collection/reports/:id/resolved` | Operator resolves report by its unique report ID; idempotent 204 |\n| `DELETE /publishers/:id` | Operator erases Archive profile; not issuer account |\n| `GET /moderation-log` | Operator forward page; `cursor`, `limit` |\n| `GET` / `POST` / `PUT /me` | Identity, register with optional `{ name }`, rename with required `{ name }` |\n| `DELETE /me` | Profile-only cascade; 204; does not clear cookie |\n| `DELETE /me/account` | Revoke issuer/subject and atomically erase profile; 204; coordinated issuer-erasure seam |\n| `GET /me/publications?collection=…` | Owner entries including hidden state and retry keys |\n| `GET /me/likes` | Forward page `{ ids, cursor }`; `cursor`, `limit` |\n| `GET /me/likes?ids=…` | Subset lookup `{ ids }`; at most `likeStateIds` input IDs |\n| `GET /me/reports` | Own forward report page across collections; `cursor`, `limit` |\n| `GET /auth/health` | Public issuer readiness; typed `AuthHealth`, 200 `ok` or 503 `degraded`; no email or peer probe |\n| `GET /auth/session` | Internal issuer-session check for the catalog service binding; exact `{ ok: true }`, `no-store`, no PII; 401 for an invalid, stale or absent-account session |\n| `POST /auth/sign-out-all` | Requires marker, exact origin, session and captured `ACCOUNT_HEADER`; atomically increments `session_version`, deletes outstanding links, preserves account and catalog data; 200 `{ ok: true }` with an expired cookie only on durable success |\n| `GET /auth/jwks.json` | Active and configured retired public verification keys |\n| `POST /auth/sign-in` | `{ email }` (trimmed and lowercased); 202 `{ ok: true }` |\n| `POST /auth/device/sign-in` | `{ email, challenge }`; 64 lowercase SHA-256 hex digits; shared admission and email budgets; 202 `{ ok: true }` |\n| `GET /auth/device/approve?token=…` | Non-destructive confirmation page displaying the matching code; no cookie; expired/invalid signatures return 410 recovery HTML |\n| `POST /auth/device/approve` | `{ token }`; marker and allowed or public origin; atomically authorizes the proof; 204 without a cookie |\n| `POST /auth/device/claim` | `{ token: proof }`; marker and allowed origin; 202 `{ ok: false }` if not claimable, 204 with session cookie when claimed; 409 if the request has a valid session |\n| `GET /auth/verify?token=…` | Safe no-store click-confirmation HTML; with valid issuer configuration, invalid queries return 400 recovery HTML; no token consumption or session change |\n| `POST /auth/verify` | JSON `{ token }`, marker and exact allowed origin or `PUBLIC_ORIGIN`; consume once; 204 with session cookie |\n| `GET /auth/account` | `{ id, email, createdAt, lastSignInAt }`; no tokens or budget data |\n| `DELETE /auth/account` | Requires `ACCOUNT_HEADER` with the captured issuer account UUID; catalog `/me/account` via `AUTH_ARCHIVE`, require exact 204, then issuer user and cookie clear; 204 |\n\nForward pages are newest first with opaque context-bound keyset cursors. Keep the same query context when following a cursor; end at `cursor: null`. `maxPageSize` bounds each page, not the total number of liked IDs, reports or audit actions you can export. The subset-like query is not a page and cannot combine `ids` with `cursor` or `limit`.\n\nFull erasure creates an issuer/subject revocation tombstone for 30 days plus ten\nseconds and deletes the profile in the same transaction. Catalog authentication\nrejects that subject with 401 on ordinary private routes; registration also checks\nrevocation in SQL to prevent resurrection races. Only `DELETE /me/account` may\nbypass the issuer session lookup, and only to retry erasure with the original\nsigned session of the same principal while its existing revocation tombstone is\nvalid; JWT signature and claims are still verified. It is not a general\nstale-session exception: initial erasure validates the issuer session. The\nissuer-facing `DELETE /auth/account` always checks the current session version\nbefore calling the catalog, so retrying it after completed erasure returns 401\nbecause the account is absent.\nDirect profile-only `DELETE /me` allows later registration using the same session.\nThe sweep removes expired tombstones. Re-enrollment through the reference issuer\ncreates a fresh account UUID subject; an external issuer must issue a new subject\nto re-enroll during the revocation window.\n\nThe issuer stores `auth_users.session_version` as a safe non-negative integer,\ndefaulting to `0`. Every session JWT carries the current value as the required\n`sessionVersion` claim. Each ordinary issuer-authenticated route compares that\nclaim to the current account row; a mismatch is unauthenticated. `POST\n/api/v1/auth/sign-out-all` checks the captured issuer account UUID against the\nverified subject before atomically incrementing the version and deleting pending\nlinks. A changed account answers 409 `account-changed`; a failed request does not\nclear the cookie. This revokes all sessions, including the caller's, after a\nsuccessful response. Requests authorized before revocation may finish; there is\nno cross-database transactional or in-flight cancellation guarantee.\n\nThe catalog requires `AUTH_ISSUER_SERVICE`, a service binding to the issuer for\nboth JWKS retrieval and live session validation. Signing-key retrieval uses\n`JWT_JWKS_URL` through the binding, so it does not depend on a public same-zone\nWorker-to-Worker fetch. After local JWT signature/claims verification, it requests\n`GET /api/v1/auth/session` through that binding on every private request. Only a\nstrictly validated 401 `unauthenticated` remains a 401. Malformed, unexpected,\nprovider and 5xx responses become 503 `auth-unavailable`; there is no authority\ncache. Both service directions use a fixed 5000 ms timeout that includes body\ndecoding. The issuer's `/api/v1/auth/session` is an internal\nservice contract, not a frontend session API.\n\nIssuer readiness is independent of catalog readiness. `GET\n/api/v1/auth/health` returns `archiveAuthHealthSchema` as `AuthHealth`; its\nread-only probe checks configuration, a signing and verification key proof,\nbinding shapes, the singleton `auth_schema_meta` stamp against\n`AUTH_SCHEMA_VERSION`, and readability of expected tables, columns and triggers.\nIt does not write, send email or probe the catalog service. Responses are\nsanitized.\nConfiguration failure, database failure and schema mismatch return HTTP 503\nwith `status: 'degraded'` and the corresponding reason.\n\nEffective hide, unhide, operator removal and publisher erasure append audit rows atomically with the state transition. Concurrent idempotent no-ops append nothing. Audit rows contain opaque IDs, not names or content, and have no foreign keys so they outlive erasure. Resolving a report sets `resolvedAt`; it is not one of the four audit action kinds.\n\n## Constants and Schemas\n\n| Export | Value or parsed output |\n| ------------------------------------------------------------- | -------------------------------------------------------------------------- |\n| `ARCHIVE_CONTRACT_VERSION`, `ARCHIVE_SCHEMA_VERSION` | Both debut at `1`; wire and storage versions are independent |\n| `AUTH_SCHEMA_VERSION` | `1`; issuer DDL stamp checked by `/auth/health` |\n| `ARCHIVE_COLLECTION_NAME_PATTERN` | `/^[a-z0-9-]{1,32}$/` |\n| `ARCHIVE_OPERATOR_ROLE` | `'archive-operator'` |\n| `SESSION_COOKIE_NAME`, `SESSION_COOKIE_PATH` | `'archive_session'`, `'/api/v1'` |\n| `SESSION_MAX_AGE_SECONDS` | `2592000` |\n| `OPERATOR_SESSION_MAX_AGE_SECONDS` | `3600` (60 minutes); shared root contract |\n| `ACCOUNT_HEADER` | `'X-Archive-Account'`; required issuer-account UUID on coordinated erasure |\n| `PUBLISHER_HEADER`, `REQUEST_MARKER_HEADER` | `'x-archive-publisher'`, `'x-archive-request'` |\n| `ILL_FORMED_TEXT`, `isWellFormedText(value: string): boolean` | Reject control characters and lone UTF-16 surrogates |\n| `uuidSchema`, `isoTimestampSchema`, `hex64Schema` | UUID, ISO timestamp, lowercase SHA-256 hex strings |\n| `archiveAliasSchema` | Trimmed, well-formed alias of at most 24 characters |\n| `archiveAuthorSchema` | `{ id: string; name: string }` |\n| `archiveIdentitySchema` | `ArchiveIdentity` |\n| `archiveAccountSchema` | `ArchiveAccount`; issuer metadata, excluding private fields |\n| `archiveLimitsSchema` | All numeric `ARCHIVE_LIMITS` fields |\n| `archiveHealthSchema` | `ArchiveHealth` |\n| `archiveAuthHealthSchema` | `AuthHealth` |\n| `archiveErrorResponseSchema` | `ArchiveErrorResponse` |\n| `archiveOkSchema` | `{ ok: true }` |\n| `archiveCollectionMetaSchema` | `ArchiveCollectionMeta` |\n| `archiveLikedIdsSchema` | `{ ids: string[] }` subset response |\n| `archiveLikesPageSchema` | `ArchiveLikesPage` |\n| `archiveLikeStateSchema` | `{ id: string; likeCount: number; liked: boolean }` |\n| `archiveReportsSchema`, `archiveOwnReportsSchema` | `ArchiveReports`, `ArchiveOwnReports` |\n| `archiveModerationLogSchema` | `ArchiveModerationLog` |\n| `archiveSortSchema` | `ArchiveSort` |\n| `ARCHIVE_ERROR_CODES` | Values of `ArchiveErrorCode` below |\n| `ARCHIVE_MODERATION_ACTIONS` | `['hide', 'unhide', 'remove', 'erase-publisher']` |\n\n### `sessionCookieValue`\n\nComposes a session cookie using the shared security attributes.\n\n```ts\nfunction sessionCookieValue(token: string, options: { maxAgeSeconds: number; secure: boolean }): string;\n```\n\n| Parameter | Contract |\n| ----------------------- | -------------------------------------------- |\n| `token` | Session token, or empty string when clearing |\n| `options.maxAgeSeconds` | Cookie lifetime; `0` clears it |\n| `options.secure` | Include `Secure` for production HTTPS |\n\n**Returns:** the `Set-Cookie` value with `HttpOnly`, `SameSite=Strict`, the shared path and optional `Secure`.\n\n**Example:** clear the production cookie.\n\n```ts\nimport { sessionCookieValue } from '@vielzeug/archive';\n\nconst expiredCookie = sessionCookieValue('', { maxAgeSeconds: 0, secure: true });\nconsole.log(expiredCookie);\n```\n\n---\n\n### `isWellFormedText`\n\nChecks text for control characters and lone UTF-16 surrogates.\n\n```ts\nfunction isWellFormedText(value: string): boolean;\n```\n\n**Returns:** `true` when `ILL_FORMED_TEXT` does not match; it does not trim or impose bounds.\n\n**Example:** validate text independently of the alias schema.\n\n```ts\nimport { isWellFormedText } from '@vielzeug/archive';\n\nconsole.log(isWellFormedText('Rice'), isWellFormedText('\\u0000'));\n```\n\n### `ARCHIVE_LIMITS`\n\n`ARCHIVE_LIMITS` is frozen with these values:\n\n```ts\nconst limits = {\n aliasChars: 24,\n cursorChars: 1024,\n idempotencyRetentionMs: 172800000,\n likeStateIds: 50,\n maxPageSize: 50,\n maxPublications: 50,\n pageSize: 10,\n payloadBytes: 8192,\n publicCacheSeconds: 30,\n reportReasonChars: 256,\n requestBytes: 12288,\n searchChars: 64,\n searchTerms: 6,\n tagsPerEntry: 16,\n titleChars: 128,\n vocabChars: 64,\n};\n```\n\n## Types\n\nThe following definitions use `Schema` from `@vielzeug/spell`. Schema-derived aliases show their complete output shape.\n\n```ts\ninterface ArchiveIndexing<F extends string = string, T extends string = string> {\n filter: F | null;\n tags: readonly T[];\n title: string;\n}\ninterface ArchiveCollectionDefinition<\n P extends object,\n C extends number,\n F extends string = never,\n T extends string = never,\n> {\n canonicalize?(payload: P): P;\n contentVersion: C;\n filters?: readonly F[];\n index(payload: P): ArchiveIndexing<NoInfer<F>, NoInfer<T>>;\n name: string;\n payloadSchema: Schema<P, unknown>;\n tags?: readonly T[];\n}\ninterface ArchiveDerivation {\n canonicalJson: string;\n contentHash: string;\n contentVersion: number;\n filter: string | null;\n tags: readonly string[];\n title: string;\n}\ninterface ArchiveEntry<P = unknown, C extends number = number> {\n author: { id: string; name: string };\n contentHash: string;\n contentVersion: C;\n id: string;\n likeCount: number;\n payload: P;\n publishedAt: string;\n revision: number;\n schemaVersion: typeof ARCHIVE_CONTRACT_VERSION;\n updatedAt: string;\n}\ninterface ArchiveOwnedEntry<P = unknown, C extends number = number> extends ArchiveEntry<P, C> {\n clientKey: string;\n hidden: boolean;\n}\ninterface ArchiveContract<P = unknown, C extends number = number> {\n entry: Schema<ArchiveEntry<P, C>>;\n ownedEntries: Schema<{ entries: ArchiveOwnedEntry<P, C>[] }>;\n ownedEntry: Schema<ArchiveOwnedEntry<P, C>>;\n page: Schema<ArchivePage<ArchiveEntry<P, C>>>;\n publishInput: Schema<{ clientKey: string; payload: P }, unknown>;\n updateInput: Schema<{ expectedRevision: number; payload: P }, unknown>;\n}\ninterface ArchiveCollection<P extends object = object, C extends number = number> {\n readonly contentVersion: C;\n readonly contract: ArchiveContract<P, C>;\n readonly derive: (raw: unknown) => Promise<ArchiveDerivation | null>;\n readonly filters: readonly string[];\n readonly name: string;\n readonly tags: readonly string[];\n}\ninterface ArchivePage<T> {\n cursor: string | null;\n entries: readonly T[];\n}\ntype ArchiveSort = 'liked' | 'recent';\ntype ArchiveDerivationStage = 'canonicalize' | 'hash' | 'index' | 'schema';\ntype ArchiveIdentity = { id: string; name: string; operator: boolean } | null;\ntype ArchiveAccount = {\n id: string;\n email: string;\n createdAt: string;\n lastSignInAt: string | null;\n};\ntype ArchiveCollectionMeta = { filters: string[]; name: string; tags: string[] };\ntype ArchiveLikesPage = { cursor: string | null; ids: string[] };\ntype ArchiveErrorCode =\n | 'account-changed'\n | 'auth-unavailable'\n | 'bad-request'\n | 'conflict'\n | 'forbidden'\n | 'gone'\n | 'internal'\n | 'invalid-payload'\n | 'likes-disabled'\n | 'method-not-allowed'\n | 'not-found'\n | 'publisher-changed'\n | 'publishing-disabled'\n | 'quota'\n | 'rate-limited'\n | 'record-unavailable'\n | 'timeout'\n | 'too-large'\n | 'unauthenticated'\n | 'unavailable'\n | 'unsupported-media';\ntype ArchiveErrorResponse = {\n error: { code: ArchiveErrorCode; message: string; requestId: string };\n};\ntype ArchiveHealth = {\n dbSchemaVersion: number | null;\n features: { likes: boolean; publishing: boolean };\n limits: {\n aliasChars: number;\n cursorChars: number;\n idempotencyRetentionMs: number;\n likeStateIds: number;\n maxPageSize: number;\n maxPublications: number;\n pageSize: number;\n payloadBytes: number;\n publicCacheSeconds: number;\n reportReasonChars: number;\n requestBytes: number;\n searchChars: number;\n searchTerms: number;\n tagsPerEntry: number;\n titleChars: number;\n vocabChars: number;\n };\n schemaVersion: 1;\n status: 'ok' | 'degraded';\n reason: 'database-unavailable' | 'schema-mismatch' | null;\n};\ntype AuthHealth = {\n dbSchemaVersion: number | null;\n schemaVersion: 1;\n status: 'ok' | 'degraded';\n reason: 'configuration-unavailable' | 'database-unavailable' | 'schema-mismatch' | null;\n};\ntype ArchiveReports = {\n cursor: string | null;\n reports: {\n id: string;\n createdAt: string;\n entryId: string;\n entryTitle: string;\n reason: string;\n reporter: { id: string; name: string };\n resolvedAt: string | null;\n }[];\n};\ntype ArchiveOwnReports = {\n cursor: string | null;\n reports: {\n collection: string;\n createdAt: string;\n entryId: string;\n id: string;\n reason: string;\n resolvedAt: string | null;\n }[];\n};\ntype ArchiveModerationAction = 'hide' | 'unhide' | 'remove' | 'erase-publisher';\ntype ArchiveModerationLog = {\n cursor: string | null;\n actions: {\n id: string;\n action: ArchiveModerationAction;\n collection: string | null;\n createdAt: string;\n operatorId: string;\n targetId: string;\n }[];\n};\n```\n\nWorker subpath types model only the binding methods the catalog calls.\n\n```ts\ninterface D1Statement {\n all<T>(): Promise<{ results?: T[] }>;\n bind(...params: (string | number | null)[]): D1Statement;\n first<T>(): Promise<T | null>;\n run(): Promise<{ meta?: { changes?: number } }>;\n}\ninterface D1Like {\n batch(statements: D1Statement[]): Promise<{ meta?: { changes?: number } }[]>;\n prepare(sql: string): D1Statement;\n}\ninterface RateLimiterBinding {\n limit(input: { key: string }): Promise<{ success: boolean }>;\n}\ninterface ArchiveWorkerEnv {\n AUTH_ISSUER_SERVICE: AuthIssuerServiceBinding;\n ALLOWED_ORIGINS: string;\n APP_ENV: string;\n DB: D1Like;\n JWT_AUDIENCE: string;\n JWT_ISSUER: string;\n JWT_JWKS_URL: string;\n LIKES_ENABLED: string;\n PUBLISHING_ENABLED: string;\n RATE_LIMIT_KEY_SECRET: string;\n READ_LIMIT: RateLimiterBinding;\n WRITE_LIMIT: RateLimiterBinding;\n}\ninterface AuthIssuerServiceBinding {\n fetch(request: Request): Promise<Response>;\n}\ninterface ArchiveExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n}\ntype ArchiveDiagnostic =\n | { readonly kind: 'configuration'; readonly field: string }\n | { readonly kind: 'database' | 'record' | 'schema' | 'internal' | 'cache' | 'collection' };\ninterface ArchiveRequestEvent {\n code: ArchiveErrorCode | 'ok';\n diagnostic?: ArchiveDiagnostic;\n ms: number;\n requestId: string;\n route: string;\n status: number;\n type: 'request';\n}\ntype ArchiveScheduledEvent =\n | { removed: number; type: 'scheduled'; status: 'ok' }\n | { type: 'scheduled'; status: 'failed'; diagnostic: ArchiveDiagnostic };\ntype ArchiveEvent =\n | ArchiveRequestEvent\n | ArchiveScheduledEvent\n | { readonly type: 'cache-error'; readonly diagnostic: ArchiveDiagnostic };\ninterface ArchiveWorkerHandler<E extends ArchiveWorkerEnv = ArchiveWorkerEnv> {\n fetch(request: Request, env: E, ctx: ArchiveExecutionContext): Promise<Response>;\n scheduled?(controller: unknown, env: E, ctx: ArchiveExecutionContext): void | Promise<void>;\n tap(handler: (event: ArchiveEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\n```\n\nScheduled `removed` counts the combined expired retry-key and revocation rows.\n\nAuth subpath types describe the sibling issuer and its required service binding.\n\n```ts\ninterface SendEmail {\n send(message: { from: string; html?: string; subject: string; text: string; to: string }): Promise<unknown>;\n}\ninterface AuthArchiveBinding {\n fetch(request: Request): Promise<Response>;\n}\ninterface AuthWorkerEnv {\n ALLOWED_ORIGINS: string;\n APP_ENV: string;\n APP_NAME: string;\n AUDIENCE: string;\n AUTH_ARCHIVE: AuthArchiveBinding;\n AUTH_DB: D1Like;\n AUTH_EMAIL: SendEmail;\n AUTH_ISSUER: string;\n AUTH_JWT_PREVIOUS_PUBLIC_JWKS?: string;\n AUTH_JWT_PRIVATE_JWK: string;\n OPERATOR_EMAILS: string;\n PUBLIC_ORIGIN: string;\n SENDER_ADDRESS: string;\n}\ninterface AuthWorkerHandler<E extends AuthWorkerEnv = AuthWorkerEnv> {\n fetch(request: Request, env: E, ctx?: ArchiveExecutionContext): Promise<Response>;\n scheduled(controller: unknown, env: E, ctx?: ArchiveExecutionContext): Promise<void>;\n tap(handler: (event: AuthEvent) => void, options?: { readonly signal?: AbortSignal }): () => void;\n}\ntype AuthDiagnostic = {\n readonly kind: 'configuration' | 'database' | 'schema' | 'email' | 'catalog' | 'internal';\n};\ntype AuthEvent =\n | {\n readonly type: 'request';\n readonly requestId: string;\n readonly route:\n | '/auth/account'\n | '/auth/device/approve'\n | '/auth/device/claim'\n | '/auth/device/sign-in'\n | '/auth/health'\n | '/auth/jwks.json'\n | '/auth/session'\n | '/auth/sign-in'\n | '/auth/sign-out-all'\n | '/auth/verify'\n | 'unmatched';\n readonly status: number;\n readonly code: ArchiveErrorCode | 'ok';\n readonly ms: number;\n readonly diagnostic?: AuthDiagnostic;\n }\n | { readonly type: 'scheduled'; readonly status: 'ok'; readonly removed: number }\n | { readonly type: 'scheduled'; readonly status: 'failed'; readonly diagnostic: AuthDiagnostic };\n```\n\nIssuer scheduled `removed` counts expired token rows, closed per-user send windows\nand deleted unverified accounts. The singleton admission row is retained and its\nwindow resets atomically on a later sign-in request.\n\n## Errors\n\n| Exported class | Trigger | Properties |\n| ------------------------ | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |\n| `ArchiveError` | Base for public package errors | `name`, `message`, optional `cause` |\n| `ArchiveDefinitionError` | Invalid collection definition or duplicate registered collection names | Extends `ArchiveError` |\n| `ArchiveDerivationError` | Unexpected schema/canonicalization/index/hash fault or violated collection invariant | Extends `ArchiveError`; readonly `stage: ArchiveDerivationStage`; optional `cause` |\n\n`ArchiveError` and `ArchiveDefinitionError` accept `(message: string, opts?: ErrorOptions)`.\n`ArchiveDerivationError` accepts `(stage: ArchiveDerivationStage, message: string, opts?: ErrorOptions)`.\nIts message and cause are local diagnostics, not response content. Worker request\nfailures use the wire envelope, not these thrown classes. Internal `ApiError` and\n`AuthOperationError` are not exported.\n\nStored entries that fail the current wire schema return 503 `record-unavailable`.\nStored payloads are canonical by construction, so the emitted entry schemas embed\nthe plain payload schema: parsing a response re-runs that schema, and an\nexception from one of its callbacks becomes a sanitized 500.\n\nThe complete public error signatures are:\n\n```ts\nclass ArchiveError extends Error {\n constructor(message: string, opts?: ErrorOptions);\n}\nclass ArchiveDefinitionError extends ArchiveError {}\nclass ArchiveDerivationError extends ArchiveError {\n readonly stage: ArchiveDerivationStage;\n constructor(stage: ArchiveDerivationStage, message: string, opts?: ErrorOptions);\n}\n```\n\nCatalog rate-limit responses use `Retry-After: 60`; configure catalog limiter periods to 60 seconds. Issuer admission/send-budget responses instead carry seconds until their durable window reopens. Health's degraded response is the health DTO, not an error envelope: schema mismatch reports the observed version; database unavailability reports `dbSchemaVersion: null`.\n",
|
|
6
6
|
"usage": "---\ntitle: 'Archive: Usage Guide'\ndescription: 'Define a collection, initialize fresh D1 databases, deploy the Workers, and wire your client and observation policy.'\n---\n\n[[toc]]\n\n## Basic Usage\n\nA deployment is a collection definition plus one factory call. Put the definition in a\nmodule both sides import — the browser needs the composed schemas, the Worker needs\nthe collection itself.\n\n```ts\n// recipes-collection.ts — the one content contract, shared by both sides.\nimport { defineArchiveCollection } from '@vielzeug/archive';\nimport { s } from '@vielzeug/spell';\n\nconst payloadSchema = s.object({\n cuisine: s.enum(['italian', 'japanese']),\n ingredients: s.array(s.string().trim().min(1).max(64)).min(1).max(20),\n name: s.string().trim().min(1).max(32),\n});\n\nexport const recipesCollection = defineArchiveCollection({\n // Ingredient order is not identity: the canonical form sorts, so reordered\n // content hashes identically and updates as a no-op.\n canonicalize: (payload) => ({ ...payload, ingredients: [...payload.ingredients].sort() }),\n contentVersion: 1,\n filters: ['italian', 'japanese'],\n index: (payload) => ({\n filter: payload.cuisine,\n tags: [payload.ingredients.length <= 5 ? 'quick' : 'involved'],\n title: payload.name,\n }),\n name: 'recipes',\n payloadSchema,\n tags: ['quick', 'involved'],\n});\n```\n\nThe Worker entry imports the collection and exports the built handler:\n\n```ts\n// backend/src/index.ts — the whole deployment.\nimport { createArchiveWorker } from '@vielzeug/archive/worker';\nimport { recipesCollection } from './recipes-collection';\n\nconst worker = createArchiveWorker([recipesCollection]);\n\n// One sanitized log line per request: ids, codes and route classes only.\nworker.tap((event) => console.log(JSON.stringify(event)));\n\nexport default worker;\n```\n\nThe browser imports the same collection for its schemas — never the worker subpath:\n\n```ts\nimport { recipesCollection } from './recipes-collection';\nimport { archiveIdentitySchema, PUBLISHER_HEADER } from '@vielzeug/archive';\n\nconst response = await fetch('/api/v1/collections/recipes/entries');\nif (!response.ok) throw new Error('Archive unavailable');\nconst page = recipesCollection.contract.page.parse(await response.json());\nconst meResponse = await fetch('/api/v1/me', { credentials: 'same-origin' });\nif (!meResponse.ok) throw new Error('Identity unavailable');\nconst me = archiveIdentitySchema.parse(await meResponse.json());\nif (me === null) throw new Error('Register a publisher first');\nconst mineResponse = await fetch('/api/v1/me/publications?collection=recipes', {\n credentials: 'same-origin',\n headers: { [PUBLISHER_HEADER]: me.id },\n});\nif (!mineResponse.ok) throw new Error('Own publications unavailable');\nconst owned = recipesCollection.contract.ownedEntries.parse(await mineResponse.json());\nconsole.log(page.entries, owned.entries);\n```\n\n## The collection contract\n\n`defineArchiveCollection` is the only place content knowledge lives. The definition is\nvalidated at registration — a bad `name`, `contentVersion`, or any vocabulary value\n(well-formed text, 1..`vocabChars` chars) throws there, never mid-request — and every\nordinary invalid content returns `null` → `422 invalid-payload`. Collection\nimplementation faults instead throw `ArchiveDerivationError` → sanitized\n`500 internal`:\n\n- **Parse** — accept stable JSON objects only; schema outputs must remain JSON.\n- **Canonicalize** — optional; a result that leaves the payload schema throws, so a\n broken normalizer can never store invalid content.\n- **Index** — the returned `filter` must be declared in `filters`, every `tag` in\n `tags` (duplicates collapse), and the `title` is trimmed and bounded\n (`titleChars`, well-formed text). A derivation outside the declared vocabulary\n would store a row no list query can reach — it throws instead.\n- **Size** — the canonical JSON must fit `payloadBytes`.\n- **Identity** — the content hash is SHA-256 over `{contentVersion, payload}`:\n identical content hashes identically, a real edit always re-identifies, and the\n core owns the envelope so collections cannot drift it.\n\nDeclare vocabularies with readonly arrays (`['fire', 'ice']`) for automatic\nliteral-union inference. Const generics retain the version literal and vocabulary\nunions; `NoInfer` prevents the index callback from widening them. Omitted arrays\nmean empty vocabularies: return `null` for\nthe filter and no tags. Object keys are recursively sorted by the core; schema\ntransformations must stabilize and `canonicalize` must be pure and idempotent.\nNon-JSON input returns `null`. Unexpected callback, schema or hashing failures,\nunstable transformations, non-idempotent canonicalization and index mutation throw\n`ArchiveDerivationError`; its `stage` identifies the failing phase.\nLossy or non-JSON schema output and invalid index-result shapes also throw.\n\n`contentVersion` participates in content identity. Request handling validates\nonly the current collection definition; it does not interpret historical schemas.\nArchive provides no content-upgrade APIs: a new definition never reinterprets\nstored rows.\n\nFilters, tags and searchable titles are persisted data derived at publish/update\ntime. Editing `index` or its vocabularies does not recompute existing projections.\nKeep the active definition and dataset consistent. For a development\ndeployment, deliberately reset and reseed a fresh database when you change payload\nor projection semantics; the package does not supply a migration framework.\nResetting destroys existing data. Perform it only as an explicit, deliberate\ndevelopment operation, not automatically during startup or deployment.\n\n**Payloads carry decisions, not content.** The payload schema should accept\nuser-authored choices expressed as IDs plus user-written text — never the content's\nown copyrighted expression (card text, artwork, rules), never more than the game's\nown identifiers. For games with paid or DLC content this is the whole answer:\nownership resolves on each viewer's device against their own library, the service\nnever learns what anyone owns, and the strict schema is the enforcement seam —\nuse a strict schema that rejects unknown fields, so a collection that only models IDs cannot\naccidentally start shipping paid content. For example, published game builds can\nreference cards, equipment and potions by ID plus a user-written name. The client\nrenders pieces the viewer does not own as unavailable. Keep the browser-safe\npublication contract in a shared domain module consumed by both the frontend and\nits backend, without importing frontend application code into the Worker.\n\n## The Worker and its environment\n\n`createArchiveWorker(collections)` returns the full handler: anonymous public reads,\ncookie-authenticated mutations behind exact-origin and request-marker guards, local\nRS256/JWKS verification followed by an uncached issuer session-version check,\nper-IP read limits and per-subject write limits keyed by peppered HMACs, the\n30-second anonymous cache on public entry lists only, operator moderation, and a\nscheduled expiry sweep for retired publish retry keys and revocation tombstones.\nHealth sits outside the rate-limit and session pipelines: probes never burn the\nanonymous read budget or call the issuer.\n\nThe Worker reads its environment fail-closed — every binding must be present and\nwell-formed, or the route answers 503 without naming what is missing:\n\n| Variable | Meaning |\n| ---------------------------------------------- | ----------------------------------------------------------------------------------------- |\n| `APP_ENV` | `local` or `production` (transport rules and the pepper policy) |\n| `ALLOWED_ORIGINS` | Exact canonical origins; never wildcards |\n| `JWT_ISSUER` / `JWT_AUDIENCE` / `JWT_JWKS_URL` | Exact issuer claim, audience and issuer JWKS endpoint URL |\n| `AUTH_ISSUER_SERVICE` | Required issuer service binding for signing-key retrieval and live session-version checks |\n| `LIKES_ENABLED` / `PUBLISHING_ENABLED` | Feature flags |\n| `RATE_LIMIT_KEY_SECRET` | HMAC pepper. Required ≥ 32 chars in production; local may fall back |\n| `DB` / `READ_LIMIT` / `WRITE_LIMIT` | D1 + rate-limit bindings |\n\nBoth limiter bindings must run 60-second windows (`simple` limiters:\n`period: 60`): the platform binding does not expose its period at runtime, so the\nWorker's 429 `Retry-After` header is fixed at 60 seconds — a longer window would\nmake the header lie. The read limit keys on `cf-connecting-ip`, which Cloudflare\nsets authoritatively for requests that reach the Worker through its network. Keep\nthat network path: never front the Worker with a proxy that forwards a\nclient-supplied header of the same name.\n\nGenerated Env types (wrangler's `worker-configuration.d.ts`) satisfy the package's\nstructural `ArchiveWorkerEnv` — no `@cloudflare/workers-types` dependency, no casts.\n\nSigning keys are fetched from `JWT_JWKS_URL` through `AUTH_ISSUER_SERVICE`, not\nglobal `fetch`. Point the URL at the bound issuer's `/api/v1/auth/jwks.json`\nroute; retain the HTTPS production or loopback HTTP local configuration rules.\nThis transport supports Workers on the same Cloudflare zone without a public\nWorker-to-Worker fetch. JOSE caches signing keys, but every private request still\nchecks the current issuer session version. A signing-key provider failure is\n`503 auth-unavailable`, not a reason to clear the browser's signed-in state.\n\n## The auth issuer\n\n`createAuthWorker()` from `@vielzeug/archive/auth` is the reference passwordless\nidentity issuer a deployment runs beside the catalog Worker: one POST with an email\nsends a single-use magic link, and explicitly confirming it sets the `archive_session`\ncookie. The catalog verifies the JWT locally, then calls the issuer through\n`AUTH_ISSUER_SERVICE` to check the account's current session version. Requests create\npending account rows; explicit link redemption atomically stamps the account's\nsign-in time and claims the token. The issuer's D1 schema ships at\n`node_modules/@vielzeug/archive/migrations/auth/`; point the issuer's\n`migrations_dir` there. The catalog's `JWT_ISSUER` and `JWT_JWKS_URL` must identify\nthe issuer, and its audience must match the issuer's `AUDIENCE`.\n\n| Variable | Meaning |\n| ------------------------------- | ----------------------------------------------------------------------------------------- |\n| `APP_NAME` | The app's display name in magic-link email and escaped confirmation-page branding |\n| `ALLOWED_ORIGINS` | Exact origins allowed to trigger unsafe routes (the app origin(s)) |\n| `APP_ENV` | `local` or `production` — production requires HTTPS and sets Secure cookies |\n| `AUDIENCE` / `AUTH_ISSUER` | The claims every minted session carries; the catalog verifies the same pair |\n| `AUTH_DB` / `AUTH_EMAIL` | The issuer's D1 and send-email bindings |\n| `AUTH_ARCHIVE` | Required service binding to the catalog Worker; deletion calls its profile-erasure route |\n| `AUTH_JWT_PRIVATE_JWK` | The RS256 private key as a JWK JSON string: a wrangler secret in production |\n| `AUTH_JWT_PREVIOUS_PUBLIC_JWKS` | Optional retired public RS256 JWKS; publish during rotation until old sessions expire |\n| `OPERATOR_EMAILS` | Comma-separated emails whose newly minted sessions carry the operator role |\n| `PUBLIC_ORIGIN` | App origin for links, confirmation POST origin checks and client navigation after sign-in |\n| `SENDER_ADDRESS` | The address magic links come from: a domain onboarded to Cloudflare Email Service |\n\nUnder `wrangler dev` the send-email binding is simulated — the link prints to the\nissuer's console, so that console is the inbox. Demo-only Alice/Bob routes are\ndeployment wrappers, not package APIs.\n\nThe issuer first admits sign-in requests through its singleton durable\n`auth_sign_in_budget` table: 20 requests per 60 seconds before creating accounts\nor delivering email. No rate-limiter binding is required. It then\npermits three sign-in emails per email in an hourly durable window.\nThose durable budgets guard `POST /auth/sign-in` and `POST /auth/device/sign-in`.\n`POST /auth/verify`, the device approval and claim routes, and\n`GET /auth/session` stay public: tokens are 256-bit, single-use and expire in\n15 minutes, so guessing is not the risk — but every request still costs the\nissuer: the verify GET renders the confirmation page, the verify POST performs a\nD1 token write, and the session check performs an RS256 verification plus an\naccount read for a well-formed signed token. Put per-client-IP Cloudflare\nrate-limit rules (or an equivalent edge control) in front of those routes in\nproduction. Prefer a block action: applications check `GET /auth/session` with\na `fetch`, and a fetch cannot solve a challenge interstitial, so challenging\nthat route breaks legitimate sign-in. The verify GET is a browser navigation\nopened from the email link, so a challenge is solvable there if you want one.\nSet thresholds with CGNAT headroom (shared mobile/office egress IPs) and tune\nfrom observed traffic.\nLater database or delivery failures do not refund global admission.\nUsing or expiring a link never refunds sends; failed delivery also spends the\nallowance. Links expire after 15 minutes. Operator sessions expire after 60 minutes\n(3600 seconds), ordinary sessions after at most 30 days. Retain retired public keys during\nrotation; the active private key signs every new session. Sign-in input trims and\nlowercases email before validation. `SENDER_ADDRESS` must already be canonical;\n`OPERATOR_EMAILS` entries are trimmed and lowercased before validation.\n\nThe scheduled sweep deletes expired links and closed per-user send windows, then\npending accounts only when neither a link nor send-budget row still references\nthem. Failed delivery deletes the unusable token but retains the spent allowance;\nit does not immediately remove the pending account. Verified accounts stay until\nexplicit erasure. The singleton admission row remains and resets its window on a\nlater admitted request.\n\nOpening `GET /auth/verify?token=…` renders a no-store confirmation page and does\nnot consume the link or change the session, so email scanners cannot sign in by\nfetching it. A deliberate click sends `POST /auth/verify` with JSON `{ token }`,\nthe request marker and an exact allowed origin or `PUBLIC_ORIGIN`.\nSuccess is 204 with Set-Cookie; the page then navigates to the fixed\n`${PUBLIC_ORIGIN}/signed-in` destination. Your application must serve that page;\nthe issuer only serves the confirmation endpoint. The redemption update and\naccount sign-in stamp are trigger-backed and atomic.\nThe page removes the token from the address bar, loads no external assets, and\nsets a restrictive CSP and `Referrer-Policy: no-referrer`. Its inline CSS and\nscript use a fresh nonce, never `unsafe-inline`. The page follows light/dark\npreferences, supports reduced motion, focuses the confirmation action and\nannounces pending, success and recovery states. Without JavaScript it links to\n`${PUBLIC_ORIGIN}/account` as “Request a new sign-in link” and does not pretend\nto complete sign-in.\n\n### Sign in an isolated installed app\n\nWhen the app and email browser do not share cookies, generate a random 32-byte\nbase64url proof in the app and compute the SHA-256 hex digest of the proof's\nUTF-8 text. Send `{ email, challenge }` to `POST /auth/device/sign-in` with the\nrequest marker. Show the first eight uppercase characters of the digest in the\napp: the approval page shows the same code, and users should approve only when\nthey match. The link's GET is non-destructive; its confirmation POST authorizes\nthe app but does not sign in the browser.\n\nThe app sends `{ token: proof }` to `POST /auth/device/claim` with credentials,\nthe request marker and an allowed origin. `202 { ok: false }` means no claimable\napproval; `204` sets the normal cookie in the app. Poll only while needed and\nwhile the app is visible, stop after 15 minutes, and serialize a claim with\naccount changes so a late cookie cannot overwrite another choice. Clear the\nproof on cancellation or completion. Do not log the proof or approval URL.\nAn existing valid session returns 409 without consuming the proof; recheck the\nsession rather than replacing that account.\nPending requests share the usual email budgets and are revoked by account\ndeletion or sign-out-all. Add edge rate limits for device approval and claim\nbefore enabling the feature; block rather than challenge the programmatic claim.\n\nArchive only serves the confirmation endpoint. Your application must serve its\nsign-in entry at the fixed `${PUBLIC_ORIGIN}/account` recovery destination and\nthe success page at `${PUBLIC_ORIGIN}/signed-in`. These are reference issuer\nroute conventions, not configurable destinations. The initial “Back to app”\nexit links to `${PUBLIC_ORIGIN}/`. No query parameter supplies a destination.\nExpired or already-used links (POST 410) require a new link rather than a retry.\nHTTP 429 enables manual retry after a `Retry-After` cooldown bounded to 1-300\nseconds, accepting unsigned integer seconds or valid HTTP-date syntax and\ndefaulting to 30 seconds for missing or invalid values, including negative or\nfractional numbers. HTTP 503 and network failures offer a retry button and a\nsecondary “Request a new sign-in link” action; invalid or expired links make\nthat recovery action primary. The page never\nautomatically retries, aborts stalled requests after 15 seconds and releases\nrequests/timers when you leave it. Response bodies, including stale responses,\nare cancelled without waiting, and completed attempts abort their controllers.\n\nWith valid issuer configuration, malformed GET links return HTTP 400 with branded\nrecovery HTML rather than the JSON error envelope. POST errors retain the JSON\nerror schema. A well-formed expired token still gets GET 200 confirmation: its\nredemption status is determined only by the deliberate POST.\n\n`GET /auth/account` exports account metadata only. For full erasure, call\n`DELETE /auth/account` with `ACCOUNT_HEADER` (`X-Archive-Account`) set to the\nissuer account UUID captured from `GET /auth/account` before confirmation.\nThe issuer rejects missing or invalid UUIDs with 400 and a different signed-in\naccount with 409 `account-changed`, before any erasure. This guard applies even\nbefore publisher registration and must stay pinned across retries.\nThe issuer forwards the caller's session and publisher\nprecondition through `AUTH_ARCHIVE` to `DELETE /me/account`, requires exactly 204,\nthen deletes its\nown user and clears the cookie. Failure preserves the session for retry. Direct\n`DELETE /me` removes only the Archive profile and leaves the cookie intact.\n\nSeveral game frontends can share one issuer and catalog. Keep the cookie\nhost-only on the central API host, use `credentials: 'include'` from same-site\nHTTPS game subdomains, and allow each exact frontend origin in both Workers.\nDo not share cookies through a parent-domain `Domain` attribute. The\n[multi-collection recipe](./examples/multi-collection-deployment.md) describes\nthe topology, session revalidation and platform-wide account boundary.\n\n`DELETE /me/account` atomically revokes the issuer/subject and cascades profile\ndeletion. Its tombstone lasts 30 days plus ten seconds; old sessions cannot read\nprivate data or register again, including a racing registration. The dedicated\naccount-erasure route alone may bypass the issuer lookup, and only to retry with\nthe same principal's original signed session while its existing tombstone is\nvalid; signature and claims are still verified, and initial erasure validates the\nissuer. The issuer's `DELETE /auth/account` checks the current version before\nstarting erasure; after completed erasure a retry there returns 401. A fresh\nissuer account gets a new UUID subject. External issuers must use a new subject to\nre-enroll during the revocation window. Profile-only deletion does not revoke the\nsubject and permits re-registration with existing credentials.\n\nEach JWT also carries the issuer account's required safe-integer `sessionVersion`.\nThe issuer compares it with `auth_users.session_version` on every ordinary\nauthenticated route. A JWT with an old version is unauthenticated even before its\nexpiry; the catalog asks the issuer on every private request and does not cache a\nsuccessful verdict. A valid local JWT with an unavailable, malformed, 5xx or\ntimed-out (fixed 5000 ms, including body decoding) issuer response becomes\n`503 auth-unavailable`, not anonymous identity.\n\n## The database\n\nThe package ships the canonical catalog migration:\n`node_modules/@vielzeug/archive/migrations/0001_community_archive.sql` — the whole schema,\nmoderation included, as one designed file. The runtime SQL in the package is\nwritten against exactly this schema, and the package's own integration suite runs\nagainst the same file. Point wrangler at the directory:\n\n```jsonc\n// wrangler.jsonc — the deployment owns its D1 database, not its DDL.\n{\n \"d1_databases\": [\n {\n \"binding\": \"DB\",\n \"database_name\": \"my-app\",\n \"migrations_dir\": \"./node_modules/@vielzeug/archive/migrations\"\n }\n ]\n}\n```\n\nThe issuer points to\n`node_modules/@vielzeug/archive/migrations/auth/0001_auth.sql`. Both files are\nfresh-database initialization definitions, not upgrades. The issuer DDL initializes\n`auth_users.session_version` to `0` and stamps `auth_schema_meta.applied` as\n`AUTH_SCHEMA_VERSION` (`1`). Neither file automatically deletes or resets data.\nArchive's canonical initial schemas are edited directly. Reset and reseed a\ndevelopment database deliberately when its schema or collection semantics no\nlonger match; reapplying the initial file does not update an existing dataset.\nThe initialization file also stamps the storage schema\n(`archive_schema_meta`) at `ARCHIVE_SCHEMA_VERSION`, and health reads it back: a\ndatabase with a mismatched stamp answers `status: 'degraded'` with the\nobserved `dbSchemaVersion` and HTTP 503 (`reason: 'schema-mismatch'`).\nAn unavailable database produces HTTP 503 with `dbSchemaVersion: null` and\n`reason: 'database-unavailable'`. The debut storage stamp is `1`. A unit\ntest pins the shipped DDL's `CHECK` bounds to `ARCHIVE_LIMITS`, so the two can never\ndrift silently. The stamp does not detect changes in your collection's payload\nschema, vocabulary or indexing function; you own that dataset consistency.\n\n## Routes and wire names\n\n```\nGET /api/v1/health\nPOST /api/v1/sign-out\nGET /api/v1/auth/health\nGET /api/v1/auth/session (internal issuer check)\nPOST /api/v1/auth/sign-out-all (revoke every session)\nGET /api/v1/collections/:collection (self-description)\nGET /api/v1/collections/:collection/entries (author, filter, tag, search, sort, cursor, limit)\nPOST /api/v1/collections/:collection/entries\nGET /api/v1/collections/:collection/entries/:id\nPUT /api/v1/collections/:collection/entries/:id (expectedRevision)\nDELETE /api/v1/collections/:collection/entries/:id\nPUT /api/v1/collections/:collection/entries/:id/like\nDELETE /api/v1/collections/:collection/entries/:id/like\nPOST /api/v1/collections/:collection/entries/:id/report (reason)\nPUT /api/v1/collections/:collection/entries/:id/hidden (operator)\nDELETE /api/v1/collections/:collection/entries/:id/hidden (operator)\nGET /api/v1/collections/:collection/reports (operator: status, cursor, limit)\nPUT /api/v1/collections/:collection/reports/:id/resolved (operator: report ID)\nDELETE /api/v1/publishers/:id (operator: erase any publisher)\nGET /api/v1/moderation-log (operator: cursor, limit)\nGET /api/v1/me POST /me PUT /me DELETE /me\nGET /api/v1/me/publications?collection=:collection GET /api/v1/me/likes[?ids=…]\nGET /api/v1/me/reports (cursor, limit)\nGET /api/v1/auth/account\nGET /api/v1/auth/jwks.json\nPOST /api/v1/auth/sign-in (email)\nPOST /api/v1/auth/device/sign-in (email and challenge)\nGET /api/v1/auth/device/approve?token=… (confirmation only)\nPOST /api/v1/auth/device/approve (authorizes device)\nPOST /api/v1/auth/device/claim (proof, then session cookie)\nDELETE /api/v1/auth/account (coordinated full erasure)\nDELETE /api/v1/me/account (issuer erasure seam; revokes subject)\nGET /api/v1/auth/verify?token=… (confirmation only)\nPOST /api/v1/auth/verify (guarded {token} redemption)\n```\n\nPublishing is bounded by `maxPublications` live entries per `(collection, owner)`.\nThe quota check runs inside the guarded insert.\n\nEvery list — entry pages, `/me/likes` without `ids`, `/me/reports`, operator\nreports and `/moderation-log` — pages forward-only: follow `cursor` until `null`,\npreserving query context; a cursor minted for another query is a 400. `limit`\ndefaults to `pageSize` and is at most `maxPageSize`; there is no total export\nbound. `/me/likes?ids=…` remains a subset lookup returning `{ ids }`, not a\npage, and cannot combine `ids` with `cursor` or `limit`.\n\nShared wire names live in the package — `archive_session` cookie,\n`x-archive-publisher` and `x-archive-request` headers, `ARCHIVE_ERROR_CODES`, and\n`ARCHIVE_LIMITS` — so a client and the Worker cannot drift. Parse failures with the\ncollection's composed schemas; parse errors with `archiveErrorResponseSchema`, the\nsign-out body with `archiveOkSchema`, a collection's self-description with\n`archiveCollectionMetaSchema` and the operator queue with `archiveReportsSchema`.\nEvery entry's `schemaVersion` is the archive contract's version, not the\ncollection's; the collection's own format version lives in its hash envelope and in\neach entry's `contentVersion`.\n\nOnly anonymous entry lists carry a 30-second edge-cache contract\n(`publicCacheSeconds`). Detail is always `no-store`. Any Cookie or Authorization\nheader disables caching, regardless of validity; metadata, private and error\nresponses also use `no-store`.\n\nImplement UI ownership checks in your application by comparing the current\npublisher ID to the entry's `author.id`; there is no package action-policy helper.\nServer mutations remain authoritative.\n\n`POST /api/v1/sign-out` is deliberately local: it clears only this browser's\ncookie and does not contact the issuer or revoke copied sessions. To revoke every\nsession, post to `/api/v1/auth/sign-out-all` with the mutation marker, an exact\nallowed `Origin`, and the issuer account UUID captured from\n`GET /api/v1/auth/account` in `X-Archive-Account`. The issuer returns 409\n`account-changed` if the active subject differs. On success it atomically increments\n`session_version`, deletes outstanding links, preserves account and catalog data,\nand returns `{ ok: true }` with an expired cookie. Requests authorized before\nrevocation may finish; there is no cross-database cancellation guarantee.\n\n`GET /api/v1/auth/health` is public and read-only. It validates issuer\nconfiguration, key signing/verification, binding shapes, the `auth_schema_meta`\nstamp and expected tables, columns and triggers, returns `AuthHealth` through\n`archiveAuthHealthSchema`, and answers 503 `degraded` for configuration,\ndatabase or schema failures. It never writes, sends email or probes the catalog.\n\n## Moderation\n\nOperator authority is the session token's optional `roles` claim carrying\n`ARCHIVE_OPERATOR_ROLE` (`'archive-operator'`) — minted by your issuer, verified with\nthe same signature, audience and issuer checks as any session, and never a separate\ncredential. Mint operator sessions with a lifetime of at most\n`OPERATOR_SESSION_MAX_AGE_SECONDS` (3600 seconds): the catalog rejects any token\ncarrying the operator role whose signed lifetime or age exceeds it, so reusing the\nordinary long session expiry 401s operator sessions immediately. Moderation routes\nadditionally require a registered publisher row: one accountable identity per action.\n\n- **Report** — any registered publisher reports a visible entry with a bounded\n free-text reason (`reportReasonChars`). Idempotent per (entry, reporter): the same\n report twice is the same 204. Missing or hidden entries answer 404 — there is\n nothing left to report.\n- **Hide** — an operator removes an entry from every public surface (list, detail,\n likes) with a soft-hide: the row, its likes and its retry key stay intact. The\n owner still sees the entry in `/me/publications` with `hidden: true`, edits and\n key replay are frozen (403), removal stays allowed, and unhiding restores\n everything. Already hidden or already visible answer the same 204.\n- **Queue** — the operator pages newest reports with entry title and reporter\n identity; `status` is `unresolved` (default) or `resolved`. Each report has its\n own `id` and nullable `resolvedAt`. Resolve it with\n `PUT /collections/:collection/reports/:id/resolved`; repeating is a 204 no-op.\n- **Log** — every effective moderation action (hide, unhide, removal, publisher\n erasure) appends one accountability row in the same transaction that applies it,\n and `GET /api/v1/moderation-log` pages the newest actions to\n operators. Rows carry only ids, the action kind and the time — no names (they\n change), no content — and no foreign keys: the audit must outlive the erasures it\n records. Idempotent repeats (hiding an already-hidden entry, erasing an\n already-erased publisher) answer the same 204 with no new row, including\n concurrent repeats: audit insertion tests the effective state inside the batch.\n\nLike and unlike both require a visible entry. Their SQL guards visibility during\nthe mutation, and the response checks it again; hiding or deleting an entry\ncannot turn a racing unlike into a successful response for unavailable content.\n\n## Observability\n\nThe core never logs. `worker.tap(handler, { signal? })` emits one `ArchiveEvent` per\nrequest — `{ type: 'request', code, ms, requestId, route, status, diagnostic? }` —\nand successful sweep — `{ type: 'scheduled', status: 'ok', removed }`. Failed\nsweeps emit `{ type: 'scheduled', status: 'failed', diagnostic }` and rethrow so\nthe runtime sees failure. Cache failures emit `{ type: 'cache-error', diagnostic }`.\nThe Worker swallows observer errors so\nobservability cannot affect the Worker. With no handlers registered there is zero\nwork. Route is a finite class like `/collections/:collection/entries`, never a\nraw path; no event carries a URL, cookie, subject, alias or token. Diagnostics are\ntyped sanitized categories, not raw exceptions. A pre-aborted tap signal is inert.\nThe sweep's `removed` counts expired retry keys and revocation tombstones together.\n\nThe issuer also exposes `tap()` with `AuthEvent` from `@vielzeug/archive/auth`.\nIt never logs directly. Events contain finite route labels, codes, counts,\nduration and sanitized `AuthDiagnostic` categories, never emails, tokens or raw\nexceptions. Scheduled failures emit then rethrow; pre-aborted taps are inert.\nIssuer sweep counts include expired tokens, closed per-user send windows and\nremoved pending accounts; the singleton admission row is not removed.\n\n```ts\nimport { createLogger } from '@vielzeug/rune';\nimport { createArchiveWorker } from '@vielzeug/archive/worker';\nimport { recipesCollection } from './recipes-collection';\n\nconst log = createLogger({ namespace: 'recipes' });\nconst worker = createArchiveWorker([recipesCollection]);\nworker.tap((event) => log.debug(event, `archive:${event.type}`));\nexport default worker;\n```\n\n## Testing\n\nThe package proves itself against real workerd + local D1:\n\n```sh\nbun x vitest run packages/archive/src/__tests__/ # fast unit suite\nbun run --filter @vielzeug/archive test:integration # real workerd + local D1 + issuer coverage\nbun run --filter @vielzeug/archive test:types # strict types over src and the integration suite\n```\n\nProve your own collection the way the reference deployment does: a slim deployment\nsuite that publishes over your real vocabulary and asserts the derivation, plus the\npackage's generic suite for the core behavior. A collection with an `index` that can\ndrift out of vocabulary should unit-test `derive` directly: ordinary invalid input\nreturns `null`, while implementation faults throw `ArchiveDerivationError`.\nDirect DDL tests exercise the shipped schema rather than a duplicate schema.\n\n## Framework Integration\n\nThe root entry is plain TypeScript with no framework coupling; Vue, React and Svelte\napps all consume the composed schemas the same way. A Vue 3 composable that pages a\ncollection:\n\n```ts\n// useRecipes.ts — one collection's typed client in any component tree.\nimport { recipesCollection } from './recipes-collection';\nimport { ref, shallowRef } from 'vue';\n\nexport function useRecipes() {\n const entries = shallowRef<ReturnType<typeof recipesCollection.contract.entry.parse>[]>([]);\n const cursor = ref<string | null>(null);\n async function load(sort: 'liked' | 'recent') {\n const params = new URLSearchParams({ sort });\n if (cursor.value !== null) params.set('cursor', cursor.value);\n const response = await fetch(`/api/v1/collections/recipes/entries?${params}`);\n if (!response.ok) throw new Error('The archive is unavailable.');\n const page = recipesCollection.contract.page.parse(await response.json());\n entries.value = [...entries.value, ...page.entries];\n cursor.value = page.cursor;\n }\n return { cursor, entries, load };\n}\n```\n\n## Working with Other Vielzeug Libraries\n\n- [Spell](/spell/) — the payload schema a collection declares; the core composes the\n envelope schemas from it, so the wire and the types cannot drift.\n- [Courier](/courier/) — the HTTP client shape an app's frontend mirrors to consume\n these routes: strict response schemas over one typed port.\n- [Rune](/rune/) — the structured logger a deployment points `tap()` events at.\n\n## Best Practices\n\n- Compose client schemas from `collection.contract`; never hand-write the envelope.\n- Declare exactly the vocabulary your `index` derives, with union types where you\n have them; a value outside it rejects loudly.\n- Keep `canonicalize` pure and schema-true: reordered lists in, canonical form out.\n- Initialize fresh databases with the shipped DDL and deliberately reset/reseed\n development data when collection or storage semantics change.\n- Treat `ARCHIVE_ERROR_CODES` and `archiveErrorResponseSchema` as one tested contract.\n- Pin the expected-publisher header from the identity you captured at sign-in, never from storage alone.\n- Grant the operator role claim only through your issuer, and only to accounts that\n are also registered publishers.\n- Wire a sanitized `tap()` sink and register the rate-limit pepper as a production secret.\n- Rate-limit the issuer's public `verify` and `session` routes at the edge; the\n durable budgets cover sign-in admission only.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Archive: Examples'\ndescription: 'Task-oriented recipes for @vielzeug/archive, from first deployment to erasure.'\n---\n\n- [Stand Up a Content Archive](./examples/stand-up-a-content-archive.md)\n- [Content Identity and Versions](./examples/content-identity-and-versions.md)\n- [Multi-Collection Deployment](./examples/multi-collection-deployment.md)\n- [Moderate Content](./examples/moderate-content.md)\n- [Client Error Mapping](./examples/client-error-mapping.md)\n- [GDPR Erasure and Export](./examples/gdpr-erasure-and-export.md)\n"
|
|
8
8
|
},
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
"apiSource": "export { catalogKeys } from './catalog';\nexport {\n LinguaDisposedError,\n LinguaError,\n LinguaInvalidCatalogError,\n LinguaInvalidLocaleError,\n LinguaInvalidPluralCountError,\n LinguaMissingCatalogError,\n LinguaMissingKeyError,\n LinguaMissingValueError,\n} from './errors';\nexport { createI18n, type I18n } from './i18n';\nexport { createTranslator, type Translator } from './translator';\nexport type {\n Catalog,\n CatalogNode,\n Catalogs,\n I18nOptions,\n Locale,\n MessageKey,\n MissingHandler,\n MissingInfo,\n MissingStrategy,\n PartsOptions,\n PluralCategory,\n PluralKey,\n PluralMessage,\n PluralOptions,\n PluralPartsOptions,\n Segment,\n SerializedI18n,\n SubscribeOptions,\n TextKey,\n TranslateOptions,\n TranslatorOptions,\n Values,\n} from './types';\n",
|
|
3
3
|
"docs": {
|
|
4
4
|
"index": "---\ntitle: 'Lingua: Explicit localization for TypeScript'\ndescription: Framework-neutral locale catalogs, typed translations, and explicit plural messages.\npackage: lingua\ncategory: i18n\nkeywords: [internationalization, translations, pluralization, locale, i18n, catalog-loading]\nrelated: [ripple, wayfinder, courier]\nexports:\n [\n createI18n,\n createTranslator,\n LinguaError,\n LinguaDisposedError,\n LinguaInvalidCatalogError,\n LinguaInvalidLocaleError,\n LinguaInvalidPluralCountError,\n LinguaMissingCatalogError,\n LinguaMissingKeyError,\n LinguaMissingValueError,\n ]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"lingua\" />\n\n## Why Lingua?\n\nLingua separates immutable translation from mutable locale state. Use `createTranslator` for one fixed-locale catalog, or `createI18n` when locale changes at runtime.\n\n```ts\n// Before\nconst message = catalogs[locale]?.inbox?.[count === 1 ? 'one' : 'other'] ?? 'inbox';\n\n// After\nconst output = i18n.translate('inbox', { count });\n```\n\n| Feature | Lingua | i18next | FormatJS |\n| ------------------------------- | -------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- |\n| Bundle size | <PackageInfo package=\"lingua\" type=\"size\" /> | Varies by selected modules | Varies by selected modules |\n| Zero runtime dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> |\n| Explicit plural catalog nodes | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Convention/config dependent | ICU-message dependent |\n| Static and lazy locale catalogs | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Plugin/config dependent | Application-defined |\n| Immutable locale snapshots | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Application-defined | Application-defined |\n\n<div class=\"decision-callout\">\n\n**Use Lingua when** you need a compact TypeScript runtime with explicit catalog structure, deterministic fallback, and framework-neutral subscriptions.\n\n**Consider i18next or FormatJS when** you need their plugin ecosystems, message extraction pipelines, or framework-specific integrations.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/lingua\n```\n\n```sh [npm]\nnpm install @vielzeug/lingua\n```\n\n```sh [yarn]\nyarn add @vielzeug/lingua\n```\n\n:::\n\n## Quick Start\n\nCreate an i18n instance with an eager default catalog and a loader for other locales.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst en = { inbox: { plural: { one: 'One message', other: '{count} messages' } } };\nconst i18n = createI18n({\n catalogs: { en },\n locale: 'en',\n loadCatalog: (locale) => import(`./locales/${locale}.ts`).then((m) => m.default),\n});\n\ntry {\n console.log(i18n.translate('inbox', { count: 3 }));\n await i18n.setLocale('de');\n console.log(i18n.translate('inbox', { count: 1 }));\n} finally {\n i18n.dispose();\n}\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createTranslator()` compiles one immutable fixed-locale catalog.\n- `createI18n()` manages eager catalogs, locale changes, and optional lazy loading.\n- `translate()` renders text and plural messages through explicit catalog nodes.\n- `load()` deduplicates loading and resolves the active locale plus configured fallbacks.\n- `getSnapshot()` and `subscribe()` expose a stable locale snapshot for framework stores.\n- `serialize()` transfers resolved SSR catalogs for client hydration.\n- `missing: 'throw' | 'key' | handler` controls failure behaviour.\n- `validateCatalog()` remains an isolated subpath tool.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Ripple](../ripple/index.md) adapts Lingua snapshots into reactive application state.\n- [Courier](../courier/index.md) can fetch locale catalogs before passing them to Lingua loaders.\n- [Wayfinder](../wayfinder/index.md) can drive locale selection from route state.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Lingua: API Reference'\ndescription: Complete API reference for @vielzeug/lingua.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ---------------------- | ------------------------------------------------------------ | -------------- | ------------------------------------------------------------------------------------------- |\n| `createTranslator()` | Compile one immutable locale catalog | Sync | No fallback locales |\n| `createI18n()` | Create mutable locale and catalog store | Sync | Provide eager catalogs, a loader, or both |\n| `createFormatter()` | Create a cached Intl facade from `/format` | Sync | Pass a locale getter for dynamic locale changes |\n| `createReactiveI18n()` | Mirror an i18n instance into ripple readables from `/ripple` | Sync | Optional `@vielzeug/ripple` peer; import from subpath |\n| `catalogKeys()` | Enumerate message keys as dotted paths | Sync | Takes a catalog (or subtree) only; for an i18n instance pass `state.catalogs[state.locale]` |\n| `validateCatalog()` | Check explicit plural forms from `/validate` | Sync | Import from subpath |\n| `compareCatalogs()` | Compare key parity across locales from `/validate` | Sync | First locale is the base; import from subpath |\n| `LinguaError` | Base class for Lingua errors | Sync | Use `instanceof LinguaError` for broad narrowing |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --------------------------- | ------------------------------------------------------------------------------------------- |\n| `@vielzeug/lingua` | Translation factories, state types, and Lingua errors |\n| `@vielzeug/lingua/format` | Standalone cached Intl formatter factory |\n| `@vielzeug/lingua/ripple` | `createReactiveI18n()`: reactive locale/translate bridge (optional `@vielzeug/ripple` peer) |\n| `@vielzeug/lingua/validate` | `validateCatalog()`, `compareCatalogs()`, and `ValidationIssue` |\n\n## Translation Factories\n\n### createTranslator\n\n```ts\nfunction createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C>;\n```\n\nCompiles one catalog and returns an immutable fixed-locale translator. Locale defaults to `en` and controls plural selection and diagnostics.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | --------------------------------------------------------- |\n| `catalog` | `C` | One catalog containing only messages and grouping objects |\n| `options` | `TranslatorOptions` | Locale and missing-message strategy |\n\n**Returns:** `Translator<C>`.\n\n**Example:**\n\n```ts\nimport { createTranslator } from '@vielzeug/lingua';\n\nconst translator = createTranslator({ save: 'Enregistrer' }, { locale: 'fr' });\n\ntranslator.translate('save');\n```\n\n| Method | Signature | Returns |\n| ------------------ | -------------------------------------------------------------------- | ---------------------- |\n| `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })` | Rendered string |\n| `translateUnkeyed` | `(key: string, options?)` | Rendered string |\n| `parts` | `(textKey, { values? })` or `(pluralKey, { count, ordinal?, values? })` | Render-order `Segment<V>[]` |\n| `partsUnkeyed` | `(key: string, options?)` | Render-order `Segment<V>[]` |\n| `locale` | `Locale` | Resolved active locale |\n\n---\n\n### createI18n\n\n```ts\nfunction createI18n<C extends Catalog>(options: I18nOptions<C>): I18n<C>;\n```\n\nCreates the catalog store, current locale state, and the active translator.\n\n| Parameter | Type | Description |\n| --------------------- | ----------------------------- | ------------------------------------------------ |\n| `options.catalogs` | `Catalogs<C>` | Eager locale catalogs |\n| `options.locale` | `Locale` | Initial locale; defaults to `en` |\n| `options.loadCatalog` | `(locale) => Promise<C> \\| C` | Loader for catalogs not supplied eagerly |\n| `options.fallback` | `Locale \\| readonly Locale[]` | Fallback locales loaded with the selected locale |\n| `options.missing` | `MissingStrategy` | Missing-key/value strategy |\n\nProvide at least one of `catalogs` or `loadCatalog`; you may combine eager `catalogs` with `loadCatalog` for later locales.\n\n**Returns:** `I18n<C>`, with every `Translator<C>` method plus lifecycle methods.\n\n**Example:**\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { title: 'Home' } },\n locale: 'en',\n});\ni18n.translate('title');\n```\n\n| Method or property | Signature | Returns |\n| ------------------ | ------------------------------------- | -------------------------------------------------------------- |\n| `translate` | Translator method | Rendered string |\n| `translateUnkeyed` | Translator method | Rendered string for a runtime key outside the typed key set |\n| `parts` | Translator method | Render-order `Segment<V>[]` for the committed locale |\n| `partsUnkeyed` | Translator method | Render-order `Segment<V>[]` for a runtime key |\n| `load` | `({ locale? })` | `Promise<void>` after the locale and configured fallbacks load |\n| `setLocale` | `(locale)` | `Promise<void>` after an atomic loaded-locale commit |\n| `isLoaded` | `({ locale? })` | `boolean` |\n| `getSnapshot` | `()` | Current locale, referentially stable until it changes |\n| `subscribe` | `(listener, { immediate?, signal? })` | Unsubscribe function; listener receives the new locale |\n| `serialize` | `()` | Loader-free `SerializedI18n<C>` for SSR transfer |\n| `dispose` | `()` | `void` |\n| `locale` | `Locale` | Current canonical locale |\n| `disposed` | `boolean` | Disposal state |\n| `disposalSignal` | `AbortSignal` | Aborts on disposal |\n| `[Symbol.dispose]` | `()` | Delegates to `dispose()` |\n\n**Memoization rule:** `translate` and `parts` have a deliberately stable function identity across `setLocale()` — they read the committed engine at call time, while `getSnapshot()` returns the locale string whose identity changes exactly when the locale does. Memoize derived translations on the **locale**, never on the function's identity (`useMemo(..., [i18n.translate])` keeps the previous language).\n\n---\n\n## Rich content (`parts`)\n\n`parts()` resolves a message exactly like `translate()` — same plural selection, locale fallback, and `missing` strategy — but returns the message as render-order segments, so framework nodes can enter a sentence without ever being stringified.\n\n```ts\nconst segments = i18n.parts('link', { values: { label: <Link href=\"/sync\">Sync</Link> } });\n// [ { type: 'text', value: 'Go to ' }, { type: 'value', name: 'label', value: <Link/> }, { type: 'text', value: ' now.' } ]\n```\n\n| Contract | Behavior |\n| ------------ | ------------------------------------------------------------------------------------------------- |\n| Order | Segments are in render order; a value used twice produces two value segments; unreferenced values are ignored |\n| Text | Text segments are never empty — adjacent placeholders yield adjacent value segments |\n| Values | Passed through untouched with identity preserved; never `String()`-ified, escaped, or merged with neighbors |\n| Missing value | Becomes a **text** segment holding the `missing` strategy's output (`null`/`undefined` count as missing; `''` is a real value) |\n| Missing key | One text segment holding the strategy's output; `'throw'` still throws |\n| Plural | `parts(key, { count, ordinal?, values? })`; `count` is interpolated into the selected form and can be overridden by an explicit `count` in `values` |\n| Equivalence | Joining segments with `String()` reproduces `translate()` exactly, so `parts` is safe as your single resolution path |\n\nThe interpolation contract shared by `translate()` and `parts()`: string values are inserted verbatim (no HTML or entity escaping), non-string values are `String(value)`-ified, and nullish values follow the `missing` strategy. Rich UIs should render `parts` segments instead of smuggling placeholders through a translated string: because values never enter the concatenated string, user data cannot reach an HTML sink through it.\n\n`V` defaults to `string`; pass your node type to keep rendering type-safe: `i18n.parts<ReactNode>('link', { values: { label: <Link/> } })`.\n\n---\n\n## Reactive bridge (`@vielzeug/lingua/ripple`)\n\n### createReactiveI18n\n\n```ts\nfunction createReactiveI18n<C extends Catalog>(i18n: I18n<C>): ReactiveI18n<C>;\n```\n\nBridges a lingua instance into `@vielzeug/ripple` so translated strings are reactive. `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()` computes once and never re-runs, since it registers no tracked dependency. The bridge's `translate`, `translateUnkeyed`, `parts`, and `partsUnkeyed` 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`/`partsUnkeyed`: calling `i18n.translateUnkeyed` directly skips the reactive locale and caches the first result.\n\n`@vielzeug/ripple` is an optional peer dependency: install it only when you use this subpath.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\nimport { createReactiveI18n } from '@vielzeug/lingua/ripple';\nimport { computed } from '@vielzeug/ripple';\n\nconst reactive = createReactiveI18n(createI18n({ catalogs, locale: 'en' }));\n\nconst heading = computed(() => reactive.translate('title')); // re-computes on setLocale()\nawait reactive.i18n.setLocale('fr');\n```\n\n| Property or method | Signature | Returns |\n| ------------------ | ------------------ | ------------------------------------------------------------------------------- |\n| `i18n` | `I18n<C>` | The underlying instance for imperative work (`setLocale`, `load`, disposal) |\n| `locale` | `Readable<Locale>` | Reactive locale: reading it inside a computed/template registers the dependency |\n| `translate` | `(key, options?)` | Rendered string; re-evaluates whenever the locale changes |\n| `translateUnkeyed` | `(key, options?)` | Rendered string for a runtime key; re-evaluates whenever the locale changes |\n| `parts` | `(key, options?)` | Render-order `Segment<V>[]`; re-evaluates whenever the locale changes |\n| `partsUnkeyed` | `(key, options?)` | `Segment<V>[]` for a runtime key; re-evaluates whenever the locale changes |\n\n---\n\n## Catalog Utilities\n\n### catalogKeys\n\n```ts\nfunction catalogKeys<C extends Catalog>(catalog: C): ReadonlyArray<MessageKey<C>>;\n```\n\nEnumerates every message key as a dotted path. Traverses nested grouping objects and explicit `{ plural: ... }` messages, producing the same paths that `TextKey<C>` represents at the type level. Pass any catalog object or subtree; for an `I18n` instance, read its current locale catalog first.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | ----------------------------------------- |\n| `catalog` | `C extends Catalog` | Raw catalog object or any catalog subtree |\n\n**Returns:** `ReadonlyArray<MessageKey<C>>`: dotted paths to every text and plural message.\n\n```ts\nimport { catalogKeys, createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { nav: { home: 'Home', settings: 'Settings' } } },\n locale: 'en',\n});\n\nconst state = i18n.serialize();\nconst allKeys = catalogKeys(state.catalogs[state.locale]); // ['nav.home', 'nav.settings']\nconst navKeys = catalogKeys(state.catalogs.en.nav); // ['home', 'settings']\n```\n\n---\n\n## Intl formatting\n\n### createFormatter\n\n```ts\nimport { createFormatter } from '@vielzeug/lingua/format';\n\nconst format = createFormatter(() => i18n.locale);\nformat.number(1_234.5);\nformat.currency(19.99, 'USD');\nformat.date(new Date(), { dateStyle: 'medium' });\n```\n\nThe formatter caches bounded `Intl` instances and resolves a locale getter for every call.\n\n## Validation\n\n### validateCatalog\n\n```ts\nfunction validateCatalog(catalog: Catalog, locale: Locale): ValidationIssue[];\n```\n\nValidates explicit plural messages against locale plural categories after catalog structural validation.\n\n| Parameter | Type | Description |\n| --------- | --------- | ---------------------------- |\n| `catalog` | `Catalog` | Explicit catalog to validate |\n| `locale` | `Locale` | BCP 47 locale tag |\n\n**Returns:** `ValidationIssue[]`.\n\n**Example:**\n\n```ts\nimport { validateCatalog } from '@vielzeug/lingua/validate';\n\nvalidateCatalog({ inbox: { plural: { one: 'One message' } } }, 'en');\n```\n\n### compareCatalogs\n\n```ts\nfunction compareCatalogs<C extends Catalog>(catalogs: Catalogs<C>): CatalogComparison;\n```\n\nCompares key sets across locales. First locale is the base: reports keys missing in each target and keys present in targets but absent from base. Validates each catalog structurally.\n\n| Parameter | Type | Description |\n| ---------- | ------------- | -------------------------------- |\n| `catalogs` | `Catalogs<C>` | Locale-keyed catalogs to compare |\n\n**Returns:** `CatalogComparison` with `missing` and `extra` arrays.\n\n```ts\nimport { compareCatalogs } from '@vielzeug/lingua/validate';\n\nconst result = compareCatalogs({\n en: { greeting: 'Hello', farewell: 'Goodbye' },\n de: { greeting: 'Hallo' },\n});\n// { missing: [{ key: 'farewell', locale: 'de' }], extra: [] }\n```\n\n## Types\n\n```ts\ntype Locale = string;\ntype PluralCategory = Intl.LDMLPluralRule;\ntype PluralMessage = { readonly plural: Partial<Record<PluralCategory, string>> };\ntype CatalogNode = Catalog | PluralMessage | string;\ntype Catalog = { readonly [key: string]: CatalogNode };\ntype Catalogs<C extends Catalog = Catalog> = Record<Locale, C>;\n\ntype MissingInfo = { readonly key: string; readonly locale: Locale; readonly name?: string };\ntype MissingHandler = (info: MissingInfo) => string;\ntype MissingStrategy = 'throw' | 'key' | MissingHandler;\n\ntype TranslatorOptions = { readonly locale?: Locale; readonly missing?: MissingStrategy };\n\ntype I18nOptions<C extends Catalog = Catalog> = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n} & (\n | { readonly catalogs: Catalogs<C>; readonly loadCatalog?: CatalogLoader<C> }\n | { readonly catalogs?: Catalogs<C>; readonly loadCatalog: CatalogLoader<C> }\n);\n\ntype CatalogLoader<C extends Catalog> = (locale: Locale) => Promise<C> | C;\n\ntype SerializedI18n<C extends Catalog = Catalog> = {\n readonly catalogs: Catalogs<C>;\n readonly locale: Locale;\n};\n\ntype I18n<C extends Catalog = Catalog> = Translator<C> & {\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n getSnapshot(): Locale;\n isLoaded(options?: { locale?: Locale }): boolean;\n load(options?: { locale?: Locale }): Promise<void>;\n serialize(): SerializedI18n<C>;\n setLocale(locale: Locale): Promise<void>;\n subscribe(listener: (locale: Locale) => void, options?: SubscribeOptions): () => void;\n [Symbol.dispose](): void;\n};\n\ntype Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n translateUnkeyed(key: string, options?: TranslateOptions | PluralOptions): string;\n parts<V = string>(key: TextKey<C>, options?: PartsOptions<V>): readonly Segment<V>[];\n parts<V = string>(key: PluralKey<C>, options: PluralPartsOptions<V>): readonly Segment<V>[];\n partsUnkeyed<V = string>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>): readonly Segment<V>[];\n};\n```\n\n```ts\ntype Values = Record<string, unknown>;\ntype TranslateOptions = { values?: Values };\ntype PluralOptions = TranslateOptions & { count: number; ordinal?: boolean };\ntype SubscribeOptions = { immediate?: boolean; signal?: AbortSignal };\n\ntype Segment<V = string> =\n | { readonly type: 'text'; readonly value: string }\n | { readonly type: 'value'; readonly name: string; readonly value: V };\ntype PartsOptions<V = string> = { values?: Record<string, V> };\ntype PluralPartsOptions<V = string> = PartsOptions<V> & { count: number; ordinal?: boolean };\n\ntype CatalogPaths<\n C,\n Leaf,\n Prefix extends string = '',\n Depth extends readonly unknown[] = readonly [1, 1, 1, 1, 1, 1],\n> = Depth extends readonly [unknown, ...infer Rest]\n ? C extends Leaf\n ? Prefix\n : C extends PluralMessage\n ? never\n : C extends Catalog\n ? {\n [K in string & keyof C]: CatalogPaths<C[K], Leaf, Prefix extends '' ? K : `${Prefix}.${K}`, Rest>;\n }[string & keyof C]\n : never\n : never;\n\ntype MessageKey<C> = CatalogPaths<C, string | PluralMessage>;\ntype TextKey<C> = CatalogPaths<C, string>;\ntype PluralKey<C> = CatalogPaths<C, PluralMessage>;\n\ntype ValidationIssue = { key: string; locale: Locale; missing: Intl.LDMLPluralRule };\ntype CatalogComparison = {\n readonly missing: ReadonlyArray<{ key: string; locale: Locale }>;\n readonly extra: ReadonlyArray<{ key: string; locale: Locale }>;\n};\n```\n\n## Errors\n\n| Error | Trigger |\n| ------------------------------- | ------------------------------------------------------- |\n| `LinguaDisposedError` | State mutation or subscription after `dispose()` |\n| `LinguaInvalidCatalogError` | Invalid catalog node or reserved key |\n| `LinguaInvalidLocaleError` | Invalid BCP 47 locale tag |\n| `LinguaInvalidPluralCountError` | Non-finite plural count |\n| `LinguaMissingCatalogError` | No `loadCatalog` function or catalog source unavailable |\n| `LinguaMissingKeyError` | Missing translation key when `missing: 'throw'` |\n| `LinguaMissingValueError` | Missing interpolation value when `missing: 'throw'` |\n",
|
|
6
|
-
"usage": "---\ntitle: 'Lingua: Usage Guide'\ndescription: Translate explicit catalogs, load lazy locales, and connect locale snapshots to UI state.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate an i18n instance with eager locale catalogs. Strings are text messages; plural messages use `{ plural: ... }`.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: {\n en: {\n greeting: 'Hello, {name}!',\n inbox: { plural: { one: 'One message', other: '{count} messages' } },\n },\n },\n locale: 'en',\n});\n\nconsole.log(i18n.translate('greeting', { values: { name: 'Ada' } }));\nconsole.log(i18n.translate('inbox', { count: 3 }));\n```\n\nCall `dispose()` when the instance belongs to a temporary request, test, or route owner.\n\n## Define Explicit Catalogs\n\nUse nested objects only to group keys. A plural message always has `plural`, so regular objects containing `one` or `other` remain groups.\n\n```ts\nconst catalog = {\n account: {\n greeting: 'Hello, {name}!',\n unread: { plural: { one: 'One unread message', other: '{count} unread messages' } },\n },\n};\n```\n\nUse `{ values }` for text replacements. Pass `count` at top level for plural selection; Lingua injects it into selected template.\n\nCatalogs contain strings, grouping objects, and explicit `{ plural: ... }` messages only. Keep application data outside catalog, then translate display labels while constructing it.\n\n```ts\nimport { createTranslator } from '@vielzeug/lingua';\n\nconst messages = {\n status: { blocked: 'Blocked', done: 'Done', inProgress: 'In progress' },\n};\nconst statusDefinitions = [\n { labelKey: 'status.inProgress', value: 'in-progress' },\n { labelKey: 'status.blocked', value: 'blocked' },\n { labelKey: 'status.done', value: 'done' },\n] as const;\nconst translator = createTranslator(messages, { locale: 'en' });\nconst statusOptions = statusDefinitions.map(({ labelKey, value }) => ({\n label: translator.translate(labelKey),\n value,\n}));\n```\n\n## Missing Keys and Values\n\nMissing keys and values do not silently echo placeholders by default: Lingua warns in development and returns the key or `{name}`. Control failure behaviour with the `missing` option:\n\n| `missing` | Behaviour |\n| --------------------- | --------------------------------------------------------- |\n| `undefined` (default) | Warn in development; return key / `{name}` |\n| `'key'` | Return key / `{name}` silently |\n| `'throw'` | Throw `LinguaMissingKeyError` / `LinguaMissingValueError` |\n| `handler` | Call `({ key, locale, name? }) => string` |\n\n```ts\nconst translator = createTranslator(messages, { locale: 'en', missing: 'throw' });\n```\n\n## Enumerate Catalog Keys\n\nUse `catalogKeys()` to derive key arrays from the catalog itself instead of maintaining a parallel list that can go stale. It traverses nested grouping objects and explicit `{ plural: ... }` messages, returning the same dotted paths that `MessageKey<C>` represents at the type level.\n\nFor an `I18n` instance, read its current locale catalog first.\n\n```ts\nimport { catalogKeys, createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: {\n en: {\n greeting: 'Hello, {name}!',\n inbox: { plural: { one: 'One message', other: '{count} messages' } },\n nav: { home: 'Home', settings: 'Settings' },\n },\n },\n locale: 'en',\n});\n\nconst state = i18n.serialize();\nconst allKeys = catalogKeys(state.catalogs[state.locale]);\n// ['greeting', 'inbox', 'nav.home', 'nav.settings']\n```\n\nPass a raw catalog object to enumerate keys directly. Call `catalogKeys()` on a nested subtree to get exactly the keys in that group: no filtering, no casts.\n\n```ts\nimport { catalogKeys } from '@vielzeug/lingua';\n\nconst messages = {\n nav: { home: 'Home', settings: 'Settings' },\n} as const;\n\nconst allKeys = catalogKeys(messages);\n// ['nav.home', 'nav.settings']\n\nconst navKeys = catalogKeys(messages.nav);\n// ['home', 'settings']\n```\n\n## Use a Fixed-Locale Translator\n\nUse `createTranslator()` when one catalog and locale stay fixed for the translator's lifetime. It defaults locale to `en`; pass `locale` when plural rules or diagnostics need another locale. Lingua snapshots catalog messages during construction. Do not mutate source catalog objects afterward.\n\n```ts\nimport { createTranslator } from '@vielzeug/lingua';\n\nconst translator = createTranslator({ save: 'Enregistrer' }, { locale: 'fr' });\n\nconsole.log(translator.translate('save'));\n```\n\n## Load Catalogs and Switch Locales\n\nProvide eager catalogs for translations needed immediately and a `loadCatalog` function for other locales. `setLocale()` loads the selected locale and configured fallbacks before it commits the change.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { navigation: { settings: 'Settings' } } },\n fallback: 'en',\n locale: 'en',\n loadCatalog: (locale) => import(`./locales/${locale}.ts`).then((m) => m.default),\n});\n\nawait i18n.setLocale('fr');\nconsole.log(i18n.translate('navigation.settings'));\n```\n\nUse loader-only configuration when every locale is lazy, and call `load()` before the first translation. Concurrent loads for the same locale share work. A failed or superseded locale selection never changes the active locale.\n\n## Subscribe to Locale Changes\n\nSubscribe when UI state must change with the locale. Every callback receives the newly committed locale; translate through the instance to read current strings.\n\n```ts\nconst unsubscribe = i18n.subscribe(\n (locale) => {\n console.log(locale, i18n.translate('navigation.settings'));\n },\n { immediate: true },\n);\n\nunsubscribe();\n```\n\nPass `{ signal }` when an `AbortController` owns subscription lifetime.\n\n## SSR State\n\nSerialize resolved catalogs on the server and pass them back to `createI18n` on the client together with the serialized locale. `getSnapshot()` returns the current locale and stays referentially stable until the locale changes, so it works directly as a framework store snapshot.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst serverI18n = createI18n({\n catalogs: { en: { title: 'Server title' } },\n locale: 'en',\n});\n\nconst state = serverI18n.serialize();\nconst clientI18n = createI18n({ catalogs: state.catalogs, locale: state.locale });\n\nconsole.log(clientI18n.translate('title'));\nserverI18n.dispose();\nclientI18n.dispose();\n```\n\nThe serialized payload contains raw loaded catalogs and the active locale. It never contains loader functions. Pass an explicit `locale` only when the client should override the serialized locale.\n\n## Validation\n\nImport catalog validation from the dedicated subpath to keep translation state focused.\n\n```ts\nimport { compareCatalogs, validateCatalog } from '@vielzeug/lingua/validate';\n\nconst catalog = { inbox: { plural: { one: 'One message', other: '{count} messages' } } };\n\nconsole.log(validateCatalog(catalog, 'en'));\n```\n\nUse `compareCatalogs()` to catch missing or extra keys across locales: the most common i18n defect. First locale is the base.\n\n```ts\nimport { compareCatalogs } from '@vielzeug/lingua/validate';\n\nconst result = compareCatalogs({\n en: { greeting: 'Hello', farewell: 'Goodbye' },\n de: { greeting: 'Hallo' },\n});\n// { missing: [{ key: 'farewell', locale: 'de' }], extra: [] }\n```\n\n## Framework Integration\n\n`getSnapshot()` and `subscribe()` match external-store primitives directly: the snapshot is the locale string, referentially stable until the locale changes.\n\n::: code-group\n\n```ts [React]\nimport { useSyncExternalStore } from 'react';\n\nimport type { I18n } from '@vielzeug/lingua';\n\nexport function useLocale(i18n: I18n) {\n return useSyncExternalStore((onChange) => i18n.subscribe(onChange), i18n.getSnapshot, i18n.getSnapshot);\n}\n```\n\n```ts [Vue 3]\nimport { readonly, shallowRef } from 'vue';\n\nimport type { I18n } from '@vielzeug/lingua';\n\nexport function useLocale(i18n: I18n) {\n const locale = shallowRef(i18n.getSnapshot());\n\n i18n.subscribe((next) => {\n locale.value = next;\n });\n\n return readonly(locale);\n}\n```\n\n```ts [Svelte]\nimport { readable } from 'svelte/store';\n\nimport type { I18n } from '@vielzeug/lingua';\n\nexport function localeStore(i18n: I18n) {\n return readable(i18n.getSnapshot(), (set) => i18n.subscribe(set));\n}\n```\n\n:::\n\n## Rich Content\n\n`parts()` resolves a message like `translate()` — same plural selection, fallback, and `missing` strategy — but returns render-order segments so framework nodes can enter a sentence without being stringified. Values pass through untouched; joining the segments with `String()` reproduces `translate()` exactly.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { sync: 'Click {link} to sync now.' } },\n locale: 'en',\n});\n\nconsole.log(i18n.parts('sync', { values: { link: 'here' } }));\n// [ { type: 'text', value: 'Click ' }, { type: 'value', name: 'link', value: 'here' }, { type: 'text', value: ' to sync now.' } ]\n```\n\nIn React, mirror the locale with `useSyncExternalStore` and key memoized translations on the **locale snapshot** — `i18n.translate`/`i18n.parts` keep a stable identity across `setLocale()` on purpose, so `[t]`-style dependency arrays keep the previous language:\n\n```tsx\nimport { Fragment, useMemo, useSyncExternalStore } from 'react';\nimport type { ReactNode } from 'react';\n\nimport type { Catalog, I18n, TextKey } from '@vielzeug/lingua';\n\nexport function useI18n<C extends Catalog>(i18n: I18n<C>) {\n const locale = useSyncExternalStore((onChange) => i18n.subscribe(onChange), i18n.getSnapshot, i18n.getSnapshot);\n\n // The fresh memo per locale gives `t` a locale-keyed identity, so downstream `[t]` memos recompute correctly.\n return useMemo(\n () => ({\n locale,\n t: i18n.translate.bind(i18n),\n rich: (key: TextKey<C>, values: Record<string, ReactNode>) =>\n i18n.parts<ReactNode>(key, { values }).map((segment, index) =>\n segment.type === 'text'\n ? segment.value\n : <Fragment key={`${segment.name}-${index}`}>{segment.value}</Fragment>,\n ),\n }),\n [locale],\n );\n}\n\n// <p>{t('sync')}</p>\n// <p>{rich('sync', { link: <Link href=\"/sync\">here</Link> })}</p>\n```\n\nThe same segment shape maps directly onto `h()` vnodes in Vue or `{#each}` blocks in Svelte — only the value-segment wrapper is framework-specific. Because values never enter the concatenated string, rich rendering via `parts` also keeps user data out of any HTML-interpolation sink that marker-and-split workarounds would expose.\n\n## Working with Other Vielzeug Libraries\n\nBridge Lingua's `getSnapshot()`/`subscribe()` pair directly when templates need reactive locale reads.\n\n```ts\nimport { createRipple } from '@vielzeug/ripple';\n\nconst ripple = createRipple();\nconst i18nState = ripple.fromSubscribable(i18n);\nexport const locale = ripple.computed(() => i18nState.value);\n\nexport const disposeLocaleBridge = () => ripple.dispose();\n```\n\nUse Courier loaders when locale catalogs come from HTTP rather than bundled modules; pass each loader to `loadCatalog`.\n\n## Best Practices\n\n- Define plural messages with `{ plural: ... }` and no sibling metadata.\n- Keep arrays and application metadata outside catalogs.\n- Treat source catalog objects as immutable after construction.\n- Provide eager catalogs for translations required during initial render.\n- Keep loader functions out of SSR payloads.\n- Dispose temporary instances after requests, tests, and route lifetimes.\n- Use `missing: 'throw'` in development to catch missing keys and values early.\n- Memoize derived translations on the `getSnapshot()` locale string, never on `translate` or `parts` function identity.\n- Render rich messages with `parts()` instead of smuggling markers through `translate()`.\n",
|
|
5
|
+
"api": "---\ntitle: 'Lingua: API Reference'\ndescription: Complete API reference for @vielzeug/lingua.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ---------------------- | ------------------------------------------------------------ | -------------- | ------------------------------------------------------------------------------------------- |\n| `createTranslator()` | Compile one immutable locale catalog | Sync | No fallback locales |\n| `createI18n()` | Create mutable locale and catalog store | Sync | Provide eager catalogs, a loader, or both |\n| `createFormatter()` | Create a cached Intl facade from `/format` | Sync | Pass a locale getter for dynamic locale changes |\n| `createReactiveI18n()` | Mirror an i18n instance into ripple readables from `/ripple` | Sync | Optional `@vielzeug/ripple` peer; import from subpath |\n| `catalogKeys()` | Enumerate message keys as dotted paths | Sync | Takes a catalog (or subtree) only; for an i18n instance pass `state.catalogs[state.locale]` |\n| `validateCatalog()` | Check explicit plural forms from `/validate` | Sync | Import from subpath |\n| `compareCatalogs()` | Compare key parity across locales from `/validate` | Sync | First locale is the base; import from subpath |\n| `LinguaError` | Base class for Lingua errors | Sync | Use `instanceof LinguaError` for broad narrowing |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --------------------------- | ------------------------------------------------------------------------------------------- |\n| `@vielzeug/lingua` | Translation factories, state types, and Lingua errors |\n| `@vielzeug/lingua/format` | Standalone cached Intl formatter factory |\n| `@vielzeug/lingua/ripple` | `createReactiveI18n()`: reactive locale/translate bridge (optional `@vielzeug/ripple` peer) |\n| `@vielzeug/lingua/validate` | `validateCatalog()`, `compareCatalogs()`, and `ValidationIssue` |\n\n## Translation Factories\n\n### createTranslator\n\n```ts\nfunction createTranslator<C extends Catalog>(catalog: C, options?: TranslatorOptions): Translator<C>;\n```\n\nCompiles one catalog and returns an immutable fixed-locale translator. Locale defaults to `en` and controls plural selection and diagnostics.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | --------------------------------------------------------- |\n| `catalog` | `C` | One catalog containing only messages and grouping objects |\n| `options` | `TranslatorOptions` | Locale and missing-message strategy |\n\n**Returns:** `Translator<C>`.\n\n**Example:**\n\n```ts\nimport { createTranslator } from '@vielzeug/lingua';\n\nconst translator = createTranslator({ save: 'Enregistrer' }, { locale: 'fr' });\n\ntranslator.translate('save');\n```\n\n| Method | Signature | Returns |\n| ------------------ | ----------------------------------------------------------------------- | --------------------------- |\n| `translate` | `(textKey, options?)` or `(pluralKey, { count, ordinal?, values? })` | Rendered string |\n| `translateUnkeyed` | `(key: string, options?)` | Rendered string |\n| `parts` | `(textKey, { values? })` or `(pluralKey, { count, ordinal?, values? })` | Render-order `Segment<V>[]` |\n| `partsUnkeyed` | `(key: string, options?)` | Render-order `Segment<V>[]` |\n| `locale` | `Locale` | Resolved active locale |\n\n---\n\n### createI18n\n\n```ts\nfunction createI18n<C extends Catalog>(options: I18nOptions<C>): I18n<C>;\n```\n\nCreates the catalog store, current locale state, and the active translator.\n\n| Parameter | Type | Description |\n| --------------------- | ----------------------------- | ------------------------------------------------ |\n| `options.catalogs` | `Catalogs<C>` | Eager locale catalogs |\n| `options.locale` | `Locale` | Initial locale; defaults to `en` |\n| `options.loadCatalog` | `(locale) => Promise<C> \\| C` | Loader for catalogs not supplied eagerly |\n| `options.fallback` | `Locale \\| readonly Locale[]` | Fallback locales loaded with the selected locale |\n| `options.missing` | `MissingStrategy` | Missing-key/value strategy |\n\nProvide at least one of `catalogs` or `loadCatalog`; you may combine eager `catalogs` with `loadCatalog` for later locales.\n\n**Returns:** `I18n<C>`, with every `Translator<C>` method plus lifecycle methods.\n\n**Example:**\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { title: 'Home' } },\n locale: 'en',\n});\ni18n.translate('title');\n```\n\n| Method or property | Signature | Returns |\n| ------------------ | ------------------------------------- | -------------------------------------------------------------- |\n| `translate` | Translator method | Rendered string |\n| `translateUnkeyed` | Translator method | Rendered string for a runtime key outside the typed key set |\n| `parts` | Translator method | Render-order `Segment<V>[]` for the committed locale |\n| `partsUnkeyed` | Translator method | Render-order `Segment<V>[]` for a runtime key |\n| `load` | `({ locale? })` | `Promise<void>` after the locale and configured fallbacks load |\n| `setLocale` | `(locale)` | `Promise<void>` after an atomic loaded-locale commit |\n| `isLoaded` | `({ locale? })` | `boolean` |\n| `getSnapshot` | `()` | Current locale, referentially stable until it changes |\n| `subscribe` | `(listener, { immediate?, signal? })` | Unsubscribe function; listener receives the new locale |\n| `serialize` | `()` | Loader-free `SerializedI18n<C>` for SSR transfer |\n| `dispose` | `()` | `void` |\n| `locale` | `Locale` | Current canonical locale |\n| `disposed` | `boolean` | Disposal state |\n| `disposalSignal` | `AbortSignal` | Aborts on disposal |\n| `[Symbol.dispose]` | `()` | Delegates to `dispose()` |\n\n**Memoization rule:** `translate` and `parts` have a deliberately stable function identity across `setLocale()` — they read the committed engine at call time, while `getSnapshot()` returns the locale string whose identity changes exactly when the locale does. Memoize derived translations on the **locale**, never on the function's identity (`useMemo(..., [i18n.translate])` keeps the previous language).\n\n---\n\n## Rich content (`parts`)\n\n`parts()` resolves a message exactly like `translate()` — same plural selection, locale fallback, and `missing` strategy — but returns the message as render-order segments, so framework nodes can enter a sentence without ever being stringified.\n\n```ts\nconst segments = i18n.parts('link', { values: { label: <Link href=\"/sync\">Sync</Link> } });\n// [ { type: 'text', value: 'Go to ' }, { type: 'value', name: 'label', value: <Link/> }, { type: 'text', value: ' now.' } ]\n```\n\n| Contract | Behavior |\n| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Order | Segments are in render order; a value used twice produces two value segments; unreferenced values are ignored |\n| Text | Text segments are never empty — adjacent placeholders yield adjacent value segments |\n| Values | Passed through untouched with identity preserved; never `String()`-ified, escaped, or merged with neighbors |\n| Missing value | Becomes a **text** segment holding the `missing` strategy's output (`null`/`undefined` count as missing; `''` is a real value) |\n| Missing key | One text segment holding the strategy's output; `'throw'` still throws |\n| Plural | `parts(key, { count, ordinal?, values? })`; `count` is interpolated into the selected form and can be overridden by an explicit `count` in `values` |\n| Equivalence | Joining segments with `String()` reproduces `translate()` exactly, so `parts` is safe as your single resolution path |\n\nThe interpolation contract shared by `translate()` and `parts()`: string values are inserted verbatim (no HTML or entity escaping), non-string values are `String(value)`-ified, and nullish values follow the `missing` strategy. Rich UIs should render `parts` segments instead of smuggling placeholders through a translated string: because values never enter the concatenated string, user data cannot reach an HTML sink through it.\n\n`V` defaults to `string`; pass your node type to keep rendering type-safe: `i18n.parts<ReactNode>('link', { values: { label: <Link/> } })`.\n\n---\n\n## Reactive bridge (`@vielzeug/lingua/ripple`)\n\n### createReactiveI18n\n\n```ts\nfunction createReactiveI18n<C extends Catalog>(i18n: I18n<C>): ReactiveI18n<C>;\n```\n\nBridges a lingua instance into `@vielzeug/ripple` so translated strings are reactive. `i18n.translate()` is not ripple-reactive on its own: reading it inside a `computed()` computes once and never re-runs, since it registers no tracked dependency. The bridge's `translate`, `translateUnkeyed`, `parts`, and `partsUnkeyed` 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`/`partsUnkeyed`: calling `i18n.translateUnkeyed` directly skips the reactive locale and caches the first result.\n\n`@vielzeug/ripple` is an optional peer dependency: install it only when you use this subpath.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\nimport { createReactiveI18n } from '@vielzeug/lingua/ripple';\nimport { computed } from '@vielzeug/ripple';\n\nconst reactive = createReactiveI18n(createI18n({ catalogs, locale: 'en' }));\n\nconst heading = computed(() => reactive.translate('title')); // re-computes on setLocale()\nawait reactive.i18n.setLocale('fr');\n```\n\n| Property or method | Signature | Returns |\n| ------------------ | ------------------ | ------------------------------------------------------------------------------- |\n| `i18n` | `I18n<C>` | The underlying instance for imperative work (`setLocale`, `load`, disposal) |\n| `locale` | `Readable<Locale>` | Reactive locale: reading it inside a computed/template registers the dependency |\n| `translate` | `(key, options?)` | Rendered string; re-evaluates whenever the locale changes |\n| `translateUnkeyed` | `(key, options?)` | Rendered string for a runtime key; re-evaluates whenever the locale changes |\n| `parts` | `(key, options?)` | Render-order `Segment<V>[]`; re-evaluates whenever the locale changes |\n| `partsUnkeyed` | `(key, options?)` | `Segment<V>[]` for a runtime key; re-evaluates whenever the locale changes |\n\n---\n\n## Catalog Utilities\n\n### catalogKeys\n\n```ts\nfunction catalogKeys<C extends Catalog>(catalog: C): ReadonlyArray<MessageKey<C>>;\n```\n\nEnumerates every message key as a dotted path. Traverses nested grouping objects and explicit `{ plural: ... }` messages, producing the same paths that `TextKey<C>` represents at the type level. Pass any catalog object or subtree; for an `I18n` instance, read its current locale catalog first.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | ----------------------------------------- |\n| `catalog` | `C extends Catalog` | Raw catalog object or any catalog subtree |\n\n**Returns:** `ReadonlyArray<MessageKey<C>>`: dotted paths to every text and plural message.\n\n```ts\nimport { catalogKeys, createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { nav: { home: 'Home', settings: 'Settings' } } },\n locale: 'en',\n});\n\nconst state = i18n.serialize();\nconst allKeys = catalogKeys(state.catalogs[state.locale]); // ['nav.home', 'nav.settings']\nconst navKeys = catalogKeys(state.catalogs.en.nav); // ['home', 'settings']\n```\n\n---\n\n## Intl formatting\n\n### createFormatter\n\n```ts\nimport { createFormatter } from '@vielzeug/lingua/format';\n\nconst format = createFormatter(() => i18n.locale);\nformat.number(1_234.5);\nformat.currency(19.99, 'USD');\nformat.date(new Date(), { dateStyle: 'medium' });\n```\n\nThe formatter caches bounded `Intl` instances and resolves a locale getter for every call.\n\n## Validation\n\n### validateCatalog\n\n```ts\nfunction validateCatalog(catalog: Catalog, locale: Locale): ValidationIssue[];\n```\n\nValidates explicit plural messages against locale plural categories after catalog structural validation.\n\n| Parameter | Type | Description |\n| --------- | --------- | ---------------------------- |\n| `catalog` | `Catalog` | Explicit catalog to validate |\n| `locale` | `Locale` | BCP 47 locale tag |\n\n**Returns:** `ValidationIssue[]`.\n\n**Example:**\n\n```ts\nimport { validateCatalog } from '@vielzeug/lingua/validate';\n\nvalidateCatalog({ inbox: { plural: { one: 'One message' } } }, 'en');\n```\n\n### compareCatalogs\n\n```ts\nfunction compareCatalogs<C extends Catalog>(catalogs: Catalogs<C>): CatalogComparison;\n```\n\nCompares key sets across locales. First locale is the base: reports keys missing in each target and keys present in targets but absent from base. Validates each catalog structurally.\n\n| Parameter | Type | Description |\n| ---------- | ------------- | -------------------------------- |\n| `catalogs` | `Catalogs<C>` | Locale-keyed catalogs to compare |\n\n**Returns:** `CatalogComparison` with `missing` and `extra` arrays.\n\n```ts\nimport { compareCatalogs } from '@vielzeug/lingua/validate';\n\nconst result = compareCatalogs({\n en: { greeting: 'Hello', farewell: 'Goodbye' },\n de: { greeting: 'Hallo' },\n});\n// { missing: [{ key: 'farewell', locale: 'de' }], extra: [] }\n```\n\n## Types\n\n```ts\ntype Locale = string;\ntype PluralCategory = Intl.LDMLPluralRule;\ntype PluralMessage = { readonly plural: Partial<Record<PluralCategory, string>> };\ntype CatalogNode = Catalog | PluralMessage | string;\ntype Catalog = { readonly [key: string]: CatalogNode };\ntype Catalogs<C extends Catalog = Catalog> = Record<Locale, C>;\n\ntype MissingInfo = { readonly key: string; readonly locale: Locale; readonly name?: string };\ntype MissingHandler = (info: MissingInfo) => string;\ntype MissingStrategy = 'throw' | 'key' | MissingHandler;\n\ntype TranslatorOptions = { readonly locale?: Locale; readonly missing?: MissingStrategy };\n\ntype I18nOptions<C extends Catalog = Catalog> = {\n readonly fallback?: Locale | readonly Locale[];\n readonly locale?: Locale;\n readonly missing?: MissingStrategy;\n} & (\n | { readonly catalogs: Catalogs<C>; readonly loadCatalog?: CatalogLoader<C> }\n | { readonly catalogs?: Catalogs<C>; readonly loadCatalog: CatalogLoader<C> }\n);\n\ntype CatalogLoader<C extends Catalog> = (locale: Locale) => Promise<C> | C;\n\ntype SerializedI18n<C extends Catalog = Catalog> = {\n readonly catalogs: Catalogs<C>;\n readonly locale: Locale;\n};\n\ntype I18n<C extends Catalog = Catalog> = Translator<C> & {\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n getSnapshot(): Locale;\n isLoaded(options?: { locale?: Locale }): boolean;\n load(options?: { locale?: Locale }): Promise<void>;\n serialize(): SerializedI18n<C>;\n setLocale(locale: Locale): Promise<void>;\n subscribe(listener: (locale: Locale) => void, options?: SubscribeOptions): () => void;\n [Symbol.dispose](): void;\n};\n\ntype Translator<C extends Catalog = Catalog> = {\n readonly locale: Locale;\n translate(key: TextKey<C>, options?: TranslateOptions): string;\n translate(key: PluralKey<C>, options: PluralOptions): string;\n translateUnkeyed(key: string, options?: TranslateOptions | PluralOptions): string;\n parts<V = string>(key: TextKey<C>, options?: PartsOptions<V>): readonly Segment<V>[];\n parts<V = string>(key: PluralKey<C>, options: PluralPartsOptions<V>): readonly Segment<V>[];\n partsUnkeyed<V = string>(key: string, options?: PartsOptions<V> | PluralPartsOptions<V>): readonly Segment<V>[];\n};\n```\n\n```ts\ntype Values = Record<string, unknown>;\ntype TranslateOptions = { values?: Values };\ntype PluralOptions = TranslateOptions & { count: number; ordinal?: boolean };\ntype SubscribeOptions = { immediate?: boolean; signal?: AbortSignal };\n\ntype Segment<V = string> =\n | { readonly type: 'text'; readonly value: string }\n | { readonly type: 'value'; readonly name: string; readonly value: V };\ntype PartsOptions<V = string> = { values?: Record<string, V> };\ntype PluralPartsOptions<V = string> = PartsOptions<V> & { count: number; ordinal?: boolean };\n\ntype CatalogPaths<\n C,\n Leaf,\n Prefix extends string = '',\n Depth extends readonly unknown[] = readonly [1, 1, 1, 1, 1, 1],\n> = Depth extends readonly [unknown, ...infer Rest]\n ? C extends Leaf\n ? Prefix\n : C extends PluralMessage\n ? never\n : C extends Catalog\n ? {\n [K in string & keyof C]: CatalogPaths<C[K], Leaf, Prefix extends '' ? K : `${Prefix}.${K}`, Rest>;\n }[string & keyof C]\n : never\n : never;\n\ntype MessageKey<C> = CatalogPaths<C, string | PluralMessage>;\ntype TextKey<C> = CatalogPaths<C, string>;\ntype PluralKey<C> = CatalogPaths<C, PluralMessage>;\n\ntype ValidationIssue = { key: string; locale: Locale; missing: Intl.LDMLPluralRule };\ntype CatalogComparison = {\n readonly missing: ReadonlyArray<{ key: string; locale: Locale }>;\n readonly extra: ReadonlyArray<{ key: string; locale: Locale }>;\n};\n```\n\n## Errors\n\n| Error | Trigger |\n| ------------------------------- | ------------------------------------------------------- |\n| `LinguaDisposedError` | State mutation or subscription after `dispose()` |\n| `LinguaInvalidCatalogError` | Invalid catalog node or reserved key |\n| `LinguaInvalidLocaleError` | Invalid BCP 47 locale tag |\n| `LinguaInvalidPluralCountError` | Non-finite plural count |\n| `LinguaMissingCatalogError` | No `loadCatalog` function or catalog source unavailable |\n| `LinguaMissingKeyError` | Missing translation key when `missing: 'throw'` |\n| `LinguaMissingValueError` | Missing interpolation value when `missing: 'throw'` |\n",
|
|
6
|
+
"usage": "---\ntitle: 'Lingua: Usage Guide'\ndescription: Translate explicit catalogs, load lazy locales, and connect locale snapshots to UI state.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate an i18n instance with eager locale catalogs. Strings are text messages; plural messages use `{ plural: ... }`.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: {\n en: {\n greeting: 'Hello, {name}!',\n inbox: { plural: { one: 'One message', other: '{count} messages' } },\n },\n },\n locale: 'en',\n});\n\nconsole.log(i18n.translate('greeting', { values: { name: 'Ada' } }));\nconsole.log(i18n.translate('inbox', { count: 3 }));\n```\n\nCall `dispose()` when the instance belongs to a temporary request, test, or route owner.\n\n## Define Explicit Catalogs\n\nUse nested objects only to group keys. A plural message always has `plural`, so regular objects containing `one` or `other` remain groups.\n\n```ts\nconst catalog = {\n account: {\n greeting: 'Hello, {name}!',\n unread: { plural: { one: 'One unread message', other: '{count} unread messages' } },\n },\n};\n```\n\nUse `{ values }` for text replacements. Pass `count` at top level for plural selection; Lingua injects it into selected template.\n\nCatalogs contain strings, grouping objects, and explicit `{ plural: ... }` messages only. Keep application data outside catalog, then translate display labels while constructing it.\n\n```ts\nimport { createTranslator } from '@vielzeug/lingua';\n\nconst messages = {\n status: { blocked: 'Blocked', done: 'Done', inProgress: 'In progress' },\n};\nconst statusDefinitions = [\n { labelKey: 'status.inProgress', value: 'in-progress' },\n { labelKey: 'status.blocked', value: 'blocked' },\n { labelKey: 'status.done', value: 'done' },\n] as const;\nconst translator = createTranslator(messages, { locale: 'en' });\nconst statusOptions = statusDefinitions.map(({ labelKey, value }) => ({\n label: translator.translate(labelKey),\n value,\n}));\n```\n\n## Missing Keys and Values\n\nMissing keys and values do not silently echo placeholders by default: Lingua warns in development and returns the key or `{name}`. Control failure behaviour with the `missing` option:\n\n| `missing` | Behaviour |\n| --------------------- | --------------------------------------------------------- |\n| `undefined` (default) | Warn in development; return key / `{name}` |\n| `'key'` | Return key / `{name}` silently |\n| `'throw'` | Throw `LinguaMissingKeyError` / `LinguaMissingValueError` |\n| `handler` | Call `({ key, locale, name? }) => string` |\n\n```ts\nconst translator = createTranslator(messages, { locale: 'en', missing: 'throw' });\n```\n\n## Enumerate Catalog Keys\n\nUse `catalogKeys()` to derive key arrays from the catalog itself instead of maintaining a parallel list that can go stale. It traverses nested grouping objects and explicit `{ plural: ... }` messages, returning the same dotted paths that `MessageKey<C>` represents at the type level.\n\nFor an `I18n` instance, read its current locale catalog first.\n\n```ts\nimport { catalogKeys, createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: {\n en: {\n greeting: 'Hello, {name}!',\n inbox: { plural: { one: 'One message', other: '{count} messages' } },\n nav: { home: 'Home', settings: 'Settings' },\n },\n },\n locale: 'en',\n});\n\nconst state = i18n.serialize();\nconst allKeys = catalogKeys(state.catalogs[state.locale]);\n// ['greeting', 'inbox', 'nav.home', 'nav.settings']\n```\n\nPass a raw catalog object to enumerate keys directly. Call `catalogKeys()` on a nested subtree to get exactly the keys in that group: no filtering, no casts.\n\n```ts\nimport { catalogKeys } from '@vielzeug/lingua';\n\nconst messages = {\n nav: { home: 'Home', settings: 'Settings' },\n} as const;\n\nconst allKeys = catalogKeys(messages);\n// ['nav.home', 'nav.settings']\n\nconst navKeys = catalogKeys(messages.nav);\n// ['home', 'settings']\n```\n\n## Use a Fixed-Locale Translator\n\nUse `createTranslator()` when one catalog and locale stay fixed for the translator's lifetime. It defaults locale to `en`; pass `locale` when plural rules or diagnostics need another locale. Lingua snapshots catalog messages during construction. Do not mutate source catalog objects afterward.\n\n```ts\nimport { createTranslator } from '@vielzeug/lingua';\n\nconst translator = createTranslator({ save: 'Enregistrer' }, { locale: 'fr' });\n\nconsole.log(translator.translate('save'));\n```\n\n## Load Catalogs and Switch Locales\n\nProvide eager catalogs for translations needed immediately and a `loadCatalog` function for other locales. `setLocale()` loads the selected locale and configured fallbacks before it commits the change.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { navigation: { settings: 'Settings' } } },\n fallback: 'en',\n locale: 'en',\n loadCatalog: (locale) => import(`./locales/${locale}.ts`).then((m) => m.default),\n});\n\nawait i18n.setLocale('fr');\nconsole.log(i18n.translate('navigation.settings'));\n```\n\nUse loader-only configuration when every locale is lazy, and call `load()` before the first translation. Concurrent loads for the same locale share work. A failed or superseded locale selection never changes the active locale.\n\n## Subscribe to Locale Changes\n\nSubscribe when UI state must change with the locale. Every callback receives the newly committed locale; translate through the instance to read current strings.\n\n```ts\nconst unsubscribe = i18n.subscribe(\n (locale) => {\n console.log(locale, i18n.translate('navigation.settings'));\n },\n { immediate: true },\n);\n\nunsubscribe();\n```\n\nPass `{ signal }` when an `AbortController` owns subscription lifetime.\n\n## SSR State\n\nSerialize resolved catalogs on the server and pass them back to `createI18n` on the client together with the serialized locale. `getSnapshot()` returns the current locale and stays referentially stable until the locale changes, so it works directly as a framework store snapshot.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst serverI18n = createI18n({\n catalogs: { en: { title: 'Server title' } },\n locale: 'en',\n});\n\nconst state = serverI18n.serialize();\nconst clientI18n = createI18n({ catalogs: state.catalogs, locale: state.locale });\n\nconsole.log(clientI18n.translate('title'));\nserverI18n.dispose();\nclientI18n.dispose();\n```\n\nThe serialized payload contains raw loaded catalogs and the active locale. It never contains loader functions. Pass an explicit `locale` only when the client should override the serialized locale.\n\n## Validation\n\nImport catalog validation from the dedicated subpath to keep translation state focused.\n\n```ts\nimport { compareCatalogs, validateCatalog } from '@vielzeug/lingua/validate';\n\nconst catalog = { inbox: { plural: { one: 'One message', other: '{count} messages' } } };\n\nconsole.log(validateCatalog(catalog, 'en'));\n```\n\nUse `compareCatalogs()` to catch missing or extra keys across locales: the most common i18n defect. First locale is the base.\n\n```ts\nimport { compareCatalogs } from '@vielzeug/lingua/validate';\n\nconst result = compareCatalogs({\n en: { greeting: 'Hello', farewell: 'Goodbye' },\n de: { greeting: 'Hallo' },\n});\n// { missing: [{ key: 'farewell', locale: 'de' }], extra: [] }\n```\n\n## Framework Integration\n\n`getSnapshot()` and `subscribe()` match external-store primitives directly: the snapshot is the locale string, referentially stable until the locale changes.\n\n::: code-group\n\n```ts [React]\nimport { useSyncExternalStore } from 'react';\n\nimport type { I18n } from '@vielzeug/lingua';\n\nexport function useLocale(i18n: I18n) {\n return useSyncExternalStore((onChange) => i18n.subscribe(onChange), i18n.getSnapshot, i18n.getSnapshot);\n}\n```\n\n```ts [Vue 3]\nimport { readonly, shallowRef } from 'vue';\n\nimport type { I18n } from '@vielzeug/lingua';\n\nexport function useLocale(i18n: I18n) {\n const locale = shallowRef(i18n.getSnapshot());\n\n i18n.subscribe((next) => {\n locale.value = next;\n });\n\n return readonly(locale);\n}\n```\n\n```ts [Svelte]\nimport { readable } from 'svelte/store';\n\nimport type { I18n } from '@vielzeug/lingua';\n\nexport function localeStore(i18n: I18n) {\n return readable(i18n.getSnapshot(), (set) => i18n.subscribe(set));\n}\n```\n\n:::\n\n## Rich Content\n\n`parts()` resolves a message like `translate()` — same plural selection, fallback, and `missing` strategy — but returns render-order segments so framework nodes can enter a sentence without being stringified. Values pass through untouched; joining the segments with `String()` reproduces `translate()` exactly.\n\n```ts\nimport { createI18n } from '@vielzeug/lingua';\n\nconst i18n = createI18n({\n catalogs: { en: { sync: 'Click {link} to sync now.' } },\n locale: 'en',\n});\n\nconsole.log(i18n.parts('sync', { values: { link: 'here' } }));\n// [ { type: 'text', value: 'Click ' }, { type: 'value', name: 'link', value: 'here' }, { type: 'text', value: ' to sync now.' } ]\n```\n\nIn React, mirror the locale with `useSyncExternalStore` and key memoized translations on the **locale snapshot** — `i18n.translate`/`i18n.parts` keep a stable identity across `setLocale()` on purpose, so `[t]`-style dependency arrays keep the previous language:\n\n```tsx\nimport { Fragment, useMemo, useSyncExternalStore } from 'react';\nimport type { ReactNode } from 'react';\n\nimport type { Catalog, I18n, TextKey } from '@vielzeug/lingua';\n\nexport function useI18n<C extends Catalog>(i18n: I18n<C>) {\n const locale = useSyncExternalStore((onChange) => i18n.subscribe(onChange), i18n.getSnapshot, i18n.getSnapshot);\n\n // The fresh memo per locale gives `t` a locale-keyed identity, so downstream `[t]` memos recompute correctly.\n return useMemo(\n () => ({\n locale,\n t: i18n.translate.bind(i18n),\n rich: (key: TextKey<C>, values: Record<string, ReactNode>) =>\n i18n\n .parts<ReactNode>(key, { values })\n .map((segment, index) =>\n segment.type === 'text' ? (\n segment.value\n ) : (\n <Fragment key={`${segment.name}-${index}`}>{segment.value}</Fragment>\n ),\n ),\n }),\n [locale],\n );\n}\n\n// <p>{t('sync')}</p>\n// <p>{rich('sync', { link: <Link href=\"/sync\">here</Link> })}</p>\n```\n\nThe same segment shape maps directly onto `h()` vnodes in Vue or `{#each}` blocks in Svelte — only the value-segment wrapper is framework-specific. Because values never enter the concatenated string, rich rendering via `parts` also keeps user data out of any HTML-interpolation sink that marker-and-split workarounds would expose.\n\n## Working with Other Vielzeug Libraries\n\nBridge Lingua's `getSnapshot()`/`subscribe()` pair directly when templates need reactive locale reads.\n\n```ts\nimport { createRipple } from '@vielzeug/ripple';\n\nconst ripple = createRipple();\nconst i18nState = ripple.fromSubscribable(i18n);\nexport const locale = ripple.computed(() => i18nState.value);\n\nexport const disposeLocaleBridge = () => ripple.dispose();\n```\n\nUse Courier loaders when locale catalogs come from HTTP rather than bundled modules; pass each loader to `loadCatalog`.\n\n## Best Practices\n\n- Define plural messages with `{ plural: ... }` and no sibling metadata.\n- Keep arrays and application metadata outside catalogs.\n- Treat source catalog objects as immutable after construction.\n- Provide eager catalogs for translations required during initial render.\n- Keep loader functions out of SSR payloads.\n- Dispose temporary instances after requests, tests, and route lifetimes.\n- Use `missing: 'throw'` in development to catch missing keys and values early.\n- Memoize derived translations on the `getSnapshot()` locale string, never on `translate` or `parts` function identity.\n- Render rich messages with `parts()` instead of smuggling markers through `translate()`.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Lingua: Examples'\ndescription: Focused examples for explicit catalogs and locale resources.\n---\n\n- [Static Translator](./examples/static-translator.md)\n- [Lazy Locale Catalog](./examples/feature-resources.md)\n- [SSR Hydration](./examples/ssr-hydration.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|