@vielzeug/codex 26.10.15 → 26.10.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/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # Vielzeug
2
2
 
3
- > 42 focused TypeScript packages. Version: 26.10.14
3
+ > 43 focused TypeScript packages. Version: 26.10.16
4
4
 
5
5
  Install any package independently: `pnpm add @vielzeug/<name>`
6
6
 
@@ -9,6 +9,7 @@ Install any package independently: `pnpm add @vielzeug/<name>`
9
9
  - [@vielzeug/archive](/archive/): Community content publishing for Cloudflare Workers + D1: a hardened Worker core over per-collection payload schemas
10
10
  - [@vielzeug/arsenal](/arsenal/): Tree-shakeable TypeScript utilities with focused category entry points for arrays, async work, caching, objects, strings, math, and guards.
11
11
  - [@vielzeug/assay](/assay/): Scoped DOM queries, exact event dispatch, and cancellable async waiting for browser tests.
12
+ - [@vielzeug/beacon](/beacon/): Guided onboarding and contextual product tours for web applications
12
13
  - [@vielzeug/clockwork](/clockwork/): Framework-neutral typed state machines with pure transitions, actor-owned runtime work, timers, invokes, and explicit effects.
13
14
  - [@vielzeug/codex](/codex/): Local MCP access to Vielzeug documentation and package metadata.
14
15
  - [@vielzeug/coins](/coins/): Exact bigint monetary arithmetic with explicit currency definitions, decimal strings, allocation, exchange, formatting, and JSON boundaries.
@@ -4,5 +4,5 @@
4
4
  "refine": "refine.json",
5
5
  "schemaVersion": 1,
6
6
  "search": "search.json",
7
- "version": "26.10.14"
7
+ "version": "26.10.16"
8
8
  }
@@ -3,7 +3,7 @@
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: [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', 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', 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
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.\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\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| `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/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
- "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.\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.\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\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)\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. Moderation routes additionally require a registered publisher row: one\naccountable 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\npnpm vitest run packages/archive/src/__tests__/ # fast unit suite\npnpm --filter @vielzeug/archive test:integration # real workerd + local D1 + issuer coverage\npnpm --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",
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.\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.\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\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)\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\npnpm vitest run packages/archive/src/__tests__/ # fast unit suite\npnpm --filter @vielzeug/archive test:integration # real workerd + local D1 + issuer coverage\npnpm --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",
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
  },
9
9
  "examples": [],
@@ -0,0 +1,51 @@
1
+ {
2
+ "apiSource": "// Public root surface of @vielzeug/beacon. Every public export goes through this file.\nexport { createCoachmark } from './coachmark';\nexport { BeaconConfigError, BeaconDisposedError, BeaconError } from './errors';\nexport { resolveTarget } from './target';\nexport { createTour } from './tour';\nexport type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';\n",
3
+ "docs": {
4
+ "index": "---\ntitle: 'Beacon: Product tours and coachmarks'\ndescription: \"Guided onboarding and contextual product tours for web applications\"\npackage: beacon\ncategory: ui-interaction\nkeywords: [onboarding, product-tour, coachmark, walkthrough, step-by-step, spotlight, headless]\nrelated: [refine, orbit, ripple, vault]\nexports: [createTour, createCoachmark, resolveTarget]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"beacon\" />\n\n## Why Beacon?\n\nProduct tours rot fast: hand-wired step sequences hard-code positioning, persistence, and target waiting into application code, and break the first time the UI moves. Beacon is the headless half of a tour — it owns step order, target waiting, resumable progress, and events — while your markup (or `@vielzeug/refine`'s `ore-tour` components) decides what a step looks like.\n\n```ts\n// Before: step logic tangled with rendering and storage\nlet step = Number(localStorage.getItem('tour-step') ?? 0);\nfunction showStep() {\n const el = document.querySelector(steps[step].selector);\n card.style.top = `${el.getBoundingClientRect().bottom + 8}px`; // breaks on scroll\n card.innerHTML = steps[step].html;\n}\n\n// After: the engine owns order, persistence, and the anchor rect\nimport { createTour } from '@vielzeug/beacon';\n\nconst tour = createTour({ id: 'welcome', steps, storage });\ntour.current.subscribe(() => renderCard(tour.current.value)); // rect is the live anchor\ntour.start();\n```\n\n| Feature | Beacon | Shepherd.js | Intro.js |\n| --- | --- | --- | --- |\n| Bundle size | <PackageInfo package=\"beacon\" type=\"size\" /> | ~50 kB | ~25 kB |\n| External dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> (none) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Headless (you own the UI) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Resumable persisted progress | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> |\n| Versioned re-offers | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Coachmarks (single hints) | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"triangle-alert\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Beacon when** tours must survive UI changes: steps anchor to your real DOM, progress persists and resumes, and the card markup is yours (or refine's ready-made `ore-tour`).\n\n**Consider Shepherd or Intro.js when** you want a fully-rendered, opinionated tour widget you never style yourself and can accept their DOM and CSS.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/beacon\n```\n\n```sh [npm]\nnpm install @vielzeug/beacon\n```\n\n```sh [yarn]\nyarn add @vielzeug/beacon\n```\n\n:::\n\n## Quick Start\n\nDefine the tour as data, run it, and render the current step wherever you like. The handle is disposable, so component teardown cleans everything up.\n\n```ts\nimport { createTour, type BeaconTourConfig } from '@vielzeug/beacon';\n\nconst config = {\n id: 'getting-started',\n steps: [\n { id: 'welcome', title: 'Welcome', description: 'A two-minute look around.' },\n { id: 'nav', target: '[data-tour=\"nav\"]', title: 'Navigation', placement: 'bottom-start' },\n ],\n} satisfies BeaconTourConfig;\n\nconst tour = createTour(config);\n\n// Render from the live snapshot: rect is the anchor, null centers the card.\nconst unsubscribe = tour.current.subscribe(() => {\n const { presentation, rect, step } = tour.current.value;\n console.log({ presentation, rect, step }); // drive your card from this\n});\n\ntour.start();\n\n// On teardown:\nunsubscribe();\ntour.dispose();\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createTour()` runs a sequential, resumable walkthrough over your own DOM.\n- `createCoachmark()` shows a single contextual hint once per user per version.\n- `current` is a live `Readable<BeaconCurrentStep>` snapshot: step, index, placement, presentation, and resolved anchor rect, kept fresh on scroll, resize, and layout changes.\n- `target` accepts a selector, `Element`, rect, or lazy resolver, and beacon waits for lazily-mounted targets before showing the step.\n- `storage` persists progress through any `BeaconStorage` bridge (localStorage, IndexedDB via `@vielzeug/vault`, a server API).\n- `version` re-offers a finished tour when the product changes underneath it.\n- `tap()` subscribes to lifecycle events (`step:start`, `tour:complete`, `target-missing`, ...) with `AbortSignal` support.\n- `resolveTarget()` turns any target into a viewport rect compatible with `@vielzeug/orbit` positioners.\n- `ore-tour`'s `bind()` in `@vielzeug/refine` renders a handle and routes its actions with zero glue code.\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- [Refine](/refine/): ships `ore-tour` and `ore-spotlight`, the ready-made dialog/popover/bottom-sheet presentation layer for a beacon handle.\n- [Orbit](/orbit/): compute exact popover coordinates from `current.rect` when you build a custom presentation.\n- [Vault](/vault/): durable storage backends that plug into `BeaconStorage` with a six-line bridge.\n- [Ripple](/ripple/): the `Readable` signals every beacon handle exposes come from here.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
5
+ "api": "---\ntitle: 'Beacon: API Reference'\ndescription: Public API of @vielzeug/beacon.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --- | --- | --- | --- |\n| `createTour(config)` | Runs a sequential, resumable walkthrough over the app's DOM | Sync (storage reads may be async) | `start()` is a no-op when the stored record says the tour is completed |\n| `createCoachmark(config)` | Shows a single contextual hint anchored to one target | Sync (storage reads may be async) | `show()` is a no-op after `dismiss()` until `reset()` or a `version` bump |\n| `resolveTarget(target)` | Resolves any target to a viewport-space rect or `null` | Sync | Call it per position update; a scrolled target's rect changes |\n| `BeaconError` | Base class for all beacon-originated errors | — | Catch this to catch any beacon error |\n| `BeaconConfigError` | Invalid tour/coachmark configuration | Thrown at creation | Empty `steps` or duplicate step ids fail at `createTour()` |\n| `BeaconDisposedError` | Handle used after `dispose()` | Thrown on call | `dispose()` is idempotent; later method calls throw |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/beacon` | Complete public Beacon API |\n\n---\n\n## Core Functions\n\n### createTour\n\n```ts\nfunction createTour(config: BeaconTourConfig): BeaconTourHandle\n```\n\nReturns a live handle for one guided tour. Throws `BeaconConfigError` when `id` is empty, `steps` is empty, or step ids are duplicated.\n\nParameters: see [`BeaconTourConfig`](#beacontourconfig).\n\n**Returns:** a [`BeaconTourHandle`](#beacontourhandle) that is also `Disposable`.\n\n**Example:**\n\n```ts\nimport { createTour } from '@vielzeug/beacon';\n\nconst tour = createTour({\n id: 'release-tour',\n steps: [{ id: 'intro', title: 'What changed' }],\n autoStart: true,\n});\n\ntour.status.subscribe(() => console.log(tour.status.value));\n```\n\nHandle methods:\n\n| Member | Behavior |\n| --- | --- |\n| `start()` | Begin or resume the tour. No-op when completed; throws after dispose. |\n| `next()` | Advance; past the last step, finishes the tour. |\n| `back()` | Return to the previous step. No-op on the first step. |\n| `goto(step)` | Jump to a step by index or id. Unknown values warn and no-op. |\n| `pause()` | Stop showing, keep progress so `start()` resumes it. |\n| `skip()` | End from a \"Skip\" control. Persisted as dismissed, reported with reason `'skip'`. |\n| `finish()` | Mark finished and stop showing. |\n| `dismiss()` | End by closing (Escape, backdrop). Persisted as dismissed. |\n| `reset()` | Discard persisted progress; the tour is eligible again. |\n| `tap(handler, options?)` | Observe [`BeaconTourEvent`](#beacontourentype)s; returns an unsubscribe, honors `options.signal`. |\n| `dispose()` / `[Symbol.dispose]()` | Release all listeners and observers. Idempotent. |\nHandle properties:\n\n| Member | Type | Notes |\n| --- | --- | --- |\n| `current` | `Readable<BeaconCurrentStep>` | The snapshot to render; `step` is `null` while closed. Beacon re-publishes the rect on scroll, resize, and target layout changes while a step is active. |\n| `status` | `Readable<BeaconStatus>` | Lifecycle, persisted on every change. |\n| `eligible` | `Readable<boolean>` | Whether the tour should be offered to this user. |\n| `steps` | `readonly BeaconStep[]` | The configured steps, in order. |\n| `id` | `string` | The configured id (also the storage key suffix). |\n| `disposed` | `boolean` | Whether `dispose()` has run. |\n| `disposalSignal` | `AbortSignal` | Aborted on dispose; pass it to your own listeners. |\n\n---\n\n### createCoachmark\n\n```ts\nfunction createCoachmark(config: BeaconCoachmarkConfig): BeaconCoachmarkHandle\n```\n\nReturns a handle for one contextual hint. Throws `BeaconConfigError` when `id` is empty.\n\nParameters: see [`BeaconCoachmarkConfig`](#beaconcoachmarkconfig).\n\n**Returns:** a [`BeaconCoachmarkHandle`](#beaconcoachmarkhandle) that is also `Disposable`.\n\n**Example:**\n\n```ts\nimport { createCoachmark } from '@vielzeug/beacon';\n\nconst hint = createCoachmark({\n id: 'share-hint',\n target: '[data-tour=\"share\"]',\n title: 'Share this board',\n});\n\nhint.show(); // waits for the target to mount if it is not on screen yet\n```\n\nHandle members:\n\n| Member | Behavior |\n| --- | --- |\n| `show()` | Show the hint. No-op once dismissed without a newer version. |\n| `hide()` | Hide without recording it as seen; it can show again. |\n| `dismiss()` | Hide and record as seen permanently (until `reset()`/`version`). |\n| `reset()` | Discard the persisted record; the hint is eligible again. |\n| `tap(handler, options?)` | Observe `coachmark:show`, `coachmark:dismiss`, and common events. |\n| `current` | `Readable<BeaconCurrentStep>` — the hint as a single-step snapshot: `step` is the hint while visible, `null` while hidden. The rect stays live on scroll, resize, and target layout changes. |\n| `eligible` | `Readable<boolean>` — never seen, or superseded by a newer version. |\n\n---\n\n### resolveTarget\n\n```ts\nfunction resolveTarget(target: BeaconTarget): BeaconRect | null\n```\n\nResolves a target to a viewport-space rect, or `null` when it is not available yet. Strings resolve through `document.querySelector`; functions are called and their result normalized.\n\n| Parameter | Type | Description |\n| --- | --- | --- |\n| `target` | `BeaconTarget` | Selector, `Element`, rect, or lazy resolver. |\n\n**Returns:** `BeaconRect | null` — shape-compatible with `getBoundingClientRect()` and `@vielzeug/orbit`'s `Rect`.\n\n**Example:**\n\n```ts\nimport { resolveTarget } from '@vielzeug/beacon';\n\nconst rect = resolveTarget('[data-tour=\"share\"]');\n// Anchor an orbit positioner from a virtual reference:\nconst reference = { getBoundingClientRect: () => resolveTarget('[data-tour=\"share\"]') ?? ZERO_RECT };\n```\n\n---\n\n## Types\n\n### BeaconTourConfig\n\n| Option | Type | Default | Description |\n| --- | --- | --- | --- |\n| `id` | `string` | required | Unique identity; used as the storage key. |\n| `steps` | `readonly BeaconStep[]` | required | Every step, in order. At least one. |\n| `autoScroll` | `boolean` | `true` | Scroll each anchored step's target into view when it activates. |\n| `autoStart` | `boolean` | `false` | Start on the next microtask when eligible. |\n| `placement` | `BeaconPlacement` | `'auto'` | Default placement handed to the presentation layer. |\n| `presentation` | `BeaconPresentation` | `'auto'` | Default presentation handed to the presentation layer. |\n| `scrollOffset` | `number \\| (() => number)` | `0` | Pixels kept clear at the viewport top for a sticky header, read at scroll time. |\n| `storage` | `BeaconStorage` | memory-only | Progress persistence. |\n| `targetTimeoutMs` | `number` | `Infinity` | How long to wait for a step's target before skipping that step. `0` publishes immediately with a `null` rect. |\n| `version` | `number` | `1` | Bump to re-show a finished tour. |\n\n### BeaconCoachmarkConfig\n\n| Option | Type | Default | Description |\n| --- | --- | --- | --- |\n| `id` | `string` | required | Unique identity; used as the storage key. |\n| `target` | `BeaconTarget` | required | Where the hint points. |\n| `autoShow` | `boolean` | `true` | Show automatically when not yet seen. |\n| `data` | `unknown` | — | Free-form data for the presentation layer. |\n| `description` | `string` | — | Supporting copy. |\n| `placement` | `BeaconPlacement` | `'auto'` | Preferred side. |\n| `presentation` | `BeaconPresentation` | `'auto'` | Preferred presentation. |\n| `storage` | `BeaconStorage` | memory-only | Seen-record persistence. |\n| `title` | `string` | — | Headline copy. |\n| `version` | `number` | `1` | Bump to re-show a seen coachmark. |\n\n### BeaconStep\n\n```ts\ninterface BeaconStep {\n readonly data?: unknown;\n readonly description?: string;\n readonly id: string;\n readonly placement?: BeaconPlacement;\n readonly presentation?: BeaconPresentation;\n readonly target?: BeaconTarget;\n readonly title?: string;\n}\n```\n\nOne stop in a tour. `id` is stable and persisted — renaming it resets progress for that step. Omit `target` for a centered intro/outro step. `placement`/`presentation` override the tour-level defaults.\n\n### BeaconTarget\n\n```ts\ntype BeaconTarget = BeaconTargetResolver | BeaconRect | Element | string;\n```\n\nWhat a step points at. Selectors and elements anchor to real DOM; rects (or resolvers returning one) anchor to element-less geometry such as a canvas region.\n\n### BeaconTargetResolver\n\n```ts\ntype BeaconTargetResolver = () => Element | BeaconRect | null;\n```\n\nResolves a target lazily; `null` means \"not available yet\".\n\n### BeaconRect\n\n```ts\ninterface BeaconRect {\n readonly height: number;\n readonly width: number;\n readonly x: number;\n readonly y: number;\n}\n```\n\nA viewport-space rectangle in CSS pixels. Matches `@vielzeug/orbit`'s `Rect` shape.\n\n### BeaconPlacement\n\n```ts\ntype BeaconPlacement =\n | 'auto'\n | 'bottom' | 'bottom-end' | 'bottom-start'\n | 'left' | 'left-end' | 'left-start'\n | 'right' | 'right-end' | 'right-start'\n | 'top' | 'top-end' | 'top-start';\n```\n\nPreferred side for an anchored presentation; `'auto'` asks the positioning layer to choose.\n\n### BeaconPresentation\n\n```ts\ntype BeaconPresentation = 'auto' | 'bottom-sheet' | 'modal' | 'popover';\n```\n\nHow a step should be presented. `'auto'` lets the presentation layer pick by available space.\n\n### BeaconStatus\n\n```ts\ntype BeaconStatus = 'active' | 'completed' | 'dismissed' | 'idle' | 'paused';\n```\n\nTour lifecycle, persisted across visits. `'idle'` means never started.\n\n### BeaconProgress\n\n```ts\ninterface BeaconProgress {\n readonly status: BeaconStatus;\n readonly stepIndex: number;\n readonly version: number;\n}\n```\n\nThe persisted record for one tour or coachmark. `stepIndex` is `-1` before the first step. Records are validated on read; invalid records fall back to a fresh tour.\n\n### BeaconStorage\n\n```ts\ninterface BeaconStorage {\n get(key: string): Promise<BeaconProgress | null | undefined> | BeaconProgress | null | undefined;\n remove(key: string): Promise<unknown> | unknown;\n set(key: string, value: BeaconProgress): Promise<unknown> | unknown;\n}\n```\n\nMinimal storage contract; sync or async. Values are JSON. Keys arrive namespaced (`@vielzeug/beacon:<id>`). A `@vielzeug/vault` store plugs in with:\n\n```ts\nconst storage: BeaconStorage = {\n get: (key) => store.get('progress', key),\n remove: (key) => store.delete('progress', key),\n set: (key, value) => store.put('progress', { id: key, ...value }),\n};\n```\n\n### BeaconCurrentStep\n\n```ts\ninterface BeaconCurrentStep {\n readonly placement: BeaconPlacement;\n readonly presentation: BeaconPresentation;\n readonly rect: BeaconRect | null;\n readonly step: BeaconStep | null;\n readonly stepIndex: number;\n readonly totalSteps: number;\n}\n```\n\nThe snapshot a presentation layer renders from. `step` is `null` before start and after the tour ends; `rect` is `null` for centered steps and unresolved targets. While a step is active, Beacon keeps `rect` fresh on scroll, resize, and target layout changes — no app-side refresh call is needed.\n\n### BeaconTourEvent\n\n```ts\ntype BeaconTourEvent =\n | { readonly index: number; readonly step: BeaconStep; readonly type: 'step:start' }\n | { readonly index: number; readonly step: BeaconStep; readonly type: 'step:complete' }\n | { readonly reason: 'finish' | 'skip'; readonly type: 'tour:complete' }\n | { readonly type: 'tour:dismiss' }\n | { readonly status: BeaconStatus; readonly type: 'status-change' }\n | { readonly message: string; readonly type: 'target-missing' }\n | { readonly index: number; readonly message: string; readonly step: BeaconStep; readonly type: 'target-waiting' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' }\n | { readonly type: 'dispose' };\n```\n\nNotable moments a tour reports through `tap()`. `target-missing` means a step was skipped because its target did not appear in time; `target-waiting` fires when a step begins waiting for its target to mount; `warning` carries storage or handler failures.\n\n### BeaconCoachmarkEvent\n\n```ts\ntype BeaconCoachmarkEvent =\n | { readonly type: 'coachmark:show' }\n | { readonly type: 'coachmark:dismiss' }\n | { readonly type: 'target-waiting' }\n | { readonly error: unknown; readonly message: string; readonly type: 'warning' }\n | { readonly type: 'dispose' };\n```\n\nNotable moments a coachmark reports through `tap()`.\n\n### BeaconTourHandle / BeaconCoachmarkHandle\n\nThe objects returned by `createTour()` and `createCoachmark()`, documented in [Core Functions](#core-functions). Both expose `disposalSignal`, `disposed`, `tap()`, `dispose()`, and `[Symbol.dispose]()`.\n\n## Errors\n\n| Error | Triggered by | Notes |\n| --- | --- | --- |\n| `BeaconError` | Base for all beacon errors | `name` is the subclass name; `cause` supported via `ErrorOptions`. |\n| `BeaconConfigError` | Empty `id`, empty `steps`, missing/duplicate step ids | Thrown synchronously from `createTour()`/`createCoachmark()`. |\n| `BeaconDisposedError` | Calling handle methods after `dispose()` | `dispose()` itself never throws. |\n",
6
+ "usage": "---\ntitle: 'Beacon: Usage Guide'\ndescription: How to use @vielzeug/beacon.\n---\n\n[[toc]]\n\n## Basic Usage\n\nA tour is a config object plus a handle you drive from your own UI. The handle never renders anything: it publishes a `current` snapshot, and your card (or refine's `ore-tour`) renders it.\n\n```ts\nimport { createTour } from '@vielzeug/beacon';\n\nconst tour = createTour({\n id: 'product-tour',\n steps: [\n { id: 'welcome', title: 'Welcome', description: 'See what changed in this release.' },\n { id: 'nav', target: '[data-tour=\"nav\"]', title: 'Find everything', placement: 'bottom-start' },\n { id: 'share', target: '[data-tour=\"share\"]', title: 'Share the board', placement: 'bottom-end' },\n ],\n autoStart: true,\n});\n\n// Readable<T> from @vielzeug/ripple: the listener takes no arguments;\n// read .value inside it.\nconst unsubscribe = tour.current.subscribe(() => {\n const current = tour.current.value;\n if (!current.step) {\n hideCard();\n return;\n }\n renderCard({\n anchor: current.rect, // viewport rect of the target, null for centered steps\n index: current.stepIndex,\n placement: current.placement,\n presentation: current.presentation,\n title: current.step.title,\n total: current.totalSteps,\n });\n});\n\n// Wire your card's controls back to the handle.\ncardEl.addEventListener('next', () => tour.next());\ncardEl.addEventListener('back', () => tour.back());\ncardEl.addEventListener('skip', () => tour.skip());\n\n// On teardown:\nunsubscribe();\ntour.dispose();\n```\n\n`start()` is a no-op when the stored record says this user already completed the tour, so calling it on every page load is safe.\n\n## Steps and Targets\n\nA step without a `target` centers (intro/outro copy). A step with one anchors, and beacon waits for the target to exist before publishing the step — a tour can walk through lazily-mounted routes without any coordination code.\n\n```ts\nconst tour = createTour({\n id: 'deep-tour',\n steps: [\n // Selector: resolved with document.querySelector on activation.\n { id: 'sidebar', target: '[data-tour=\"sidebar\"]', title: 'Your libraries' },\n // Element: a ref your framework already holds.\n { id: 'editor', target: editorEl, title: 'The editor' },\n // Rect: geometry with no element, such as a canvas region.\n { id: 'chart', target: { height: 120, width: 240, x: 400, y: 300 }, title: 'This trend' },\n // Resolver: computed on every activation, and on scroll/resize while the step is active.\n { id: 'selection', target: () => window.getSelection()?.getRangeAt(0).getBoundingClientRect() ?? null, title: 'Your selection' },\n ],\n // Give up waiting after 4s and skip the step instead of hanging the tour.\n targetTimeoutMs: 4000,\n});\n```\n\nWith the default `targetTimeoutMs: Infinity`, a step whose target never mounts simply waits: the tour resumes the moment the user navigates to it. Set `0` to publish immediately with a `null` rect instead of waiting.\n\n## Persisting Progress\n\nWithout `storage`, progress lives in memory for the handle's lifetime only. Any object matching `BeaconStorage` makes it durable — values are JSON, keys are namespaced under `@vielzeug/beacon:`.\n\n```ts\nimport type { BeaconStorage } from '@vielzeug/beacon';\n\nconst storage: BeaconStorage = {\n get: (key) => JSON.parse(localStorage.getItem(key) ?? 'null'),\n remove: (key) => localStorage.removeItem(key),\n set: (key, value) => localStorage.setItem(key, JSON.stringify(value)),\n};\n\nconst tour = createTour({ id: 'product-tour', steps, storage });\n```\n\nAsync storage works too: `get` may return a promise, and the tour boots as soon as it resolves. A `set` that rejects is reported through `tap()` as a `warning` event, never thrown.\n\nRecords are validated on read, so a hand-edited or stale record falls back to a fresh tour instead of crashing.\n\n### Re-offering a finished tour\n\nBump `version` when the product changes and every user who finished the old tour becomes eligible again — users mid-tour on the old version keep their progress.\n\n```ts\nconst tour = createTour({\n id: 'product-tour',\n steps: newSteps,\n version: 2, // stored records at version 1 no longer block the tour\n});\n```\n\n`reset()` clears the persisted record for the current user, which is what a \"Replay tour\" or \"Reset onboarding\" control should call before `start()`.\n\n## Driving a Refine Presentation\n\n`@vielzeug/refine` ships `ore-tour` (a dialog with step footer, progress, and focus handling) and `ore-spotlight` (a decorative cutout that dims everything but the target). A beacon handle satisfies `ore-tour`'s `TourController` shape, so one call wires both directions:\n\n```ts\nimport type { OreTourElement } from '@vielzeug/refine/tour';\n\nconst card = document.querySelector<OreTourElement>('#tour-card');\n\nconst tour = createTour({ id: 'product-tour', presentation: 'auto', steps });\n\n// bind() renders `current` into the card's props and routes the card's\n// next/back/skip/finish/dismiss actions back into the handle.\nconst unbind = card.bind(tour);\n\ntour.start();\n\n// On teardown:\nunbind();\ntour.dispose();\n```\n\n`presentation: 'auto'` maps to a popover on wide viewports and a bottom sheet on narrow ones; ore-tour makes that switch itself and freezes the choice while the card is open, so a mid-step resize never rebuilds the card. Beacon keeps `current.rect` fresh on scroll, resize, and layout changes, so the anchored card follows the layout with no app-side listeners.\n\nApps that render their own markup read `current` directly instead (see [Basic Usage](#basic-usage)).\n\n## Coachmarks\n\nA coachmark is one hint anchored to one target, shown the first time the target appears and dismissed permanently after. Use it for the \"explain this button once\" moment a tour would be too heavy for — or as the follow-up a tour hands off to.\n\n```ts\nimport { createCoachmark } from '@vielzeug/beacon';\n\nconst share = createCoachmark({\n id: 'share-hint',\n target: '[data-tour=\"share\"]',\n title: 'Share this board',\n description: 'Send a link that opens straight into this view.',\n storage,\n});\n\n// Render from `current` — the same single-step snapshot a tour publishes.\nshare.current.subscribe(() => console.log(share.current.value.step !== null, share.current.value.rect));\n\n// The target may never appear on this page; show() waits for it.\nshare.show();\n\n// \"Got it\" button:\nshare.dismiss(); // records it as seen; never shows again for this version\n```\n\n`hide()` closes the hint without recording it, so it can appear again later; `dismiss()` is permanent until `reset()` or a `version` bump.\n\n## Events and Analytics\n\n`tap()` observes everything the engine considers notable. It returns an unsubscribe function and accepts an `AbortSignal`, so one controller can tear down every subscription.\n\n```ts\nconst controller = new AbortController();\n\ntour.tap((event) => {\n switch (event.type) {\n case 'step:start':\n analytics.track('tour_step', { id: tour.id, step: event.step.id });\n break;\n case 'tour:complete':\n analytics.track('tour_complete', { id: tour.id, reason: event.reason });\n break;\n case 'target-missing':\n // A step's target never mounted: your selector drifted from the DOM.\n console.warn(event.message);\n break;\n case 'warning':\n console.warn(event.message, event.error);\n break;\n }\n}, { signal: controller.signal });\n```\n\n`target-missing` is the event to alert on: it means a step was skipped because its target did not appear within `targetTimeoutMs`, which is exactly how stale tours announce themselves.\n\n## Testing\n\nBeacon runs without a rendering layer, so plain DOM tests are enough. The default in-memory storage keeps each handle's progress isolated, and `jsdom`'s `getBoundingClientRect()` returns zero-sized rects, which is fine for step-order assertions.\n\n```ts\nimport { createTour } from '@vielzeug/beacon';\nimport { expect, test } from 'vitest';\n\ntest('walks steps in order and completes', () => {\n const tour = createTour({\n id: 'test-tour',\n steps: [{ id: 'a' }, { id: 'b' }],\n targetTimeoutMs: 0, // publish immediately even without targets\n });\n\n tour.start();\n expect(tour.current.value.step?.id).toBe('a');\n\n tour.next();\n expect(tour.current.value.step?.id).toBe('b');\n\n tour.next(); // past the last step finishes\n expect(tour.status.value).toBe('completed');\n});\n```\n\nFor persistence assertions, pass a `Map`-backed `BeaconStorage` and a second handle with the same `id` to check it resumes where the first stopped.\n\n## Framework Integration\n\nBeacon is framework-neutral: bridge the `Readable` snapshot with whatever primitive your framework already has.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useState } from 'react';\nimport { createTour } from '@vielzeug/beacon';\n\nfunction useTourState(tour: ReturnType<typeof createTour>) {\n const [current, setCurrent] = useState(tour.current.value);\n useEffect(() => tour.current.subscribe(() => setCurrent(tour.current.value)), [tour]);\n return current;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { onScopeDispose, shallowRef } from 'vue';\nimport { createTour } from '@vielzeug/beacon';\n\nconst current = shallowRef(tour.current.value);\nconst unsubscribe = tour.current.subscribe(() => (current.value = tour.current.value));\nonScopeDispose(unsubscribe);\n</script>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onDestroy } from 'svelte';\n import { readable } from 'svelte/store';\n\n const current = readable(tour.current.value, (set) => {\n set(tour.current.value);\n return tour.current.subscribe(() => set(tour.current.value));\n });\n onDestroy(() => tour.dispose());\n</script>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n- **Refine**: `ore-tour` and `ore-spotlight` are the intended presentation layer; see [Driving a Refine Presentation](#driving-a-refine-presentation).\n- **Orbit**: `current.rect` matches orbit's `Rect` shape, so a custom card positions with `computePosition({ getBoundingClientRect: () => current.rect ?? ZERO_RECT }, floatingEl, middleware)`.\n- **Vault**: any vault store becomes a `BeaconStorage` with a six-line bridge (see the `BeaconStorage` docs in [API Reference](./api.md)).\n- **Ripple**: every handle exposes ripple `Readable`s; `createRipple().isBatchingObservable` semantics apply when you subscribe from effects.\n\n## Best Practices\n\n- Give every tour and coachmark a stable `id` — it is the storage key; treat renames as data migrations.\n- Keep tour configs in their own modules as plain data checked with `satisfies BeaconTourConfig`, so steps stay reviewable data, not component code.\n- Prefer `data-tour=\"...\"` attributes as target selectors: they survive class renames and read as intent.\n- Set a finite `targetTimeoutMs` in production and alert on `target-missing` to catch stale selectors.\n- Call `reset()` before `start()` for replay controls; never delete storage keys by hand.\n- Bump `version` when a tour's meaning changes, not when its copy is typo-fixed.\n- Dispose handles on teardown; `tap()` subscriptions with a shared `AbortSignal` clean up in one call.\n",
7
+ "examples": "---\ntitle: 'Beacon: Examples'\ndescription: Practical examples and recipes for @vielzeug/beacon.\n---\n\n## Examples\n\n- [Getting Started](./examples/getting-started.md)\n"
8
+ },
9
+ "examples": [
10
+ {
11
+ "id": "coachmark",
12
+ "code": "import { createCoachmark } from '@vielzeug/beacon'\n\nconst button = document.createElement('button')\nbutton.textContent = 'Share'\nbutton.dataset.tour = 'share'\ndocument.body.appendChild(button)\n\nconst hint = createCoachmark({\n autoShow: false,\n description: 'Send a link that opens straight into this view.',\n id: 'share-hint',\n target: '[data-tour=\"share\"]',\n title: 'Share this board',\n})\n\nhint.tap((event) => console.log('event:', event.type))\n\n// current is the single-step snapshot: step is the hint while visible, null while hidden.\nhint.current.subscribe(() => console.log('visible:', hint.current.value.step !== null))\n\nhint.show()\nconsole.log('rect anchored to button:', JSON.stringify(hint.current.value.rect))\n\n// hide() can come back; dismiss() records it as seen.\nhint.hide()\nhint.show()\nhint.dismiss()\n\n// Once dismissed, show() is a no-op until reset() or a version bump.\nhint.show()\nconsole.log('eligible after dismiss:', hint.eligible.value)\n\nhint.reset()\nconsole.log('eligible after reset:', hint.eligible.value)",
13
+ "name": "Coachmark - Show Once, Dismiss, Reset"
14
+ },
15
+ {
16
+ "id": "persist-progress",
17
+ "code": "import { createTour } from '@vielzeug/beacon'\n\n// Any key-value object is a BeaconStorage; keys arrive namespaced.\nconst db = new Map()\nconst storage = {\n get: (key) => (db.has(key) ? JSON.parse(db.get(key)) : null),\n remove: (key) => db.delete(key),\n set: (key, value) => db.set(key, JSON.stringify(value)),\n}\n\nconst steps = [\n { id: 'a', title: 'First' },\n { id: 'b', title: 'Second' },\n { id: 'c', title: 'Third' },\n]\n\nconst first = createTour({ id: 'resume-demo', steps, storage, targetTimeoutMs: 0 })\nfirst.start()\nfirst.next()\nconsole.log('First session stopped at step index:', first.current.value.stepIndex)\nfirst.pause() // keeps progress so the next handle resumes\n\n// A brand-new handle (next page load) resumes from the stored record.\nconst second = createTour({ id: 'resume-demo', steps, storage, targetTimeoutMs: 0 })\nconsole.log('Resumed status:', second.status.value)\nsecond.start()\nconsole.log('Resumed at step:', second.current.value.step.title)\n\nsecond.finish()\nconsole.log('After finish:', second.status.value)\n\n// start() is a no-op for completed tours:\nsecond.start()\nconsole.log('Still:', second.status.value)\n\n// reset() makes it eligible again (what a \"Replay tour\" button calls):\nsecond.reset()\nsecond.start()\nconsole.log('After reset + start, step:', second.current.value.step.title)",
18
+ "name": "Persist Progress - Resume, Finish, Replay"
19
+ },
20
+ {
21
+ "id": "tour-basics",
22
+ "code": "import { createTour } from '@vielzeug/beacon'\n\n// A tiny stage so the tour has something real to anchor to.\nconst stage = document.createElement('div')\nstage.innerHTML = '<button data-tour=\"nav\" style=\"margin:24px\">Navigation</button><button data-tour=\"share\" style=\"margin:24px\">Share</button>'\ndocument.body.appendChild(stage)\n\nconst tour = createTour({\n autoScroll: false, // jsdom has no real scrolling\n id: 'repl-tour',\n steps: [\n { id: 'welcome', title: 'Welcome' },\n { id: 'nav', target: '[data-tour=\"nav\"]', title: 'Navigation' },\n { id: 'share', target: '[data-tour=\"share\"]', title: 'Share' },\n ],\n targetTimeoutMs: 0,\n})\n\n// Readable<T>: the listener takes no arguments, read .value inside.\ntour.current.subscribe(() => {\n const current = tour.current.value\n if (!current.step) return\n console.log('Step ' + (current.stepIndex + 1) + ' of ' + current.totalSteps + ': ' + current.step.title)\n console.log(' anchor rect:', current.rect === null ? 'null (centered)' : JSON.stringify(current.rect))\n})\n\ntour.tap((event) => {\n if (event.type === 'tour:complete') console.log('Tour complete, reason:', event.reason)\n})\n\ntour.start()\ntour.next()\ntour.next()\ntour.next() // past the last step finishes the tour\n\nconsole.log('status:', tour.status.value)",
23
+ "name": "Tour Basics - Steps, Rects, Completion"
24
+ }
25
+ ],
26
+ "typeSignatures": {
27
+ "createCoachmark": "export { createCoachmark } from './coachmark';",
28
+ "BeaconConfigError": "export { BeaconConfigError, BeaconDisposedError, BeaconError } from './errors';",
29
+ "BeaconDisposedError": "export { BeaconConfigError, BeaconDisposedError, BeaconError } from './errors';",
30
+ "BeaconError": "export { BeaconConfigError, BeaconDisposedError, BeaconError } from './errors';",
31
+ "resolveTarget": "export { resolveTarget } from './target';",
32
+ "createTour": "export { createTour } from './tour';",
33
+ "BeaconBaseEvent": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
34
+ "BeaconCoachmarkConfig": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
35
+ "BeaconCoachmarkEvent": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
36
+ "BeaconCoachmarkHandle": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
37
+ "BeaconCurrentStep": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
38
+ "BeaconPlacement": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
39
+ "BeaconPresentation": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
40
+ "BeaconProgress": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
41
+ "BeaconRect": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
42
+ "BeaconStatus": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
43
+ "BeaconStep": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
44
+ "BeaconStorage": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
45
+ "BeaconTarget": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
46
+ "BeaconTargetResolver": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
47
+ "BeaconTourConfig": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
48
+ "BeaconTourEvent": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';",
49
+ "BeaconTourHandle": "export type {\n BeaconBaseEvent,\n BeaconCoachmarkConfig,\n BeaconCoachmarkEvent,\n BeaconCoachmarkHandle,\n BeaconCurrentStep,\n BeaconPlacement,\n BeaconPresentation,\n BeaconProgress,\n BeaconRect,\n BeaconStatus,\n BeaconStep,\n BeaconStorage,\n BeaconTarget,\n BeaconTargetResolver,\n BeaconTourConfig,\n BeaconTourEvent,\n BeaconTourHandle,\n} from './types';"
50
+ }
51
+ }