@vielzeug/codex 26.10.17 → 26.10.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/catalog.json +44 -44
- package/data/llms-full.txt +29 -6
- package/data/llms.txt +1 -1
- package/data/manifest.json +1 -1
- package/data/packages/archive.json +2 -2
- package/data/packages/ore.json +1 -1
- package/data/search.json +3 -3
- package/package.json +2 -2
package/data/search.json
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
"description": "community content publishing for cloudflare workers + d1: a hardened worker core over per collection payload schemas",
|
|
5
5
|
"docs": {
|
|
6
6
|
"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",
|
|
7
|
-
"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",
|
|
8
|
-
"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
|
+
"api": " \ntitle: 'archive: api reference'\ndescription: 'collection definitions, browser safe wire schemas, worker deployment, and identity issuance.'\n \n\n[[toc]]\n\n## api overview\n\n| symbol | purpose | execution mode | common gotcha |\n| | | | |\n| `definearchivecollection` | compose validation, indexing, identity and wire schemas | sync | invalid content derives to `null`; callback faults throw |\n| `createarchiveworker` | build the catalog worker | sync | collection names must be unique |\n| `createauthworker` | build the passwordless issuer | sync | `auth_archive` is required |\n| `worker.tap`, `issuer.tap` | observe sanitized runtime outcomes | sync | neither core logs by default; observer exceptions are swallowed |\n| `archivederivationerror` | identify a collection implementation/runtime fault | sync | faults become sanitized 500s, not content validation 422s |\n| `archive_limits` | shared application bounds | sync | page bounds do not cap total exports |\n| `archiveerrorresponseschema`, `archiveauthhealthschema` | validate error and issuer health responses | sync | unknown error codes and health states reject |\n| `archiveerror`, `archivedefinitionerror` | public base and invalid definition errors | sync | thrown locally, not transmitted as error objects |\n| `sessioncookievalue` | compose shared session cookie attributes | sync | deployments must choose `secure` from their environment |\n| `iswellformedtext` | check control characters and lone surrogates | sync | does not trim or impose a length bound |\n\n## package entry point\n\n| import | purpose |\n| | |\n| `@vielzeug/archive` | browser safe collections, constants, schemas and errors |\n| `@vielzeug/archive/worker` | catalog factory, issuer signing key/session service binding and event types |\n| `@vielzeug/archive/auth` | issuer factory and binding types |\n\n## collections\n\n### `definearchivecollection`\n\ncreates a frozen collection and its contract; malformed names, versions or vocabularies throw `archivedefinitionerror`.\n\n```ts\nfunction definearchivecollection<\n p extends object,\n const c extends number,\n const f extends string = never,\n const t extends string = never,\n>(definition: archivecollectiondefinition<p, c, f, t>): archivecollection<p, c>;\n```\n\n| parameter | contract |\n| | |\n| `name` | lowercase `[a z0 9 ]{1,32}` |\n| `contentversion` | positive safe integer |\n| `payloadschema` | spell schema whose output is a stable json object |\n| `filters`, `tags` | optional readonly arrays; omitted means empty vocabulary |\n| `canonicalize` | optional pure, idempotent, schema valid normalization |\n| `index` | derive `filter`, `tags` and searchable `title` without mutating the payload |\n\n**returns:** `archivecollection<p, c>`.\n\n**example:** define and derive one collection without worker bindings.\n\n```ts\nimport { definearchivecollection } from '@vielzeug/archive';\nimport { s } from '@vielzeug/spell';\n\nconst recipes = definearchivecollection({\n name: 'recipes',\n contentversion: 1,\n payloadschema: s.object({ name: s.string().min(1).max(32) }),\n index: (payload) => ({ filter: null, tags: [], title: payload.name }),\n});\nconst derived = await recipes.derive({ name: 'rice' });\nif (derived === null) throw new error('invalid recipe');\nconsole.log(derived.contenthash);\n```\n\n| method / property | result |\n| | |\n| `derive(raw)` | `promise<archivederivation \\| null>` |\n| `contract.entry` | public entry schema |\n| `contract.ownedentry`, `ownedentries` | owner view with `clientkey` and `hidden` |\n| `contract.page` | entries and the forward cursor |\n| `contract.publishinput`, `updateinput` | publish and revision guarded update request schemas |\n| `filters`, `tags` | frozen vocabulary snapshots |\n\n`derive` returns `null` for invalid json objects, schema invalid input, invalid titles, too many tags and oversized canonical payloads. unexpected schema, callback or hashing failures throw `archivederivationerror`. non idempotent or schema invalid canonicalization, unstable schema transformations, index mutation and out of vocabulary projections are also derivation faults. routes map `null` to 422 `invalid payload` and faults to a sanitized 500 `internal`.\nschema output that is lossy or no longer json is a derivation fault, not invalid\nsubmitted content. invalid index result shapes also throw.\n\nconst generics preserve the content version literal and infer filter/tag unions from vocabulary arrays without `as const`. `noinfer` prevents `index` from widening those unions; omitted arrays infer `never`, permitting only `filter: null` and empty tags.\n\nobjects serialize with recursively sorted keys; arrays preserve order unless your canonicalizer changes it. sha 256 hashes the core owned `{contentversion, payload}` envelope. stored payloads are canonical by construction, so the emitted entry schemas embed the plain payload schema.\n\n`filter`, tags and searchable title are persisted projections, not computed during reads. changing `index` or its vocabulary does not update stored rows. the active definition and persisted dataset must remain consistent; archive has no projection update or historical schema api.\n\n## worker and maintenance\n\n### `createarchiveworker`\n\nreturns the catalog request/scheduled handler and its observation side channel.\n\n```ts\nfunction createarchiveworker<e extends archiveworkerenv>(\n collections: readonly archivecollection[],\n): archiveworkerhandler<e>;\n```\n\n**returns:** `archiveworkerhandler<e>`; duplicate names throw `archivedefinitionerror` at registration.\n\n**example:** export a deployable worker using the package's structural bindings.\n\n```ts\nimport { definearchivecollection } from '@vielzeug/archive';\nimport { createarchiveworker, type archiveworkerenv } from '@vielzeug/archive/worker';\nimport { s } from '@vielzeug/spell';\n\nconst notes = definearchivecollection({\n name: 'notes',\n contentversion: 1,\n payloadschema: s.object({ title: s.string().min(1).max(128) }),\n index: ({ title }) => ({ title, filter: null, tags: [] }),\n});\nexport default createarchiveworker<archiveworkerenv>([notes]);\n```\n\n| method | contract |\n| | |\n| `fetch(request, env, ctx)` | returns `promise<response>` |\n| `scheduled(controller, env, ctx)` | sweeps expired retry keys and revocation tombstones; emits failures and rethrows |\n| `tap(handler, { signal? }?)` | returns unsubscribe; a pre aborted signal registers nothing |\n\n`auth_issuer_service` is a required `fetch` shaped service binding to the issuer.\nthe catalog fetches signing keys from the configured `jwt_jwks_url` through that\nbinding, not through global `fetch`. the url still selects the issuer's jwks\nroute and must satisfy the environment's transport rules. key requests use get\nwithout a session cookie and do not follow redirects.\nthe catalog verifies the signed jwt locally, then asks the issuer to validate its\ncurrent account session version. jose caches signing keys; the catalog does not\ncache successful issuer session verdicts.\nif the service exchange fails or exceeds its fixed 5000 ms timeout (body decoding\nincluded), the catalog returns `503 auth unavailable`; the timeout does not cancel\nwork already started by the issuer.\n\nonly anonymous entry lists can use the 30 second edge cache. any `cookie` or `authorization` header disables caching, even if invalid or empty. detail, metadata, private and error responses are `no store`. public reads do not verify sessions.\n\n \n\n### `worker.tap`\n\nobserves typed request, scheduled and cache failure events without affecting request behavior.\n\n```ts\ntap(handler: (event: archiveevent) => void, options?: { readonly signal?: abortsignal }): () => void;\n```\n\n**returns:** an unsubscribe function; abort detaches the observer. diagnostics contain categories and trusted configuration field names, never raw errors, sql, subjects, aliases, tokens or urls.\n\n**example:** observe a worker and detach explicitly.\n\n```ts\nimport { createarchiveworker, type archiveworkerenv } from '@vielzeug/archive/worker';\n\nconst worker = createarchiveworker<archiveworkerenv>([]);\nconst stop = worker.tap((event) => console.log(json.stringify(event)));\nstop();\n```\n\n \n\n## identity issuer\n\n### `createauthworker`\n\nreturns the passwordless email issuer with account export and coordinated erasure.\n\n```ts\nfunction createauthworker<e extends authworkerenv>(): authworkerhandler<e>;\n```\n\n**returns:** `authworkerhandler<e>`.\n\n**example:** export an issuer configured through deployment bindings.\n\n```ts\nimport { createauthworker, type authworkerenv } from '@vielzeug/archive/auth';\n\nexport default createauthworker<authworkerenv>();\n```\n\n| method | contract |\n| | |\n| `fetch(request, env, ctx?)` | returns `promise<response>` |\n| `scheduled(controller, env, ctx?)` | removes expired links, closed send windows and unverified unreferenced accounts |\n| `tap(handler, { signal? }?)` | observes typed `authevent`; returns unsubscribe; pre aborted signals are inert |\n\nmagic links expire after 15 minutes and work once. the durable per email budget allows three sends per hour; consumption, expiration and send failure do not refund it. ordinary sessions last at most 30 days. operator sessions use `operator_session_max_age_seconds` (3600 seconds, or 60 minutes). `operator_emails` controls newly minted role claims.\n\nthe issuer global admission budget is durable d1 state in `auth_sign_in_budget`:\n20 requests per 60 second window before account creation or email delivery.\nthis supplements, rather than replaces, the durable per email budget. no external\nrate limiter binding is required for sign in admission; the budgets do not cover\n`post /auth/verify` or `get /auth/session`, which deployments rate limit at the\nedge. edge rules should block rather than challenge `get /auth/session`: clients\ncheck it with a `fetch`, which cannot solve a challenge interstitial. the verify\nget is a browser navigation from the email link, so a challenge is solvable there.\nadmission spends are not refunded after later database or email failures.\nrequest emails are trimmed and lowercased before validation. `sender_address`\nmust already be canonical; `operator_emails` entries are trimmed and lowercased\nbefore validation.\n\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",
|
|
8
|
+
"usage": " \ntitle: 'archive: usage guide'\ndescription: 'define a collection, initialize fresh d1 databases, deploy the workers, and wire your client and observation policy.'\n \n\n[[toc]]\n\n## basic usage\n\na deployment is a collection definition plus one factory call. put the definition in a\nmodule both sides import — the browser needs the composed schemas, the worker needs\nthe collection itself.\n\n```ts\n// recipes collection.ts — the one content contract, shared by both sides.\nimport { definearchivecollection } from '@vielzeug/archive';\nimport { s } from '@vielzeug/spell';\n\nconst payloadschema = s.object({\n cuisine: s.enum(['italian', 'japanese']),\n ingredients: s.array(s.string().trim().min(1).max(64)).min(1).max(20),\n name: s.string().trim().min(1).max(32),\n});\n\nexport const recipescollection = definearchivecollection({\n // ingredient order is not identity: the canonical form sorts, so reordered\n // content hashes identically and updates as a no op.\n canonicalize: (payload) => ({ ...payload, ingredients: [...payload.ingredients].sort() }),\n contentversion: 1,\n filters: ['italian', 'japanese'],\n index: (payload) => ({\n filter: payload.cuisine,\n tags: [payload.ingredients.length <= 5 ? 'quick' : 'involved'],\n title: payload.name,\n }),\n name: 'recipes',\n payloadschema,\n tags: ['quick', 'involved'],\n});\n```\n\nthe worker entry imports the collection and exports the built handler:\n\n```ts\n// backend/src/index.ts — the whole deployment.\nimport { createarchiveworker } from '@vielzeug/archive/worker';\nimport { recipescollection } from './recipes collection';\n\nconst worker = createarchiveworker([recipescollection]);\n\n// one sanitized log line per request: ids, codes and route classes only.\nworker.tap((event) => console.log(json.stringify(event)));\n\nexport default worker;\n```\n\nthe browser imports the same collection for its schemas — never the worker subpath:\n\n```ts\nimport { recipescollection } from './recipes collection';\nimport { archiveidentityschema, publisher_header } from '@vielzeug/archive';\n\nconst response = await fetch('/api/v1/collections/recipes/entries');\nif (!response.ok) throw new error('archive unavailable');\nconst page = recipescollection.contract.page.parse(await response.json());\nconst meresponse = await fetch('/api/v1/me', { credentials: 'same origin' });\nif (!meresponse.ok) throw new error('identity unavailable');\nconst me = archiveidentityschema.parse(await meresponse.json());\nif (me === null) throw new error('register a publisher first');\nconst mineresponse = await fetch('/api/v1/me/publications?collection=recipes', {\n credentials: 'same origin',\n headers: { [publisher_header]: me.id },\n});\nif (!mineresponse.ok) throw new error('own publications unavailable');\nconst owned = recipescollection.contract.ownedentries.parse(await mineresponse.json());\nconsole.log(page.entries, owned.entries);\n```\n\n## the collection contract\n\n`definearchivecollection` is the only place content knowledge lives. the definition is\nvalidated at registration — a bad `name`, `contentversion`, or any vocabulary value\n(well formed text, 1..`vocabchars` chars) throws there, never mid request — and every\nordinary invalid content returns `null` → `422 invalid payload`. collection\nimplementation faults instead throw `archivederivationerror` → sanitized\n`500 internal`:\n\n **parse** — accept stable json objects only; schema outputs must remain json.\n **canonicalize** — optional; a result that leaves the payload schema throws, so a\n broken normalizer can never store invalid content.\n **index** — the returned `filter` must be declared in `filters`, every `tag` in\n `tags` (duplicates collapse), and the `title` is trimmed and bounded\n (`titlechars`, well formed text). a derivation outside the declared vocabulary\n would store a row no list query can reach — it throws instead.\n **size** — the canonical json must fit `payloadbytes`.\n **identity** — the content hash is sha 256 over `{contentversion, payload}`:\n identical content hashes identically, a real edit always re identifies, and the\n core owns the envelope so collections cannot drift it.\n\ndeclare vocabularies with readonly arrays (`['fire', 'ice']`) for automatic\nliteral union inference. const generics retain the version literal and vocabulary\nunions; `noinfer` prevents the index callback from widening them. omitted arrays\nmean empty vocabularies: return `null` for\nthe filter and no tags. object keys are recursively sorted by the core; schema\ntransformations must stabilize and `canonicalize` must be pure and idempotent.\nnon json input returns `null`. unexpected callback, schema or hashing failures,\nunstable transformations, non idempotent canonicalization and index mutation throw\n`archivederivationerror`; its `stage` identifies the failing phase.\nlossy or non json schema output and invalid index result shapes also throw.\n\n`contentversion` participates in content identity. request handling validates\nonly the current collection definition; it does not interpret historical schemas.\narchive provides no content upgrade apis: a new definition never reinterprets\nstored rows.\n\nfilters, tags and searchable titles are persisted data derived at publish/update\ntime. editing `index` or its vocabularies does not recompute existing projections.\nkeep the active definition and dataset consistent. for a development\ndeployment, deliberately reset and reseed a fresh database when you change payload\nor projection semantics; the package does not supply a migration framework.\nresetting destroys existing data. perform it only as an explicit, deliberate\ndevelopment operation, not automatically during startup or deployment.\n\n**payloads carry decisions, not content.** the payload schema should accept\nuser authored choices expressed as ids plus user written text — never the content's\nown copyrighted expression (card text, artwork, rules), never more than the game's\nown identifiers. for games with paid or dlc content this is the whole answer:\nownership resolves on each viewer's device against their own library, the service\nnever learns what anyone owns, and the strict schema is the enforcement seam —\nuse a strict schema that rejects unknown fields, so a collection that only models ids cannot\naccidentally start shipping paid content. for example, published game builds can\nreference cards, equipment and potions by id plus a user written name. the client\nrenders pieces the viewer does not own as unavailable. keep the browser safe\npublication contract in a shared domain module consumed by both the frontend and\nits backend, without importing frontend application code into the worker.\n\n## the worker and its environment\n\n`createarchiveworker(collections)` returns the full handler: anonymous public reads,\ncookie authenticated mutations behind exact origin and request marker guards, local\nrs256/jwks verification followed by an uncached issuer session version check,\nper ip read limits and per subject write limits keyed by peppered hmacs, the\n30 second anonymous cache on public entry lists only, operator moderation, and a\nscheduled expiry sweep for retired publish retry keys and revocation tombstones.\nhealth sits outside the rate limit and session pipelines: probes never burn the\nanonymous read budget or call the issuer.\n\nthe worker reads its environment fail closed — every binding must be present and\nwell formed, or the route answers 503 without naming what is missing:\n\n| variable | meaning |\n| | |\n| `app_env` | `local` or `production` (transport rules and the pepper policy) |\n| `allowed_origins` | exact canonical origins; never wildcards |\n| `jwt_issuer` / `jwt_audience` / `jwt_jwks_url` | exact issuer claim, audience and issuer jwks endpoint url |\n| `auth_issuer_service` | required issuer service binding for signing key retrieval and live session version checks |\n| `likes_enabled` / `publishing_enabled` | feature flags |\n| `rate_limit_key_secret` | hmac pepper. required ≥ 32 chars in production; local may fall back |\n| `db` / `read_limit` / `write_limit` | d1 + rate limit bindings |\n\nboth limiter bindings must run 60 second windows (`simple` limiters:\n`period: 60`): the platform binding does not expose its period at runtime, so the\nworker's 429 `retry after` header is fixed at 60 seconds — a longer window would\nmake the header lie. the read limit keys on `cf connecting ip`, which cloudflare\nsets authoritatively for requests that reach the worker through its network. keep\nthat network path: never front the worker with a proxy that forwards a\nclient supplied header of the same name.\n\ngenerated env types (wrangler's `worker configuration.d.ts`) satisfy the package's\nstructural `archiveworkerenv` — no `@cloudflare/workers types` dependency, no casts.\n\nsigning keys are fetched from `jwt_jwks_url` through `auth_issuer_service`, not\nglobal `fetch`. point the url at the bound issuer's `/api/v1/auth/jwks.json`\nroute; retain the https production or loopback http local configuration rules.\nthis transport supports workers on the same cloudflare zone without a public\nworker to worker fetch. jose caches signing keys, but every private request still\nchecks the current issuer session version. a signing key provider failure is\n`503 auth unavailable`, not a reason to clear the browser's signed in state.\n\n## the auth issuer\n\n`createauthworker()` from `@vielzeug/archive/auth` is the reference passwordless\nidentity issuer a deployment runs beside the catalog worker: one post with an email\nsends a single use magic link, and explicitly confirming it sets the `archive_session`\ncookie. the catalog verifies the jwt locally, then calls the issuer through\n`auth_issuer_service` to check the account's current session version. requests create\npending account rows; explicit link redemption atomically stamps the account's\nsign in time and claims the token. the issuer's d1 schema ships at\n`node_modules/@vielzeug/archive/migrations/auth/`; point the issuer's\n`migrations_dir` there. the catalog's `jwt_issuer` and `jwt_jwks_url` must identify\nthe issuer, and its audience must match the issuer's `audience`.\n\n| variable | meaning |\n| | |\n| `app_name` | the app's display name in magic link email and escaped confirmation page branding |\n| `allowed_origins` | exact origins allowed to trigger unsafe routes (the app origin(s)) |\n| `app_env` | `local` or `production` — production requires https and sets secure cookies |\n| `audience` / `auth_issuer` | the claims every minted session carries; the catalog verifies the same pair |\n| `auth_db` / `auth_email` | the issuer's d1 and send email bindings |\n| `auth_archive` | required service binding to the catalog worker; deletion calls its profile erasure route |\n| `auth_jwt_private_jwk` | the rs256 private key as a jwk json string: a wrangler secret in production |\n| `auth_jwt_previous_public_jwks` | optional retired public rs256 jwks; publish during rotation until old sessions expire |\n| `operator_emails` | comma separated emails whose newly minted sessions carry the operator role |\n| `public_origin` | app origin for links, confirmation post origin checks and client navigation after sign in |\n| `sender_address` | the address magic links come from: a domain onboarded to cloudflare email service |\n\nunder `wrangler dev` the send email binding is simulated — the link prints to the\nissuer's console, so that console is the inbox. demo only alice/bob routes are\ndeployment wrappers, not package apis.\n\nthe issuer first admits sign in requests through its singleton durable\n`auth_sign_in_budget` table: 20 requests per 60 seconds before creating accounts\nor delivering email. no rate limiter binding is required. it then\npermits three sign in emails per email in an hourly durable window.\nthose durable budgets guard `post /auth/sign in` only. `post /auth/verify` and\n`get /auth/session` stay public: tokens are 256 bit, single use and expire in\n15 minutes, so guessing is not the risk — but every request still costs the\nissuer: the verify get renders the confirmation page, the verify post performs a\nd1 token write, and the session check performs an rs256 verification plus an\naccount read for a well formed signed token. put per client ip cloudflare\nrate limit rules (or an equivalent edge control) in front of both routes in\nproduction. prefer a block action: applications check `get /auth/session` with\na `fetch`, and a fetch cannot solve a challenge interstitial, so challenging\nthat route breaks legitimate sign in. the verify get is a browser navigation\nopened from the email link, so a challenge is solvable there if you want one.\nset thresholds with cgnat headroom (shared mobile/office egress ips) and tune\nfrom observed traffic.\nlater database or delivery failures do not refund global admission.\nusing or expiring a link never refunds sends; failed delivery also spends the\nallowance. links expire after 15 minutes. operator sessions expire after 60 minutes\n(3600 seconds), ordinary sessions after at most 30 days. retain retired public keys during\nrotation; the active private key signs every new session. sign in input trims and\nlowercases email before validation. `sender_address` must already be canonical;\n`operator_emails` entries are trimmed and lowercased before validation.\n\nthe scheduled sweep deletes expired links and closed per user send windows, then\npending accounts only when neither a link nor send budget row still references\nthem. failed delivery deletes the unusable token but retains the spent allowance;\nit does not immediately remove the pending account. verified accounts stay until\nexplicit erasure. the singleton admission row remains and resets its window on a\nlater admitted request.\n\nopening `get /auth/verify?token=…` renders a no store confirmation page and does\nnot consume the link or change the session, so email scanners cannot sign in by\nfetching it. a deliberate click sends `post /auth/verify` with json `{ token }`,\nthe request marker and an exact allowed origin or `public_origin`.\nsuccess is 204 with set cookie; the page then navigates to the fixed\n`${public_origin}/signed in` destination. your application must serve that page;\nthe issuer only serves the confirmation endpoint. the redemption update and\naccount sign in stamp are trigger backed and atomic.\nthe page removes the token from the address bar, loads no external assets, and\nsets a restrictive csp and `referrer policy: no referrer`. its inline css and\nscript use a fresh nonce, never `unsafe inline`. the page follows light/dark\npreferences, supports reduced motion, focuses the confirmation action and\nannounces pending, success and recovery states. without javascript it links to\n`${public_origin}/account` as “request a new sign in link” and does not pretend\nto complete sign in.\n\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 rate limit the issuer's public `verify` and `session` routes at the edge; the\n durable budgets cover sign in admission only.\n",
|
|
9
9
|
"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"
|
|
10
10
|
},
|
|
11
11
|
"examples": [],
|
|
@@ -959,7 +959,7 @@
|
|
|
959
959
|
"description": "functional custom element authoring with typed props, reactive templates, lifecycle helpers, and testing utilities.",
|
|
960
960
|
"docs": {
|
|
961
961
|
"index": " \ntitle: 'ore: web component authoring with signals'\ndescription: functional custom element authoring with typed props, reactive templates, lifecycle helpers, and testing utilities.\npackage: ore\ncategory: ui primitives\nkeywords: [web components, custom elements, reactive, templates, signals, lifecycle]\nrelated: [ripple, refine, orbit]\nexports: [define, prop, html, css, ref, createcontext, inject, injectstrict, provide, onmounted, oncleanup, onevent, onelement, onformreset, watcheffect, useemit, useslots, gethost, bind, each, when, classmap, stylemap, live, model, unsafehtml, usefield, createid, oreerror, oreapierror, oreinternalerror, orelifecycleerror, attributebindings, bindoptions, maybereactive]\nenvironments: [browser]\n \n\n<! markdownlint disable md025 md033 md060 >\n\n<packagehero package=\"ore\" />\n\n## why ore?\n\nore keeps custom elements functional and signal driven while giving you direct control over templates, lifecycle hooks, host bindings, and form associated behavior.\n\n```ts\n// before: vanilla custom element boilerplate\nclass mycounter extends htmlelement {\n #count = 0;\n connectedcallback() {\n this.attachshadow({ mode: 'open' });\n this.#render();\n }\n #render() {\n this.shadowroot!.innerhtml = `<button>${this.#count}</button>`;\n this.shadowroot!.queryselector('button')!.onclick = () => {\n this.#count++;\n this.#render();\n };\n }\n}\ncustomelements.define('my counter', mycounter);\n\n// after: ore\nimport { signal } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('my counter', {\n setup() {\n const count = signal(0);\n return html`<button @click=${() => count.value++}>${count}</button>`;\n },\n});\n```\n\n| feature | ore | lit | stencil |\n| | | | |\n| bundle size | <packageinfo package=\"ore\" type=\"size\" /> | ~12 kb | ~60 kb+ toolchain |\n| signal first runtime | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> (separate signals package) | <ore icon name=\"x\" size=\"16\"></ore icon> |\n| functional component setup | <ore icon name=\"check\" size=\"16\"></ore icon> | partial | <ore icon name=\"x\" size=\"16\"></ore icon> |\n| typed prop helpers | <ore icon name=\"check\" size=\"16\"></ore icon> | partial | <ore icon name=\"check\" size=\"16\"></ore icon> |\n| host binding helpers | <ore icon name=\"check\" size=\"16\"></ore icon> | partial | partial |\n| form associated helpers | <ore icon name=\"check\" size=\"16\"></ore icon> | manual | partial |\n| zero dependencies | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"check\" size=\"16\"></ore icon> | <ore icon name=\"x\" size=\"16\"></ore icon> |\n\n<div class=\"decision callout\">\n\n**use ore when** you want typed, signal driven custom elements with minimal runtime overhead and no framework lock in.\n\n**consider lit when** you need a mature ecosystem with wide community adoption and don't need signal based reactivity.\n\n</div>\n\n## installation\n\n::: code group\n\n```sh [pnpm]\npnpm add @vielzeug/ore @vielzeug/ripple\n```\n\n```sh [npm]\nnpm install @vielzeug/ore @vielzeug/ripple\n```\n\n```sh [yarn]\nyarn add @vielzeug/ore @vielzeug/ripple\n```\n\n:::\n\n## quick start\n\n```ts\nimport { computed, signal } from '@vielzeug/ripple';\nimport { bind, css, define, html, onmounted, prop } from '@vielzeug/ore';\n\ndefine('my counter', {\n props: {\n label: prop.string('count'),\n step: prop.number(1),\n },\n styles: [\n css`\n :host {\n display: inline grid;\n gap: 0.5rem;\n }\n `,\n ],\n setup(props) {\n const count = signal(0);\n const doubled = computed(() => count.value * 2);\n\n bind({ class: { 'is positive': () => count.value > 0 } });\n\n onmounted(() => console.log('mounted'));\n\n return html`\n <button @click=${() => (count.value += props.step.value)}>${props.label}: ${count}</button>\n <p>doubled: ${doubled}</p>\n `;\n },\n});\n```\n\n## features\n\n<div class=\"features grid\">\n\n signal first runtime with `signal`, `computed`, `watch`, `batch` from `@vielzeug/ripple`: import them directly\n functional component authoring via `define(tag, { props, setup, styles, formassociated })`\n props via `prop.*` helpers (`prop.string`, `prop.number`, `prop.bool`, `prop.oneof`, `prop.json`, `prop.data`) or raw `propdef` objects\n `setup(props)` takes only props and returns an `htmlresult` directly: `return html\\`...\\``\n lifecycle hooks: `onmounted`, `oncleanup`, `onevent`, `onelement`, `watcheffect`: plain functions imported from `@vielzeug/ore`, called directly from `setup()` or any composable it calls\n directives: `each` (transactional keyed list reconciliation), `classmap`, `stylemap`, `when`, `live`, `model`, `unsafehtml`\n host bindings via `bind({ attr, class, style, on })`: pass `{ target: el }` to bind any off host element\n reactive aria sync via explicit `aria *` keys in `bind({ attr }, { target })`, with automatic cleanup on disconnect\n context via `provide(key, value)` / `inject(key)`; typed emit/slots via `useemit<emits>()` / `useslots<slotnames>()`\n form associated `usefield()` and observer helpers are root exports\n testing utilities (`@vielzeug/ore/testing`): `mount`, `renderhook`, `flush`, `cleanup`\n generic testing utilities (scoped queries, named event dispatchers, and async waits) are exported by `@vielzeug/assay`\n\n</div>\n\n## package entry points\n\n| import | purpose |\n| | |\n| `@vielzeug/ore` | all browser runtime apis: components, directives, `usefield`, and observers |\n| `@vielzeug/ore/testing` | ore specific mounting, lifecycle flushing, hooks, cleanup, and form internals |\n| `@vielzeug/assay` | generic dom events, scoped queries, and async waiting |\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/index.md) for prebuilt accessible components powered by ore.\n [ripple](../ripple/index.md) for reactive state used inside ore components.\n [forge](../forge/index.md) for typed form state that integrates with ore.\n\n</div>\n\n<! markdownlint enable md025 md033 md060 >\n",
|
|
962
|
-
"api": " \ntitle: 'ore: api reference'\ndescription: complete api reference for @vielzeug/ore and @vielzeug/ore/testing.\n \n\n[[toc]]\n\n## api overview\n\nall browser runtime symbols below are imported from `@vielzeug/ore`. lifecycle/context/binding functions (`onmounted`, `oncleanup`, `onevent`, `onelement`, `watcheffect`, `bind`, `provide`, `useemit`, `useslots`, `gethost`) resolve the active component through an implicit \"current component\" context: they work when called synchronously during `setup()`, or from any composable function `setup()` calls (transitively), but throw if called outside that window.\n\n> `watcheffect` is not named `watch`: `@vielzeug/ripple` already exports a `watch(source, callback)` with different semantics (explicit source + old/new value pair), and the two are frequently imported in the same file.\n\n| symbol | purpose | execution mode | common gotcha |\n| | | | |\n| `define()` | create and register a custom element | sync | tag must contain a hyphen; call before first use |\n| `html` | tagged template literal returning htmlresult | sync | expressions must be signals, functions, or primitives |\n| `prop.*` | typed prop helpers (string, bool, number, …) | sync | prop values are signals: read `.value` |\n| `provide()`/`inject()` | context api for parent to descendant sharing | setup only | must be called synchronously during `setup()` |\n| `ref()` | reactive reference to a dom element | sync | value is null until after first mount |\n| `createcontext()` | create a unique typed injection key | sync | context is scoped to the component tree |\n| `each()` | keyed list rendering with dom diffing | sync | duplicate keys report `ore:error`; plain `t[]` is a one time static render |\n| `when()` | conditional branch rendering | sync | getter fn computed disposed on cleanup; static bool skips subscription |\n| `live(signal)` | one way binding that skips stale writes during input | sync | use for controlled inputs alongside a manual `@input` handler |\n| `model(signal)` | two way form control binding (value/checked + write back) | sync | plain `value`/`checked` attribute only; pass `get` to keep numeric signals numeric |\n| `onmounted(fn)` | dom ready callback | setup only | must be called synchronously during `setup()` |\n| `oncleanup(fn)` | register teardown | setup only | called on component disconnect |\n| `onevent(target, …)` | scoped event listener with auto cleanup | setup only | no ops on null target; removed on disconnect |\n| `usefield(options)` | wire signal to form `elementinternals` | setup only | requires `formassociated: true` on the component definition |\n| `onformreset(fn)` | run work when the ancestor `<form>` resets | setup only | fires every reset (not one shot); only for `formassociated: true` components |\n| `useemit<emits>()` | typed `emit()` bound to the current host | setup only | call once per component; returns `dispatchevent`'s boolean (`false` if a listener called `preventdefault()`) |\n| `useslots<slotnames>()`| reactive slot presence/element signals | setup only | safe to call more than once: the underlying registry is created once |\n| `gethost()` | the current component's host element | setup only | prefer a higher level helper (`bind`, …) when one exists |\n\n## package entry points\n\n| import | purpose |\n| | |\n| `@vielzeug/ore` | all browser runtime apis, including directives, fields, and lifecycle helpers |\n| `@vielzeug/ore/testing` | ore specific mounting, lifecycle, hook, cleanup, and form test support |\n| `@vielzeug/assay` | generic dom events, scoped queries, and async waiting |\n\n## core component api\n\n### `define(tag, definition)`\n\n```ts\ndefine<props>(tag: string, definition: componentdefinition<props>): customelementconstructor;\n```\n\nreturns the registered class (for `instanceof` or subclassing); registration itself is the only global side effect.\n\nthe `setup()` function receives only typed prop signals:\n\n```ts\nsetup(props) {\n return html`<div>${props.label}</div>`;\n}\n```\n\neverything else: lifecycle hooks, host bindings, context, slots, emit: is a plain function imported from `@vielzeug/ore`, called directly from `setup()` (or a composable it calls):\n\n```ts\nimport { define, html, onmounted, useemit, useslots } from '@vielzeug/ore';\n\ndefine('my card', {\n setup(_props) {\n const emit = useemit<{ close: undefined }>();\n const slots = useslots<'header' | 'footer'>();\n\n onmounted(() => console.log('mounted'));\n\n // emit() returns dispatchevent's boolean: false if a listener called preventdefault()\n const notcancelled = emit('close');\n\n return html`${when(slots.has('header'), () => html`<slot name=\"header\"></slot>`)}`;\n },\n});\n```\n\n`useemit<emits>()` and `useslots<slotnames>()` are factory hooks: call them once per setup run to get a typed\n`emit`/`slots` bound to the current host. `useslots()` is safe to call more than once within that setup run.\n\n### componentdefinition\n\n```ts\ntype componentdefinition<props> = {\n formassociated?: boolean;\n props?: propsdef<props>;\n setup: (props: inferprops<propsdef<props>>) => htmlresult | null;\n shadow?: partial<shadowrootinit> | false; // false = light dom (no shadow root)\n styles?: (string | cssstylesheet | cssresult)[];\n};\n```\n\n## runtime helpers\n\n`onmounted`, `oncleanup`, `onevent`, `onelement`, and `watcheffect` are plain functions imported from `@vielzeug/ore`. call them directly during `setup()`.\n\n```ts\nimport { html, oncleanup, onevent, onmounted } from '@vielzeug/ore';\n\nsetup(props) {\n onmounted(() => {\n // dom is ready; return a function for mount scoped cleanup\n return () => { /* cleanup on unmount */ };\n });\n\n oncleanup(() => { /* called on disconnect */ });\n\n onevent(window, 'keydown', (e) => { /* auto removed on disconnect */ });\n\n return html`...`;\n}\n```\n\nbecause these resolve the active component through an implicit context (rather than a value threaded through parameters), composable helper functions can call them directly too: no need to pass hooks in as options:\n\n```ts\nimport { oncleanup } from '@vielzeug/ore';\n\nfunction usemyhelper() {\n oncleanup(() => { /* teardown */ });\n}\n\n// in setup:\nsetup(_props) {\n usemyhelper();\n return html`...`;\n}\n```\n\n## props api\n\n| helper | signature | notes |\n| | | |\n| `prop.string(defaultvalue?)` | `propdef<string>` | reflects by default |\n| `prop.bool(defaultvalue?)` | `propdef<boolean>` | any non null attribute value other than `\"false\"` parses as `true`; `\"false\"` or absent attribute is `false` |\n| `prop.number(defaultvalue?)` | `propdef<number>` | returns default (not nan) and warns in dev when attribute is not a valid number |\n| `prop.oneof(allowed, defaultvalue?)` | `propdef<t>` | restricts to a fixed set of string or number members; `parse` falls back to `defaultvalue` (or `undefined` when omitted) for anything outside the set. numeric members match the attribute parsed as a number |\n| `prop.json(defaultvalue)` | `propdef<t>` | json.parse from attribute; `reflect: false` |\n| `prop.data<t>(defaultvalue?)` | `propdef<t>` | js only: never reads/writes an attribute; use for objects, arrays, callbacks, or any non serialisable value |\n\n> **choosing the right prop helper:**\n>\n> **`prop.oneof`**: the honest way to type a union valued prop: the restriction is enforced at runtime (`parse` falls back for anything outside the set), not just in a type parameter a raw attribute value could violate. pass an `as const` array of the allowed string or number members.\n> **`prop.json`**: value can be declared in html (`<my el config='{\"x\":1}'>`); attribute string is `json.parse`d.\n> **`prop.data`**: value is always set from javascript (objects, arrays, callbacks, class instances); the attribute is never read. use this for both data and function props.\n\nwhen you need custom parsing or `reflect: false`, use a raw `propdef` object:\n\n```ts\nprops: {\n items: { default: [], parse: () => [], reflect: false },\n}\n```\n\nuse `prop.data` for props that hold js only values (including callbacks) that cannot be serialised through an html attribute:\n\n```ts\ndefine('data grid', {\n props: {\n getrowkey: prop.data<(row: unknown) => string>(),\n columns: prop.data<datagridcolumn[]>([]),\n onsort: prop.data<(key: string) => void>(),\n },\n setup(props) {\n // set from js: grid.getrowkey = (row) => row.id\n return html`...`;\n },\n});\n```\n\n## template and directives\n\n### `html`\n\ntagged template literal that returns an `htmlresult`. supports text interpolation, ordinary attributes (`attr=`),\nboolean attributes (`?attr=`), explicit property bindings (`.prop=`), events (`@event=` with optional\n`.stop`/`.prevent`/`.once`/`.capture` modifiers), refs (`ref=`), and nested templates.\n\n`.prop=${value}` always writes the element property (never an attribute): the explicit channel for structured\nvalues (arrays, objects, callbacks). prototype polluting names (`__proto__`, `constructor`, `prototype`) are\nrejected at compile time.\n\n`@event.stop`, `.prevent`, `.once`, and `.capture` are shorthand for the matching listener behavior\n(`stoppropagation`/`preventdefault` applied before the handler runs; `once`/`capture` passed as listener\noptions). an unknown modifier throws at compile time.\n\n### `css`\n\ntagged template literal that returns a `cssresult` for use in `styles`.\n\n### directives\n\n| directive | purpose |\n| | |\n| `each(source, key, render, fallback?)` | keyed reactive list; render receives `readable<t>` and `readable<number>`; plain `t[]` is a one time static snapshot |\n| `when(condition, truthy, falsy?)` | conditional rendering |\n| `classmap(record)` | reactive class string from object map |\n| `stylemap(record)` | reactive inline style string from object map |\n| `live(signal)` | one way binding that skips stale writes during active user input; use with `@input` handler |\n| `model(signal, options?)` | two way form control binding: writes the signal to `value`/`checked` and writes user input back on the control's change event |\n| `unsafehtml(value)` | html rendering sink; sanitize untrusted values before calling |\n\n`each()` treats number and string keys as distinct. a reconciliation failure (a duplicate key, or a render function that throws) reports `ore:error` and preserves the last valid list: entries created during the failed pass are rolled back, so the previous list stays exactly on screen.\n\n### `model(signal, options?)`\n\ntwo way binding for a form control: `value=${model(signal)}`. it writes the signal to the control's `value`/`checked` property on every change and writes user input back into the signal on the control's change event (`'change'` for checkboxes, radios, and `<select>`; `'input'` otherwise). this is the complete controlled input loop that the `live()` + manual `@input` handler pair used to require.\n\n```ts\nconst text = signal('');\nconst agree = signal(false);\nconst count = signal(0);\n\nhtml`\n <input value=${model(text)} />\n <input type=\"checkbox\" checked=${model(agree)} />\n <input type=\"number\" value=${model(count, { get: (el) => number(el.value) })} />\n`;\n```\n\n`options` overrides the defaults for non native controls: `event` sets the write back event name and `get` reads the current value out of the element (default `el.checked` for checkboxes/radios, `el.value` otherwise). because a native text input's `value` is always a string, pass a `get` like `(el) => number(el.value)` to keep a numeric signal numeric. `model()` can only drive a plain `value`/`checked` attribute binding; using it on a boolean (`?checked=`) or other attribute throws.\n\n### `unsafehtml`\n\n`unsafehtml()` is an explicit html injection sink. it has no global sanitizer: sanitize untrusted\ncontent before passing it to the directive, so the trust boundary remains at the call site.\n\n```ts\nimport { unsafehtml } from '@vielzeug/ore';\n\nconst safearticle = sanitize(usersuppliedarticle);\n\nreturn html`<article>${unsafehtml(safearticle)}</article>`;\n```\n\n## host bindings\n\n`bind(config, options?)` is a plain function imported from `@vielzeug/ore`:\n\n```ts\nbind({\n attr: { role: 'button', 'aria expanded': () => string(open.value) },\n class: { 'is open': open },\n style: { ' height': () => height.value + 'px' },\n on: { click: handleclick },\n});\n```\n\n`bind()` auto registers cleanup with the component scope: no manual `oncleanup` needed. returns a cleanup function for early teardown.\n\n### off host bindings\n\npass `{ target: el }` as a second argument to bind to any element other than the host:\n\n```ts\nbind(\n { attr: { 'aria expanded': () => string(isopen.value) } },\n { target: triggerel },\n);\n```\n\nevent listener options (`once`, `capture`, `passive`) are also accepted in the second argument. cleanup is auto registered with the component scope when called during setup.\n\n### reactive aria attributes\n\nuse explicit `aria *` keys in `bind({ attr }, { target })`:\n\n```ts\nconst stoparia = bind(\n {\n attr: {\n 'aria controls': panelid,\n 'aria expanded': () => isopen.value,\n 'aria haspopup': 'listbox',\n },\n },\n { target: triggerel },\n);\n```\n\nstatic values are applied once. getters and signals create reactive effects. calling `stoparia()` stops updates. values of `null`, `undefined`, or `false` remove the attribute.\n\n## slots\n\n `slots.has(name?)`: `readable<boolean>`: whether the named (or default) slot has assigned content\n `slots.elements(name?)`: `readable<element[]>`: the assigned elements for the slot\n\nslot signals update reactively when assigned content changes, including when slots are inserted dynamically (via `when()` or `each()`) after mount.\n\n## context api\n\n `createcontext<t>(description)`: create a unique typed injection key; the description is diagnostic only\n `provide(key, value)`: provide a value to descendants\n `inject(key)`: resolve from nearest ancestor; returns `undefined` if not found\n `inject(key, fallback)`: resolve with a fallback value\n `injectstrict(key)`: resolve or throw if absent\n\n`provide()` and `inject()` must be called synchronously during `setup()`. calling them outside a setup context throws\n`'lifecycle hooks must be called during component setup'`. context resolution walks the ancestor chain including shadow\ndom boundaries. `inject()` resolves and caches its result once per consumer: provide a `readable` (signal/computed)\nrather than a raw value if descendants need to observe later changes; re calling `provide()` with a new raw value\nafterward is not seen by consumers that already resolved it (a dev mode warning fires when a key is provided twice on\nthe same element). `provide()` registers cleanup automatically: context keys are removed from the registry when the\nproviding component disconnects, so reconnecting the same element runs `setup()` fresh without spurious \"overwriting\"\nwarnings or stale keys leaking to descendants.\n\n## utilities\n\n `ref<t>()`: create a `signal<t | null>` element reference. set to the element via `ref=` in templates.\n `createid(prefix = 'id')`: generate a collision resistant id with a semantic prefix, a per runtime tag, and a monotonic counter (for example, `'field a3k21'`).\n\n## form associated api\n\nimport from `@vielzeug/ore`.\n\n### `usefield(options)`\n\nwire a form associated element to `elementinternals`. requires `formassociated: true` on the component definition. the `disabled` state tracking via `internals.states` (customstateset) is skipped with a dev warning if the api is unavailable in the current environment.\n\n```ts\ntype formfieldvalidity = { flags: validitystateflags; message: string };\n\ntype formfieldoptions<t> = {\n disabled?: readable<boolean>;\n /**\n * when true, a null/undefined value is submitted as '' instead of null,\n * keeping the field's key present in formdata even when the value is absent.\n * only applies to the default toformvalue; ignored if toformvalue is provided.\n * @default false\n */\n emptystringfornull?: boolean;\n /** called when the ancestor <form> resets (see onformreset): restore local field state here. */\n onreset?: () => void;\n toformvalue?: (value: t) => file | formdata | string | null;\n /**\n * recomputed reactively and passed straight to internals.setvalidity().\n * null (or omitted) = always valid. flags and message travel together because\n * the platform's setvalidity() contract couples them (flags without a\n * non empty message throw); a single { flags, message } | null input makes a\n * desynced pair unrepresentable.\n */\n validity?: readable<formfieldvalidity | null>;\n value: signal<t> | readable<t>;\n};\n\ntype formfieldhandle = {\n checkvalidity(): boolean;\n readonly internals: elementinternals;\n reportvalidity(): boolean;\n /** set (non empty message) or clear (empty string) a custom validity error. */\n setcustomvalidity(message: string): void;\n};\n```\n\npass a single `validity` signal to make `required` style constraints participate in native constraint validation\nthrough `checkvalidity()` and `reportvalidity()`. the `{ flags, message }` pair is the one validity input: the old\nsplit `validity` + `validationmessage` options are gone, since they could drift apart into a state the platform\nrejects.\n\n```ts\nconst isblank = (v: string) => v.trim() === '';\n\nusefield({\n validity: computed(() =>\n required.value && isblank(value.value)\n ? { flags: { valuemissing: true }, message: 'this field is required.' }\n : null,\n ),\n value,\n});\n```\n\n## testing apis\n\nimport from `@vielzeug/ore/testing`.\n\n| api | purpose |\n| | |\n| `mount(setup, options?)` | mount a component and return a test fixture |\n| `cleanup()` | remove all mounted elements and reset test state |\n| `install(aftereach)` | register auto cleanup after each test |\n| `flush(options?)` | drain reactive updates and animation frames |\n| `renderhook(setup)` | run lifecycle hooks in isolation; overload accepts `propdefs` as first arg for typed props |\n| `oretimeouterror` | error thrown when `flush()` cannot settle tracked ore work |\n\n> **test isolation:** `cleanup()` removes mounted elements and resets ore's cross test caches and counters. call it in `aftereach`, or use `install(aftereach)`.\n\nimport `within`, named dispatchers such as `fireclick`, and waits such as `waituntil` or `waitforevent` from\n`@vielzeug/assay`.\n\n> **form associated component testing:** jsdom implements none of the `elementinternals` form association api.\n> `@vielzeug/assay` exports `installforminternalspolyfill()` for this: it polyfills\n> `setformvalue`/`setvalidity`/`checkvalidity`/`reportvalidity`/`validationmessage`/`validity`/`states`, mixes\n> `checkvalidity`/`reportvalidity`/`validity`/`validationmessage` onto the host element itself (real browsers do\n> this for any `formassociated: true` element), makes `formdata` collect a form associated element's set value, and\n> makes `<form>.reset()` invoke `formresetcallback()`. every patch is a guarded no op when its target already\n> exists, and the function returns an `uninstall()` that restores every patched global. call it directly from a\n> test setup (alongside `install(aftereach)`) only when the suite tests form associated components: the patches\n> are global, so suites without them shouldn't carry them. a downstream package (e.g. a component library built\n> on `ore`) should rely on it instead of hand rolling its own copy.\n\n#### `fixture` interface\n\n```ts\ninterface fixture<t extends htmlelement = htmlelement> {\n [symbol.dispose](): void; // delegates to dispose(): enables `using` declarations\n element: t;\n readonly disposed: boolean; // true after dispose() has been called\n readonly shadow: shadowroot | null;\n get<e extends element>(selector: string): e;\n query<e extends element>(selector: string): e | null;\n queryall<e extends element>(selector: string): e[];\n getbytext<e extends element>(text: string, selector?: string): e;\n querybytext<e extends element>(text: string, selector?: string): e | null;\n queryallbytext<e extends element>(text: string, selector?: string): e[];\n getbytestid<e extends element>(testid: string): e;\n querybytestid<e extends element>(testid: string): e | null;\n queryallbytestid<e extends element>(testid: string): e[];\n attr(name: string, value: string | number | boolean): promise<void>;\n attrs(record: record<string, string | number | boolean>): promise<void>;\n flush(options?: flushoptions): promise<void>;\n act(fn: () => unknown): promise<void>;\n dispose(): void; // removes the component from the dom: idempotent\n}\n```\n\n#### `renderhook`\n\nuseful for testing composable lifecycle hooks (`onmounted`, `watcheffect`, `inject`, etc.) without a template. `onmounted`/`oncleanup`/`watcheffect`/... work exactly as inside a real `setup()`, since they resolve the same implicit current component context:\n\n```ts\n// without props\nconst { result, flush, dispose } = await renderhook(() => {\n const count = signal(0);\n onmounted(() => {\n count.value = 1;\n });\n return count;\n});\nexpect(result.value).tobe(1);\n\n// with typed props (prop defs overload)\nconst { result } = await renderhook({ label: prop.string('hello'), count: prop.number(0) }, (props) => props.label);\nexpect(result.value).tobe('hello');\n```\n\n## ripple primitives\n\nore does **not** re export reactive primitives. import them directly from `@vielzeug/ripple`:\n\n```ts\nimport { batch, computed, signal, watch } from '@vielzeug/ripple';\n```\n\nsee the [ripple documentation](/ripple/) for the full api.\n\n## lifecycle events\n\n| event | when |\n| | |\n| `ore:error` | when a lifecycle callback fails: bubbles, composed; detail is `orelifecycleerror` |\n\n## types\n\n```ts\ntype propdef<t> = {\n readonly default: t;\n readonly parse: (value: string | null) => t;\n reflect?: boolean;\n};\n\ntype propsdef<t extends record<string, unknown>> = {\n [k in keyof required<t>]: propdef<t[k & keyof t]>;\n};\n\ntype propinputdefs = record<string, propdef<unknown>>;\n\n/**\n * infer reactive props type from a propinputdefs map.\n * each entry becomes readable<t> keyed by prop name.\n */\ntype inferprops<d extends propinputdefs> = {\n readonly [k in keyof d] ?: readable<inferpropvalue<d[k]>>;\n};\n\n// runtime hooks: all plain functions imported from '@vielzeug/ore', not fields on an object.\ntype onmountedcallback = () => cleanup | undefined;\ntype onformresetcallback = () => void;\n\ndeclare function onmounted(fn: onmountedcallback): void; // dom ready callback; runs after each connection's render\ndeclare function oncleanup(fn: cleanup): void; // register teardown; called on disconnect\ndeclare function onelement<t extends htmlelement>(\n ref: readable<t | null>,\n callback: (el: t) => cleanup | undefined,\n): () => void;\ndeclare function onevent<k extends keyof htmlelementeventmap>(\n target: eventtarget | null | undefined,\n event: k,\n listener: (e: htmlelementeventmap[k]) => void,\n options?: addeventlisteneroptions,\n): void;\ndeclare function onevent(\n target: eventtarget | null | undefined,\n event: string,\n listener: eventlistener,\n options?: addeventlisteneroptions,\n): void;\ndeclare function onformreset(fn: onformresetcallback): void; // runs on every ancestor <form> reset; formassociated only\ndeclare function watcheffect(fn: () => cleanup | undefined): () => void; // scoped reactive effect; auto cleaned on disconnect\ndeclare function bind(config: hostbindconfig, options?: bindoptions): () => void; // bindings for host or any target element\ndeclare function provide<t>(key: injectionkey<t>, value: t): void; // register a context value on the host element\ndeclare function inject<t>(key: injectionkey<t>): t | undefined;\ndeclare function inject<t>(key: injectionkey<t>, fallback: t): t;\ndeclare function gethost(): htmlelement; // the current component's host element\ndeclare function useemit<emits extends record<string, unknown> = record<string, never>>(): emitfn<emits>;\ndeclare function useslots<slotnames extends string = string>(): componentslots<slotnames>;\n\ntype componentdefinition<props extends record<string, unknown> = record<never, never>> = {\n formassociated?: boolean;\n props?: propsdef<props>;\n setup: (props: inferprops<propsdef<props>>) => htmlresult | null;\n shadow?: partial<shadowrootinit> | false; // false = light dom\n styles?: (string | cssstylesheet | cssresult)[];\n};\n\ntype maybereactive<t> = t | readable<t> | (() => t); // plain value, signal, or getter: accepted by when(), each(), classmap(), and bind()\n\ntype hostbindingvalue = maybereactive<string | number | boolean | null | undefined>;\n\ntype attributebindings = record<string, hostbindingvalue>;\n\ntype hostbindconfig = {\n attr?: attributebindings;\n class?: (() => record<string, boolean>) | record<string, readable<boolean> | (() => boolean) | boolean>;\n on?: record<string, ((event: event) => void) | undefined>;\n style?: record<string, hostbindingvalue>;\n};\n\ntype bindoptions = addeventlisteneroptions & {\n target?: element;\n};\n\ntype componentslots<s extends string = string> = {\n elements(name?: s): readable<element[]>;\n has(name?: s): readable<boolean>;\n};\n\ntype ref<t extends element> = signal<t | null>;\n\ntype refcallback<t extends element> = (el: t | null) => void;\n\ntype injectionkey<t> = symbol & { readonly __ore_injection_key?: t };\n\ninterface htmlresult {\n mount(\n parent: parentnode,\n anchor: node | null,\n registercleanup: (fn: () => void) => void,\n ): node[];\n}\n\ntype cssresult = {\n content: string;\n tostring(): string;\n};\n\ntype livebinding<t> = { readonly source: readable<t> };\n\ntype modeloptions<t = unknown> = {\n /** write back event (default: 'change' for checkbox/radio/select, 'input' otherwise). */\n event?: string;\n /** value reader (default: el.checked for checkbox/radio, el.value otherwise). */\n get?: (el: htmlelement) => t;\n};\n\ntype emitfn<t extends record<string, unknown>> = {\n <k extends keyswithoutdetail<t>>(event: k): boolean;\n <k extends exclude<keyof t, keyswithoutdetail<t>>>(event: k, detail: t[k]): boolean;\n};\n// keyswithoutdetail is an internal helper type, not exported.\n\ntype formfieldvalidity = { flags: validitystateflags; message: string };\n\ntype formfieldoptions<t = unknown> = {\n disabled?: readable<boolean>;\n emptystringfornull?: boolean;\n onreset?: () => void;\n toformvalue?: (value: t) => file | formdata | string | null;\n validity?: readable<formfieldvalidity | null>;\n value: signal<t> | readable<t>;\n};\n\ntype formfieldhandle = {\n checkvalidity: () => boolean;\n readonly internals: elementinternals;\n reportvalidity: () => boolean;\n setcustomvalidity: (message: string) => void;\n};\n\n/** phase in which a oreerror occurred. */\ntype oreerrorphase = 'each reconcile' | 'form reset' | 'mounted' | 'setup';\n```\n\n## errors\n\n`oreerror` is the base class for every ore error class: `err instanceof oreerror` catches all of them.\n\n **`oreapierror`**: thrown when the `ore` api itself is misused: calling `define()` with a duplicate tag, calling a lifecycle hook (`inject`, `onmounted`, `oncleanup`, `onevent`, …) outside of `setup()`, or passing an invalid prop definition to `define()`.\n **`oreinternalerror`**: thrown when an ore invariant fails, indicating a package bug rather than invalid application code.\n **`orelifecycleerror`**: reported in the `ore:error` event when component `setup()`, a mounted callback, a form reset callback, or `each()` reconciliation fails. extends `oreerror` with:\n `component: string`: the element's local name\n `phase: oreerrorphase`: `'setup'` | `'mounted'` | `'form reset'` | `'each reconcile'`\n `cause: error`: the original error thrown by `setup()`\n **`oretimeouterror`**: thrown by `flush()` (from `@vielzeug/ore/testing`) when pending ore work does not settle before its timeout.\n\nlifecycle failures dispatch a bubbling, composed `ore:error` event whose `detail` is the `orelifecycleerror`. setup\nfailures still rethrow their original error; mounted and form reset callback failures are reported through the same\nevent so their remaining callbacks can continue.\n",
|
|
962
|
+
"api": " \ntitle: 'ore: api reference'\ndescription: complete api reference for @vielzeug/ore and @vielzeug/ore/testing.\n \n\n[[toc]]\n\n## api overview\n\nall browser runtime symbols below are imported from `@vielzeug/ore`. lifecycle/context/binding functions (`onmounted`, `oncleanup`, `onevent`, `onelement`, `watcheffect`, `bind`, `provide`, `useemit`, `useslots`, `gethost`) resolve the active component through an implicit \"current component\" context: they work when called synchronously during `setup()`, or from any composable function `setup()` calls (transitively), but throw if called outside that window.\n\n> `watcheffect` is not named `watch`: `@vielzeug/ripple` already exports a `watch(source, callback)` with different semantics (explicit source + old/new value pair), and the two are frequently imported in the same file.\n\n| symbol | purpose | execution mode | common gotcha |\n| | | | |\n| `define()` | create and register a custom element | sync | tag must contain a hyphen; call before first use |\n| `html` | tagged template literal returning htmlresult | sync | expressions must be signals, functions, or primitives |\n| `prop.*` | typed prop helpers (string, bool, number, …) | sync | prop values are signals: read `.value` |\n| `provide()`/`inject()` | context api for parent to descendant sharing | setup only | must be called synchronously during `setup()` |\n| `ref()` | reactive reference to a dom element | sync | value is null until after first mount |\n| `createcontext()` | create a unique typed injection key | sync | context is scoped to the component tree |\n| `each()` | keyed list rendering with dom diffing | sync | duplicate keys report `ore:error`; plain `t[]` is a one time static render |\n| `when()` | conditional branch rendering | sync | getter fn computed disposed on cleanup; static bool skips subscription |\n| `live(signal)` | one way binding that skips stale writes during input | sync | use for controlled inputs alongside a manual `@input` handler |\n| `model(signal)` | two way form control binding (value/checked + write back) | sync | plain `value`/`checked` attribute only; pass `get` to keep numeric signals numeric |\n| `onmounted(fn)` | dom ready callback | setup only | must be called synchronously during `setup()` |\n| `oncleanup(fn)` | register teardown | setup only | called on component disconnect |\n| `onevent(target, …)` | scoped event listener with auto cleanup | setup only | no ops on null target; removed on disconnect |\n| `usefield(options)` | wire signal to form `elementinternals` | setup only | requires `formassociated: true` on the component definition |\n| `onformreset(fn)` | run work when the ancestor `<form>` resets | setup only | fires every reset (not one shot); only for `formassociated: true` components |\n| `useemit<emits>()` | typed `emit()` bound to the current host | setup only | call once per component; returns `dispatchevent`'s boolean (`false` if a listener called `preventdefault()`) |\n| `useslots<slotnames>()`| reactive slot presence/element signals | setup only | safe to call more than once: the underlying registry is created once |\n| `gethost()` | the current component's host element | setup only | prefer a higher level helper (`bind`, …) when one exists |\n\n## package entry points\n\n| import | purpose |\n| | |\n| `@vielzeug/ore` | all browser runtime apis, including directives, fields, and lifecycle helpers |\n| `@vielzeug/ore/testing` | ore specific mounting, lifecycle, hook, cleanup, and form test support |\n| `@vielzeug/assay` | generic dom events, scoped queries, and async waiting |\n\n## core component api\n\n### `define(tag, definition)`\n\n```ts\ndefine<props>(tag: string, definition: componentdefinition<props>): customelementconstructor;\n```\n\nreturns the registered class (for `instanceof` or subclassing); registration itself is the only global side effect.\n\nthe `setup()` function receives only typed prop signals:\n\n```ts\nsetup(props) {\n return html`<div>${props.label}</div>`;\n}\n```\n\neverything else: lifecycle hooks, host bindings, context, slots, emit: is a plain function imported from `@vielzeug/ore`, called directly from `setup()` (or a composable it calls):\n\n```ts\nimport { define, html, onmounted, useemit, useslots } from '@vielzeug/ore';\n\ndefine('my card', {\n setup(_props) {\n const emit = useemit<{ close: undefined }>();\n const slots = useslots<'header' | 'footer'>();\n\n onmounted(() => console.log('mounted'));\n\n // emit() returns dispatchevent's boolean: false if a listener called preventdefault()\n const notcancelled = emit('close');\n\n return html`${when(slots.has('header'), () => html`<slot name=\"header\"></slot>`)}`;\n },\n});\n```\n\n`useemit<emits>()` and `useslots<slotnames>()` are factory hooks: call them once per setup run to get a typed\n`emit`/`slots` bound to the current host. `useslots()` is safe to call more than once within that setup run.\n\n### componentdefinition\n\n```ts\ntype componentdefinition<props> = {\n formassociated?: boolean;\n props?: propsdef<props>;\n setup: (props: inferprops<propsdef<props>>) => htmlresult | null;\n shadow?: partial<shadowrootinit> | false; // false = light dom (no shadow root)\n styles?: (string | cssstylesheet | cssresult)[];\n};\n```\n\n## runtime helpers\n\n`onmounted`, `oncleanup`, `onevent`, `onelement`, and `watcheffect` are plain functions imported from `@vielzeug/ore`. call them directly during `setup()`.\n\n```ts\nimport { html, oncleanup, onevent, onmounted } from '@vielzeug/ore';\n\nsetup(props) {\n onmounted(() => {\n // dom is ready; return a function for mount scoped cleanup\n return () => { /* cleanup on unmount */ };\n });\n\n oncleanup(() => { /* called on disconnect */ });\n\n onevent(window, 'keydown', (e) => { /* auto removed on disconnect */ });\n\n return html`...`;\n}\n```\n\nbecause these resolve the active component through an implicit context (rather than a value threaded through parameters), composable helper functions can call them directly too: no need to pass hooks in as options:\n\n```ts\nimport { oncleanup } from '@vielzeug/ore';\n\nfunction usemyhelper() {\n oncleanup(() => { /* teardown */ });\n}\n\n// in setup:\nsetup(_props) {\n usemyhelper();\n return html`...`;\n}\n```\n\n## props api\n\n| helper | signature | notes |\n| | | |\n| `prop.string(defaultvalue?)` | `propdef<string>` | reflects by default |\n| `prop.bool(defaultvalue?)` | `propdef<boolean>` | any non null attribute value other than `\"false\"` parses as `true`; `\"false\"` or absent attribute is `false` |\n| `prop.number(defaultvalue?)` | `propdef<number>` | returns default (not nan) and warns in dev when attribute is not a valid number |\n| `prop.oneof(allowed, defaultvalue?)` | `propdef<t>` | restricts to a fixed set of string or number members; `parse` falls back to `defaultvalue` (or `undefined` when omitted) for anything outside the set. numeric members match the attribute parsed as a number |\n| `prop.json(defaultvalue)` | `propdef<t>` | json.parse from attribute; `reflect: false` |\n| `prop.data<t>(defaultvalue?)` | `propdef<t>` | js only: never reads/writes an attribute; use for objects, arrays, callbacks, or any non serialisable value |\n\n> **choosing the right prop helper:**\n>\n> **`prop.oneof`**: the honest way to type a union valued prop: the restriction is enforced at runtime (`parse` falls back for anything outside the set), not just in a type parameter a raw attribute value could violate. pass an `as const` array of the allowed string or number members.\n> **`prop.json`**: value can be declared in html (`<my el config='{\"x\":1}'>`); attribute string is `json.parse`d.\n> **`prop.data`**: value is always set from javascript (objects, arrays, callbacks, class instances); the attribute is never read. use this for both data and function props.\n\nwhen you need custom parsing or `reflect: false`, use a raw `propdef` object:\n\n```ts\nprops: {\n items: { default: [], parse: () => [], reflect: false },\n}\n```\n\nuse `prop.data` for props that hold js only values (including callbacks) that cannot be serialised through an html attribute:\n\n```ts\ndefine('data grid', {\n props: {\n getrowkey: prop.data<(row: unknown) => string>(),\n columns: prop.data<datagridcolumn[]>([]),\n onsort: prop.data<(key: string) => void>(),\n },\n setup(props) {\n // set from js: grid.getrowkey = (row) => row.id\n return html`...`;\n },\n});\n```\n\n## template and directives\n\n### `html`\n\ntagged template literal that returns an `htmlresult`. supports text interpolation, ordinary attributes (`attr=`),\nboolean attributes (`?attr=`), explicit property bindings (`.prop=`), events (`@event=` with optional\n`.stop`/`.prevent`/`.once`/`.capture` modifiers), refs (`ref=`), and nested templates.\n\n`.prop=${value}` always writes the element property (never an attribute): the explicit channel for structured\nvalues (arrays, objects, callbacks). prototype polluting names (`__proto__`, `constructor`, `prototype`) and\nraw html parsing names (`innerhtml`, `outerhtml`, `srcdoc`) are rejected at compile time: render sanitized\nhtml through the `unsafehtml()` directive instead of a property binding.\n\n`@event.stop`, `.prevent`, `.once`, and `.capture` are shorthand for the matching listener behavior\n(`stoppropagation`/`preventdefault` applied before the handler runs; `once`/`capture` passed as listener\noptions). an unknown modifier throws at compile time.\n\n### `css`\n\ntagged template literal that returns a `cssresult` for use in `styles`.\n\n### directives\n\n| directive | purpose |\n| | |\n| `each(source, key, render, fallback?)` | keyed reactive list; render receives `readable<t>` and `readable<number>`; plain `t[]` is a one time static snapshot |\n| `when(condition, truthy, falsy?)` | conditional rendering |\n| `classmap(record)` | reactive class string from object map |\n| `stylemap(record)` | reactive inline style string from object map |\n| `live(signal)` | one way binding that skips stale writes during active user input; use with `@input` handler |\n| `model(signal, options?)` | two way form control binding: writes the signal to `value`/`checked` and writes user input back on the control's change event |\n| `unsafehtml(value)` | html rendering sink; sanitize untrusted values before calling |\n\n`each()` treats number and string keys as distinct. a reconciliation failure (a duplicate key, or a render function that throws) reports `ore:error` and preserves the last valid list: entries created during the failed pass are rolled back, so the previous list stays exactly on screen.\n\n### `model(signal, options?)`\n\ntwo way binding for a form control: `value=${model(signal)}`. it writes the signal to the control's `value`/`checked` property on every change and writes user input back into the signal on the control's change event (`'change'` for checkboxes, radios, and `<select>`; `'input'` otherwise). this is the complete controlled input loop that the `live()` + manual `@input` handler pair used to require.\n\n```ts\nconst text = signal('');\nconst agree = signal(false);\nconst count = signal(0);\n\nhtml`\n <input value=${model(text)} />\n <input type=\"checkbox\" checked=${model(agree)} />\n <input type=\"number\" value=${model(count, { get: (el) => number(el.value) })} />\n`;\n```\n\n`options` overrides the defaults for non native controls: `event` sets the write back event name and `get` reads the current value out of the element (default `el.checked` for checkboxes/radios, `el.value` otherwise). because a native text input's `value` is always a string, pass a `get` like `(el) => number(el.value)` to keep a numeric signal numeric. `model()` can only drive a plain `value`/`checked` attribute binding; using it on a boolean (`?checked=`) or other attribute throws.\n\n### `unsafehtml`\n\n`unsafehtml()` is an explicit html injection sink. it has no global sanitizer: sanitize untrusted\ncontent before passing it to the directive, so the trust boundary remains at the call site.\n\n```ts\nimport { unsafehtml } from '@vielzeug/ore';\n\nconst safearticle = sanitize(usersuppliedarticle);\n\nreturn html`<article>${unsafehtml(safearticle)}</article>`;\n```\n\n## host bindings\n\n`bind(config, options?)` is a plain function imported from `@vielzeug/ore`:\n\n```ts\nbind({\n attr: { role: 'button', 'aria expanded': () => string(open.value) },\n class: { 'is open': open },\n style: { ' height': () => height.value + 'px' },\n on: { click: handleclick },\n});\n```\n\n`bind()` auto registers cleanup with the component scope: no manual `oncleanup` needed. returns a cleanup function for early teardown.\n\n### off host bindings\n\npass `{ target: el }` as a second argument to bind to any element other than the host:\n\n```ts\nbind(\n { attr: { 'aria expanded': () => string(isopen.value) } },\n { target: triggerel },\n);\n```\n\nevent listener options (`once`, `capture`, `passive`) are also accepted in the second argument. cleanup is auto registered with the component scope when called during setup.\n\n### reactive aria attributes\n\nuse explicit `aria *` keys in `bind({ attr }, { target })`:\n\n```ts\nconst stoparia = bind(\n {\n attr: {\n 'aria controls': panelid,\n 'aria expanded': () => isopen.value,\n 'aria haspopup': 'listbox',\n },\n },\n { target: triggerel },\n);\n```\n\nstatic values are applied once. getters and signals create reactive effects. calling `stoparia()` stops updates. values of `null`, `undefined`, or `false` remove the attribute.\n\n## slots\n\n `slots.has(name?)`: `readable<boolean>`: whether the named (or default) slot has assigned content\n `slots.elements(name?)`: `readable<element[]>`: the assigned elements for the slot\n\nslot signals update reactively when assigned content changes, including when slots are inserted dynamically (via `when()` or `each()`) after mount.\n\n## context api\n\n `createcontext<t>(description)`: create a unique typed injection key; the description is diagnostic only\n `provide(key, value)`: provide a value to descendants\n `inject(key)`: resolve from nearest ancestor; returns `undefined` if not found\n `inject(key, fallback)`: resolve with a fallback value\n `injectstrict(key)`: resolve or throw if absent\n\n`provide()` and `inject()` must be called synchronously during `setup()`. calling them outside a setup context throws\n`'lifecycle hooks must be called during component setup'`. context resolution walks the ancestor chain including shadow\ndom boundaries. `inject()` resolves and caches its result once per consumer: provide a `readable` (signal/computed)\nrather than a raw value if descendants need to observe later changes; re calling `provide()` with a new raw value\nafterward is not seen by consumers that already resolved it (a dev mode warning fires when a key is provided twice on\nthe same element). `provide()` registers cleanup automatically: context keys are removed from the registry when the\nproviding component disconnects, so reconnecting the same element runs `setup()` fresh without spurious \"overwriting\"\nwarnings or stale keys leaking to descendants.\n\n## utilities\n\n `ref<t>()`: create a `signal<t | null>` element reference. set to the element via `ref=` in templates.\n `createid(prefix = 'id')`: generate a collision resistant id with a semantic prefix, a per runtime tag, and a monotonic counter (for example, `'field a3k21'`).\n\n## form associated api\n\nimport from `@vielzeug/ore`.\n\n### `usefield(options)`\n\nwire a form associated element to `elementinternals`. requires `formassociated: true` on the component definition. the `disabled` state tracking via `internals.states` (customstateset) is skipped with a dev warning if the api is unavailable in the current environment.\n\n```ts\ntype formfieldvalidity = { flags: validitystateflags; message: string };\n\ntype formfieldoptions<t> = {\n disabled?: readable<boolean>;\n /**\n * when true, a null/undefined value is submitted as '' instead of null,\n * keeping the field's key present in formdata even when the value is absent.\n * only applies to the default toformvalue; ignored if toformvalue is provided.\n * @default false\n */\n emptystringfornull?: boolean;\n /** called when the ancestor <form> resets (see onformreset): restore local field state here. */\n onreset?: () => void;\n toformvalue?: (value: t) => file | formdata | string | null;\n /**\n * recomputed reactively and passed straight to internals.setvalidity().\n * null (or omitted) = always valid. flags and message travel together because\n * the platform's setvalidity() contract couples them (flags without a\n * non empty message throw); a single { flags, message } | null input makes a\n * desynced pair unrepresentable.\n */\n validity?: readable<formfieldvalidity | null>;\n value: signal<t> | readable<t>;\n};\n\ntype formfieldhandle = {\n checkvalidity(): boolean;\n readonly internals: elementinternals;\n reportvalidity(): boolean;\n /** set (non empty message) or clear (empty string) a custom validity error. */\n setcustomvalidity(message: string): void;\n};\n```\n\npass a single `validity` signal to make `required` style constraints participate in native constraint validation\nthrough `checkvalidity()` and `reportvalidity()`. the `{ flags, message }` pair is the one validity input: the old\nsplit `validity` + `validationmessage` options are gone, since they could drift apart into a state the platform\nrejects.\n\n```ts\nconst isblank = (v: string) => v.trim() === '';\n\nusefield({\n validity: computed(() =>\n required.value && isblank(value.value)\n ? { flags: { valuemissing: true }, message: 'this field is required.' }\n : null,\n ),\n value,\n});\n```\n\n## testing apis\n\nimport from `@vielzeug/ore/testing`.\n\n| api | purpose |\n| | |\n| `mount(setup, options?)` | mount a component and return a test fixture |\n| `cleanup()` | remove all mounted elements and reset test state |\n| `install(aftereach)` | register auto cleanup after each test |\n| `flush(options?)` | drain reactive updates and animation frames |\n| `renderhook(setup)` | run lifecycle hooks in isolation; overload accepts `propdefs` as first arg for typed props |\n| `oretimeouterror` | error thrown when `flush()` cannot settle tracked ore work |\n\n> **test isolation:** `cleanup()` removes mounted elements and resets ore's cross test caches and counters. call it in `aftereach`, or use `install(aftereach)`.\n\nimport `within`, named dispatchers such as `fireclick`, and waits such as `waituntil` or `waitforevent` from\n`@vielzeug/assay`.\n\n> **form associated component testing:** jsdom implements none of the `elementinternals` form association api.\n> `@vielzeug/assay` exports `installforminternalspolyfill()` for this: it polyfills\n> `setformvalue`/`setvalidity`/`checkvalidity`/`reportvalidity`/`validationmessage`/`validity`/`states`, mixes\n> `checkvalidity`/`reportvalidity`/`validity`/`validationmessage` onto the host element itself (real browsers do\n> this for any `formassociated: true` element), makes `formdata` collect a form associated element's set value, and\n> makes `<form>.reset()` invoke `formresetcallback()`. every patch is a guarded no op when its target already\n> exists, and the function returns an `uninstall()` that restores every patched global. call it directly from a\n> test setup (alongside `install(aftereach)`) only when the suite tests form associated components: the patches\n> are global, so suites without them shouldn't carry them. a downstream package (e.g. a component library built\n> on `ore`) should rely on it instead of hand rolling its own copy.\n\n#### `fixture` interface\n\n```ts\ninterface fixture<t extends htmlelement = htmlelement> {\n [symbol.dispose](): void; // delegates to dispose(): enables `using` declarations\n element: t;\n readonly disposed: boolean; // true after dispose() has been called\n readonly shadow: shadowroot | null;\n get<e extends element>(selector: string): e;\n query<e extends element>(selector: string): e | null;\n queryall<e extends element>(selector: string): e[];\n getbytext<e extends element>(text: string, selector?: string): e;\n querybytext<e extends element>(text: string, selector?: string): e | null;\n queryallbytext<e extends element>(text: string, selector?: string): e[];\n getbytestid<e extends element>(testid: string): e;\n querybytestid<e extends element>(testid: string): e | null;\n queryallbytestid<e extends element>(testid: string): e[];\n attr(name: string, value: string | number | boolean): promise<void>;\n attrs(record: record<string, string | number | boolean>): promise<void>;\n flush(options?: flushoptions): promise<void>;\n act(fn: () => unknown): promise<void>;\n dispose(): void; // removes the component from the dom: idempotent\n}\n```\n\n#### `renderhook`\n\nuseful for testing composable lifecycle hooks (`onmounted`, `watcheffect`, `inject`, etc.) without a template. `onmounted`/`oncleanup`/`watcheffect`/... work exactly as inside a real `setup()`, since they resolve the same implicit current component context:\n\n```ts\n// without props\nconst { result, flush, dispose } = await renderhook(() => {\n const count = signal(0);\n onmounted(() => {\n count.value = 1;\n });\n return count;\n});\nexpect(result.value).tobe(1);\n\n// with typed props (prop defs overload)\nconst { result } = await renderhook({ label: prop.string('hello'), count: prop.number(0) }, (props) => props.label);\nexpect(result.value).tobe('hello');\n```\n\n## ripple primitives\n\nore does **not** re export reactive primitives. import them directly from `@vielzeug/ripple`:\n\n```ts\nimport { batch, computed, signal, watch } from '@vielzeug/ripple';\n```\n\nsee the [ripple documentation](/ripple/) for the full api.\n\n## lifecycle events\n\n| event | when |\n| | |\n| `ore:error` | when a lifecycle callback fails: bubbles, composed; detail is `orelifecycleerror` |\n\n## types\n\n```ts\ntype propdef<t> = {\n readonly default: t;\n readonly parse: (value: string | null) => t;\n reflect?: boolean;\n};\n\ntype propsdef<t extends record<string, unknown>> = {\n [k in keyof required<t>]: propdef<t[k & keyof t]>;\n};\n\ntype propinputdefs = record<string, propdef<unknown>>;\n\n/**\n * infer reactive props type from a propinputdefs map.\n * each entry becomes readable<t> keyed by prop name.\n */\ntype inferprops<d extends propinputdefs> = {\n readonly [k in keyof d] ?: readable<inferpropvalue<d[k]>>;\n};\n\n// runtime hooks: all plain functions imported from '@vielzeug/ore', not fields on an object.\ntype onmountedcallback = () => cleanup | undefined;\ntype onformresetcallback = () => void;\n\ndeclare function onmounted(fn: onmountedcallback): void; // dom ready callback; runs after each connection's render\ndeclare function oncleanup(fn: cleanup): void; // register teardown; called on disconnect\ndeclare function onelement<t extends htmlelement>(\n ref: readable<t | null>,\n callback: (el: t) => cleanup | undefined,\n): () => void;\ndeclare function onevent<k extends keyof htmlelementeventmap>(\n target: eventtarget | null | undefined,\n event: k,\n listener: (e: htmlelementeventmap[k]) => void,\n options?: addeventlisteneroptions,\n): void;\ndeclare function onevent(\n target: eventtarget | null | undefined,\n event: string,\n listener: eventlistener,\n options?: addeventlisteneroptions,\n): void;\ndeclare function onformreset(fn: onformresetcallback): void; // runs on every ancestor <form> reset; formassociated only\ndeclare function watcheffect(fn: () => cleanup | undefined): () => void; // scoped reactive effect; auto cleaned on disconnect\ndeclare function bind(config: hostbindconfig, options?: bindoptions): () => void; // bindings for host or any target element\ndeclare function provide<t>(key: injectionkey<t>, value: t): void; // register a context value on the host element\ndeclare function inject<t>(key: injectionkey<t>): t | undefined;\ndeclare function inject<t>(key: injectionkey<t>, fallback: t): t;\ndeclare function gethost(): htmlelement; // the current component's host element\ndeclare function useemit<emits extends record<string, unknown> = record<string, never>>(): emitfn<emits>;\ndeclare function useslots<slotnames extends string = string>(): componentslots<slotnames>;\n\ntype componentdefinition<props extends record<string, unknown> = record<never, never>> = {\n formassociated?: boolean;\n props?: propsdef<props>;\n setup: (props: inferprops<propsdef<props>>) => htmlresult | null;\n shadow?: partial<shadowrootinit> | false; // false = light dom\n styles?: (string | cssstylesheet | cssresult)[];\n};\n\ntype maybereactive<t> = t | readable<t> | (() => t); // plain value, signal, or getter: accepted by when(), each(), classmap(), and bind()\n\ntype hostbindingvalue = maybereactive<string | number | boolean | null | undefined>;\n\ntype attributebindings = record<string, hostbindingvalue>;\n\ntype hostbindconfig = {\n attr?: attributebindings;\n class?: (() => record<string, boolean>) | record<string, readable<boolean> | (() => boolean) | boolean>;\n on?: record<string, ((event: event) => void) | undefined>;\n style?: record<string, hostbindingvalue>;\n};\n\ntype bindoptions = addeventlisteneroptions & {\n target?: element;\n};\n\ntype componentslots<s extends string = string> = {\n elements(name?: s): readable<element[]>;\n has(name?: s): readable<boolean>;\n};\n\ntype ref<t extends element> = signal<t | null>;\n\ntype refcallback<t extends element> = (el: t | null) => void;\n\ntype injectionkey<t> = symbol & { readonly __ore_injection_key?: t };\n\ninterface htmlresult {\n mount(\n parent: parentnode,\n anchor: node | null,\n registercleanup: (fn: () => void) => void,\n ): node[];\n}\n\ntype cssresult = {\n content: string;\n tostring(): string;\n};\n\ntype livebinding<t> = { readonly source: readable<t> };\n\ntype modeloptions<t = unknown> = {\n /** write back event (default: 'change' for checkbox/radio/select, 'input' otherwise). */\n event?: string;\n /** value reader (default: el.checked for checkbox/radio, el.value otherwise). */\n get?: (el: htmlelement) => t;\n};\n\ntype emitfn<t extends record<string, unknown>> = {\n <k extends keyswithoutdetail<t>>(event: k): boolean;\n <k extends exclude<keyof t, keyswithoutdetail<t>>>(event: k, detail: t[k]): boolean;\n};\n// keyswithoutdetail is an internal helper type, not exported.\n\ntype formfieldvalidity = { flags: validitystateflags; message: string };\n\ntype formfieldoptions<t = unknown> = {\n disabled?: readable<boolean>;\n emptystringfornull?: boolean;\n onreset?: () => void;\n toformvalue?: (value: t) => file | formdata | string | null;\n validity?: readable<formfieldvalidity | null>;\n value: signal<t> | readable<t>;\n};\n\ntype formfieldhandle = {\n checkvalidity: () => boolean;\n readonly internals: elementinternals;\n reportvalidity: () => boolean;\n setcustomvalidity: (message: string) => void;\n};\n\n/** phase in which a oreerror occurred. */\ntype oreerrorphase = 'each reconcile' | 'form reset' | 'mounted' | 'setup';\n```\n\n## errors\n\n`oreerror` is the base class for every ore error class: `err instanceof oreerror` catches all of them.\n\n **`oreapierror`**: thrown when the `ore` api itself is misused: calling `define()` with a duplicate tag, calling a lifecycle hook (`inject`, `onmounted`, `oncleanup`, `onevent`, …) outside of `setup()`, or passing an invalid prop definition to `define()`.\n **`oreinternalerror`**: thrown when an ore invariant fails, indicating a package bug rather than invalid application code.\n **`orelifecycleerror`**: reported in the `ore:error` event when component `setup()`, a mounted callback, a form reset callback, or `each()` reconciliation fails. extends `oreerror` with:\n `component: string`: the element's local name\n `phase: oreerrorphase`: `'setup'` | `'mounted'` | `'form reset'` | `'each reconcile'`\n `cause: error`: the original error thrown by `setup()`\n **`oretimeouterror`**: thrown by `flush()` (from `@vielzeug/ore/testing`) when pending ore work does not settle before its timeout.\n\nlifecycle failures dispatch a bubbling, composed `ore:error` event whose `detail` is the `orelifecycleerror`. setup\nfailures still rethrow their original error; mounted and form reset callback failures are reported through the same\nevent so their remaining callbacks can continue.\n",
|
|
963
963
|
"usage": " \ntitle: 'ore: usage guide'\ndescription: practical ore usage patterns for components, props, templates, slots, context, forms, sentinel integration, and tests.\n \n\n[[toc]]\n\n## basic usage\n\n`define(tag, definition)` creates and registers a custom element. call it from the module or browser bootstrap responsible for registration.\n\nyour `setup()` function receives typed prop signals and returns an `htmlresult` directly. its state belongs to the\ncurrent connection: disconnect disposes it, and reconnecting the same element runs setup again.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('status chip', {\n setup() {\n const online = signal(true);\n\n return html`\n <button @click=${() => (online.value = !online.value)}>${() => (online.value ? 'online' : 'offline')}</button>\n `;\n },\n});\n```\n\neverything besides `props`: lifecycle hooks, host bindings, context, slots, emit: is a plain function imported from `@vielzeug/ore`, called directly from `setup()` (or a composable it calls):\n\n```ts\nimport { define, gethost, html, bind, useemit, useslots } from '@vielzeug/ore';\n\ndefine('my widget', {\n setup(_props) {\n const el = gethost(); // the host htmlelement\n const emit = useemit<{ close: undefined }>(); // typed event emitter\n const slots = useslots<'header'>(); // reactive slot observation\n\n bind({ attr: { role: 'group' } }); // host binding helper (attr, class, style, on)\n\n return html`<slot></slot>`;\n },\n});\n```\n\n## signals and effects\n\nore does not re export ripple primitives: import them directly from `@vielzeug/ripple`.\n\n```ts\nimport { batch, computed, effect, signal, watch } from '@vielzeug/ripple';\n\nconst count = signal(0);\nconst doubled = computed(() => count.value * 2);\n\neffect(() => {\n console.log('doubled =', doubled.value);\n});\n\nwatch(count, (next, prev) => {\n console.log('count changed', prev, ' >', next);\n});\n\nbatch(() => {\n count.value = 1;\n count.value = 2;\n});\n```\n\n## onmounted and lifecycle\n\nuse `onmounted()` for dom dependent initialization that must run after the template is mounted. use `onelement(ref, cb)` for work tied to a specific dom node. `onevent()` attaches a listener that is automatically removed on disconnect.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, onelement, onevent, onmounted, ref, useslots } from '@vielzeug/ore';\n\ndefine('deferred init', {\n setup(_props) {\n const tabindex = signal(0);\n const inputref = ref<htmlinputelement>();\n const slots = useslots<'items'>();\n\n onmounted(() => {\n const items = slots.elements('items').value;\n console.log('found', items.length, 'items');\n });\n\n onelement(inputref, (input) => {\n input.focus();\n });\n\n onevent(window, 'keydown', (e: keyboardevent) => {\n if (e.key === 'escape') tabindex.value = 0;\n });\n\n return html`<div><slot name=\"items\"></slot><input ref=${inputref} /></div>`;\n },\n});\n```\n\n## prop definitions\n\nuse `prop.*` helpers for common cases, or raw `propdef` objects for custom parsing or `reflect: false`.\n\n```ts\nimport { define, html, prop } from '@vielzeug/ore';\n\ndefine('x button', {\n props: {\n label: prop.string('button'),\n disabled: prop.bool(false),\n variant: prop.oneof(['primary', 'secondary'] as const, 'primary'),\n count: prop.number(0),\n },\n setup(props) {\n return html`\n <button ?disabled=${props.disabled} data variant=${props.variant}>${props.label} (${props.count})</button>\n `;\n },\n});\n```\n\n## template bindings\n\n`html` supports text, attributes, booleans, properties, events, refs, and nested templates. event bindings accept\n`.stop`, `.prevent`, `.once`, and `.capture`: the first two apply before the handler runs, while the latter two use\nnative listener options. unknown modifiers throw while ore compiles the template.\n\n```ts\nimport { computed, signal } from '@vielzeug/ripple';\nimport { define, html, model, ref } from '@vielzeug/ore';\n\ndefine('profile name', {\n setup() {\n const name = signal('alice');\n const inputref = ref<htmlinputelement>();\n\n return html`\n <label title=${computed(() => 'current: ' + name.value)}>name</label>\n <input\n ref=${inputref}\n value=${model(name)}\n aria label=${() => 'current name ' + name.value} />\n <p>hello ${name}</p>\n `;\n },\n});\n```\n\n## directives\n\nore exports `each`, `classmap`, `stylemap`, `when`, `live`, `model`, and `unsafehtml` from `@vielzeug/ore`.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { classmap, define, each, html, stylemap, when } from '@vielzeug/ore';\n\ndefine('task list', {\n setup() {\n const tasks = signal([{ id: 1, text: 'write tests' }]);\n const active = signal(true);\n\n return html`\n <ul\n class=\"${classmap({ ready: () => tasks.value.length > 0 })}\"\n style=${stylemap({ opacity: () => (active.value ? 1 : 0.5) })}>\n ${when(\n () => active.value,\n () => html`<li>active</li>`,\n () => html`<li>paused</li>`,\n )}\n ${each(\n tasks,\n (task) => task.id,\n (task) => html`<li>${() => task.value.text}</li>`,\n )}\n </ul>\n `;\n },\n});\n```\n\n### each() api\n\n`each(source, key, render, fallback?)` takes positional arguments:\n\n **source**: signal, getter, or plain array\n **key**: function returning a unique string or number per item; number and string keys remain distinct\n **render**: receives reactive `item` and `index` signals\n **fallback**: optional, rendered when the list is empty\n\n```ts\neach(\n items,\n (item) => item.id,\n (item, index) => html`<li>#${index}: ${() => item.value.label}</li>`,\n () => html`<li>no items</li>`,\n);\n```\n\neach reactive reconciliation is transactional. ore creates missing entries before committing updates or removing stale\nentries; if a render callback throws, entries created during that pass are rolled back and the last successful list\nremains on screen. ore reports the failure through `ore:error` with phase `each reconcile`.\n\n## model: two way form bindings\n\nuse `model(signal)` for a controlled input: it writes the signal to the control's `value`/`checked` property and\nwrites user input back on the control's change event (`'change'` for checkboxes, radios, and selects; `'input'`\notherwise). this replaces the `live()` + manual `@input` handler pair with one binding.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, model } from '@vielzeug/ore';\n\ndefine('live search', {\n setup() {\n const query = signal('');\n const agree = signal(false);\n\n return html`\n <input value=${model(query)} />\n <input type=\"checkbox\" checked=${model(agree)} />\n `;\n },\n});\n```\n\na native text input's `value` is always a string, so pass a `get` reader to keep a numeric signal numeric, and an\n`event` name for custom controls that emit their own change event:\n\n```ts\nconst count = signal(0);\n\nhtml`\n <input type=\"number\" value=${model(count, { get: (el) => number(el.value) })} />\n <my picker value=${model(pick, { event: 'pick change', get: (el) => (el as mypicker).selection })} />\n`;\n```\n\n## live: one way bindings that preserve user edits\n\nuse `live(signal)` when a binding must skip a stale app state write while the user is mid edit, without writing\nuser input back. `model()` covers the common controlled input case; `live()` is for one way bindings that only\nneed the stale write guard.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, live } from '@vielzeug/ore';\n\ndefine('live search', {\n setup() {\n const query = signal('');\n\n return html`\n <input value=${live(query)} @input=${(e: event) => (query.value = (e.target as htmlinputelement).value)} />\n `;\n },\n});\n```\n\n## host bindings\n\n`bind()` wires reactive attrs, classes, styles, and events to the host element.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html } from '@vielzeug/ore';\n\ndefine('x toggle', {\n setup(_props) {\n const open = signal(false);\n\n bind({\n attr: { 'aria expanded': () => string(open.value), role: 'button', tabindex: 0 },\n class: { 'is open': open },\n on: { click: () => (open.value = !open.value) },\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\nthe `bind` config supports `attr`, `class`, `style`, and `on` sections.\n\n## aria bindings\n\nuse explicit `aria *` keys in `bind({ attr: config }, { target })` to reactively sync aria attributes to any element.\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html, onmounted } from '@vielzeug/ore';\n\ndefine('x disclosure', {\n setup(_props) {\n const open = signal(false);\n const panelid = 'disclosure panel';\n\n bind({\n attr: { role: 'button', tabindex: 0 },\n on: { click: () => (open.value = !open.value) },\n });\n\n onmounted(() => {\n const trigger = document.queryselector('#trigger') as htmlelement;\n if (trigger) {\n // bind() registers cleanup automatically when called inside setup\n bind(\n {\n attr: {\n 'aria controls': panelid,\n 'aria expanded': () => string(open.value),\n 'aria haspopup': 'region',\n },\n },\n { target: trigger },\n );\n }\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\nstatic values are applied once. getter functions create reactive effects. setting a value to `null`, `undefined`, or `false` removes the attribute.\n\n`bind()` always returns a cleanup function. use it to stop syncing early when a trigger element can be swapped out:\n\n```ts\nonmounted(() => {\n const trigger = document.queryselector('#trigger') as htmlelement;\n const stoparia = bind({ attr: { 'aria expanded': () => string(open.value) } }, { target: trigger });\n\n // stop syncing when the trigger is replaced\n oncleanup(stoparia);\n});\n```\n\n### binding a non host element with `bind()`\n\npass `{ target: el }` as a second argument to bind attributes, classes, styles, or events to any element:\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { bind, define, html, onmounted, ref } from '@vielzeug/ore';\n\ndefine('button wrapper', {\n setup(_props) {\n const visible = signal(false);\n const btnref = ref<htmlbuttonelement>();\n\n onmounted(() => {\n const btn = btnref.value;\n if (!btn) return;\n\n bind(\n {\n attr: { 'aria pressed': () => string(visible.value) },\n on: { click: () => (visible.value = !visible.value) },\n },\n { target: btn },\n );\n });\n\n return html`<button ref=${btnref}>toggle</button>`;\n },\n});\n```\n\n## slots and emits\n\n```ts\nimport { define, html, useemit, useslots, when } from '@vielzeug/ore';\n\ndefine('card with footer', {\n setup(_props) {\n const slots = useslots<'header' | 'footer'>();\n const emit = useemit<{ action: undefined }>();\n\n return html`\n <div class=\"card\">\n <slot name=\"header\"></slot>\n <slot></slot>\n ${when(slots.has('footer'), () => html`<footer><slot name=\"footer\"></slot></footer>`)}\n </div>\n <button @click=${() => emit('action')}>go</button>\n `;\n },\n});\n```\n\npass a `slotnames` type parameter to `useslots<slotnames>()` to get typed `slots.has()` and `slots.elements()` calls.\n\n## context provide/inject\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { createcontext, define, html, injectstrict, provide } from '@vielzeug/ore';\n\nconst count_ctx = createcontext<returntype<typeof signal<number>>>('count');\n\ndefine('count provider', {\n setup(_props) {\n const count = signal(0);\n provide(count_ctx, count);\n\n return html`<button @click=${() => count.value++}><slot></slot></button>`;\n },\n});\n\ndefine('count consumer', {\n setup() {\n const count = injectstrict(count_ctx);\n\n return html`<p>count: ${count}</p>`;\n },\n});\n```\n\n`provide()` registers cleanup automatically: context keys are removed from the registry when the providing component disconnects. on reconnect, `setup()` runs fresh and `provide()` re registers without spurious \"overwriting\" warnings. provide a `readable` (signal/computed) rather than a raw value if descendants need to observe later changes: `inject()` resolves and caches the value once per consumer connection.\n\n## form associated elements\n\n```ts\nimport { signal } from '@vielzeug/ripple';\nimport { define, html, prop } from '@vielzeug/ore';\nimport { usefield } from '@vielzeug/ore';\n\ndefine('rating input', {\n formassociated: true,\n setup() {\n const value = signal(0);\n const field = usefield({ value });\n\n return html`\n <button @click=${() => (value.value = 1)}>1</button>\n <button @click=${() => (value.value = 2)}>2</button>\n <button @click=${() => (value.value = 3)}>3</button>\n <button @click=${() => field.reportvalidity()}>validate</button>\n <p>current: ${value}</p>\n `;\n },\n});\n```\n\n## sentinel observers\n\nuse `@vielzeug/sentinel` for subscribable browser and dom observations. create element dependent sentinels inside `onmounted()` and dispose them with the component.\n\n```ts\nimport { define, html, oncleanup, onmounted, ref, watcheffect } from '@vielzeug/ore';\nimport { fromsubscribable } from '@vielzeug/ripple';\nimport { createelementsize, sentinelunavailableerror } from '@vielzeug/sentinel';\n\ndefine('x observed', {\n setup(_props) {\n const boxref = ref<htmldivelement>();\n\n onmounted(() => {\n const element = boxref.value;\n if (!element) return;\n\n try {\n const size = createelementsize(element);\n const sizestate = fromsubscribable(size, { signal: size.disposalsignal });\n\n watcheffect(() => {\n console.log(sizestate.value?.width);\n });\n\n oncleanup(() => size.dispose());\n } catch (error) {\n if (!(error instanceof sentinelunavailableerror)) throw error;\n }\n });\n\n return html`<div ref=${boxref}>observe me</div>`;\n },\n});\n```\n\n## testing utilities\n\nimport from `@vielzeug/ore/testing`.\n\n```ts\nimport { aftereach, describe, expect, it } from 'vitest';\nimport { signal } from '@vielzeug/ripple';\nimport { fireclick } from '@vielzeug/assay';\nimport { html } from '@vielzeug/ore';\nimport { cleanup, mount } from '@vielzeug/ore/testing';\n\ndescribe('my counter', () => {\n aftereach(cleanup);\n\n it('increments on click', async () => {\n let count!: returntype<typeof signal<number>>;\n const { query, act } = await mount(() => {\n count = signal(0);\n return html`<button @click=${() => count.value++}>${count}</button>`;\n });\n\n expect(query('button')?.textcontent).tobe('0');\n\n await act(() => fireclick(query('button')!));\n\n expect(query('button')?.textcontent).tobe('1');\n });\n});\n```\n\n## framework integration\n\nore components are standard custom elements and work natively in any framework.\n\n::: code group\n\n```tsx [react]\n// react 19+ supports custom elements natively.\nimport './x toggle'; // wherever define('x toggle', { ... }) is called\n\nfunction app() {\n return <x toggle aria label=\"open menu\" />;\n}\n```\n\n```ts [vue 3]\n<script setup lang=\"ts\">\nimport './x toggle'; // wherever define('x toggle', { ... }) is called\nimport { ref } from 'vue';\n\nconst open = ref(false);\n</script>\n\n<template>\n <x toggle :aria label=\"'open menu'\" @click=\"open = !open\" />\n</template>\n```\n\n```svelte [svelte]\n<script>\n import './x toggle'; // wherever define('x toggle', { ... }) is called\n\n function handleclick() {\n console.log('toggled');\n }\n</script>\n\n<x toggle aria label=\"open menu\" on:click={handleclick} />\n```\n\n:::\n\n## working with other vielzeug libraries\n\n### with ripple\n\nimport ripple primitives directly from `@vielzeug/ripple` for standalone reactive state outside components.\n\n```ts\nimport { signal, computed } from '@vielzeug/ripple';\nimport { define, html } from '@vielzeug/ore';\n\n// shared state created outside any component\nconst theme = signal<'light' | 'dark'>('light');\nconst isdark = computed(() => theme.value === 'dark');\n\ndefine('theme toggle', {\n setup() {\n return html`\n <button @click=${() => (theme.value = isdark.value ? 'light' : 'dark')}>\n ${() =>\n isdark.value ? '<ore icon name=\"sun\" size=\"16\"></ore icon>' : '<ore icon name=\"moon\" size=\"16\"></ore icon>'}\n </button>\n `;\n },\n});\n```\n\n### with forge\n\nuse `@vielzeug/forge` for typed form state. `usefield()` remains intentionally narrow: it connects a form associated\ncustom element to native `elementinternals` without imposing submission, validation, or dirty state policy.\n\n```ts\nimport { createform } from '@vielzeug/forge';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('signup form', {\n setup(_props) {\n const form = createform({ initialvalues: { email: '' } });\n\n return html`\n <form\n @submit=${(event: submitevent) => {\n event.preventdefault();\n void form.submit(async (values) => {\n console.log(values);\n });\n }}>\n <slot></slot>\n </form>\n `;\n },\n});\n```\n\n## best practices\n\n setup returns `html\\`...\\`` directly: not a function wrapping the template.\n use `watcheffect()` for reactive subscriptions tied to component lifetime: it auto registers cleanup on disconnect.\n use `onelement(ref, cb)` instead of `onmounted` when the work is tied to a single dom node.\n bind host attributes and classes via `bind()` rather than mutating the element directly.\n provide context at the nearest ancestor: avoid global context singletons.\n call `oncleanup()` for every resource allocated in `setup()` (websockets, intervals, external subscriptions).\n use `model(signal)` for two way form inputs; use `live(signal)` for a one way binding that must not clobber user in progress edits.\n extract composable helper functions freely: `onmounted`/`oncleanup`/`bind`/... resolve the active component through implicit context, so they work from any function called (transitively) during `setup()`, with no need to pass them in as parameters.\n test component mounting and lifecycle with `@vielzeug/ore/testing`; import generic dom events, queries, and waits\n from `@vielzeug/assay`.\n",
|
|
964
964
|
"examples": " \ntitle: 'ore: examples'\ndescription: practical examples and recipes for ore.\n \n\n## examples\n\n [counter component](./examples/counter component.md)\n [typed props and emits](./examples/typed props and emits.md)\n [observers in onmounted()](./examples/observers in onmount.md)\n [search list with directives](./examples/search list with directives.md)\n [context provider and consumer](./examples/context provider and consumer.md)\n [prop helpers and raw propdef](./examples/propsof builder api.md)\n [form associated rating input](./examples/form associated rating input.md)\n [test example with @vielzeug/ore/testing](./examples/test example at vielzeug ore testing.md)\n"
|
|
965
965
|
},
|