@cf-sync/client 0.1.0 → 0.2.0

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.
@@ -0,0 +1,143 @@
1
+ # defineApp & the definition kit
2
+
3
+ The shared app-definition kit from `@cf-sync/protocol` — the one package importable from both the worker and the browser. `defineSchema` declares the tables, `defineMutators` declares the named mutations, and `defineApp` bundles them with a version and migration chain into the single value both [`createWorkspaceDO`](/reference/server) and [`SyncClient`](/reference/sync-client#app) take — so "client and server disagree about the schema or mutators" is unrepresentable.
4
+
5
+ ```ts
6
+ import { defineApp, defineSchema, defineMutators, AppError } from '@cf-sync/protocol'
7
+ import { z } from 'zod'
8
+
9
+ const schema = defineSchema({
10
+ issues: z.object({ id: z.string(), title: z.string(), column: z.string().default('backlog') }),
11
+ })
12
+
13
+ const mutators = defineMutators(schema, {
14
+ 'issue.move': {
15
+ args: z.object({ id: z.string(), column: z.string() }),
16
+ apply: (tx, { id, column }) => {
17
+ const issue = tx.get('issues', id)
18
+ if (!issue) throw new AppError('NotFound', `issue ${id} does not exist`)
19
+ tx.put('issues', id, { ...issue, column })
20
+ },
21
+ },
22
+ })
23
+
24
+ export const app = defineApp({ version: 1, schema, mutators })
25
+ ```
26
+
27
+ ## Functions
28
+
29
+ ### defineApp
30
+
31
+ `(config) => AppDefinition`
32
+
33
+ The anchor of the kit. `config` takes:
34
+
35
+ | Field | Type | Notes |
36
+ |---|---|---|
37
+ | `version` | `number` · **required** | Current schema version — a positive integer, start at 1 |
38
+ | `schema` | `SyncSchema` · **required** | The `defineSchema` result |
39
+ | `mutators` | mutator registry | Omissible for a pure-CRUD app; required non-empty with `crud: false` |
40
+ | `migrations` | `{ [toVersion]: fn \| null }` | The chain that carries old workspaces forward |
41
+ | `presence` | standard schema | Enables the typed [presence surface](/guide/presence) |
42
+ | `crud` | `boolean` · default `true` | `false` drops the built-in `sync.put`/`sync.del` pair |
43
+
44
+ Validation happens at definition time, so a bad chain fails at startup in both bundles — not silently at data-touch time. `version` must be a positive integer. `migrations` keys must be integers ≥ 2, none beyond `version`, consecutive (each entry's key is the previous key + 1), and the chain must end exactly at `version` — bumping the version without declaring what happens to existing data throws immediately. Entries below the versions still in the field may be dropped; a workspace stored below the oldest declared entry re-raises the error at wake instead of restamping data it cannot interpret. See [Schema evolution](/guide/schema-evolution).
45
+
46
+ `mutators` takes a registry built by [`defineMutators`](#definemutators) or the definitions written inline — both infer identically (each `apply`'s `tx` and `args` type from the schema and the sibling `args` schema). `defineMutators` is only *required* when declaring an `authContext`, its third argument.
47
+
48
+ Unless `crud: false`, the [`crudMutators`](#crudmutators) pair is spread into the registry first — your entries win on a name collision, so a hand-rolled `sync.put` overrides the built-in rather than duplicating it. `crud: false` with no mutators throws (it declares an app nothing can write to), and [collections](/reference/collections) refuse to attach to a `crud: false` app — every write must go through a named mutator. The `authContext` schema declared with `defineMutators` is lifted onto the definition here, so the server can validate authorize verdicts at connect and the client can fail-fast-validate its `authContext` option.
49
+
50
+ The `presence` schema, unlike table schemas, needs **no** version bump when it changes — presence is never stored, so drift between deploy bundles only warns softly. It must parse its own output (plain object schemas, no `transform`s): `presence.update` merges partials into the previously *parsed* state and re-validates, so output that fails input validation breaks the merge — enforced with a descriptive throw at the first `set`/`initialPresence`.
51
+
52
+ ### defineSchema
53
+
54
+ `(tables: Record<string, TableSchema>) => SyncSchema`
55
+
56
+ Declares the synced tables and their row schemas — the single source of truth shared by server and client. Each value is a standard schema whose input and output are plain records (a zod `z.object(...)` is the expected shape). Everything typed derives from it: collection row types, `MutatorTx` reads and writes, server-side row validation.
57
+
58
+ Table names must match `TABLE_NAME_RE` — identifier-like, a letter or underscore followed by up to 63 letters, digits, or underscores — and `defineSchema` throws at definition time on anything else. Row ids are capped at `MAX_ID_LENGTH` (256 UTF-16 code units); an id that is empty, over the cap, or contains a NUL makes any `tx` operation targeting it reject permanently with `InvalidArgs`.
59
+
60
+ The server validates **every** row write against the table's schema before it commits — a client can never write a shape the schema doesn't allow, no matter what it sends. Defaults apply on insert: `tx.put` takes the schema's *input* shape (defaults omissible) and stores the validated *output*. Validation must be synchronous — mutations apply inside a synchronous SQLite transaction, so a schema whose validate returns a Promise (a zod async refinement) is rejected at validation time as a permanent error.
61
+
62
+ ### defineMutators
63
+
64
+ `(schema, defs, options?) => defs`
65
+
66
+ Declares the named, intent-based mutations for a schema — shared by the server (authoritative apply) and the client (typed `mutate`, fail-fast validation). Each entry is a `MutatorDef`:
67
+
68
+ - `args` — optional standard schema for the mutation's arguments. The server validates before `apply` runs (invalid args are a permanent `InvalidArgs` error that still advances the LMID); a SyncClient built with the same registry validates at `mutate()` time as a fail-fast. Omit for mutators that take no args.
69
+ - `apply(tx, args, ctx)` — the mutation itself, against a [`MutatorTx`](#mutatortx) with a [`MutatorContext`](#mutatorcontext). The same function runs twice — optimistically on the client the moment `mutate` is called, authoritatively on the server when the push arrives — so it must be deterministic: pass ids, timestamps, and random values in as args, never compute them inside, or the server's result will not match the local prediction. See [the two authoring rules](/guide/defining-your-app#the-two-authoring-rules).
70
+
71
+ Names are validated at definition time: non-empty, no empty dot-segments, and — because dots namespace the `client.mutate` call tree (`mutate.todos.clearCompleted`) — a name cannot be both a mutator and a namespace prefix of another (`todos` alongside `todos.clear` throws).
72
+
73
+ The optional third argument, `{ authContext: schema }`, declares the shape of `ctx.auth` — the connection-time context the worker's `authorize` hook stamps on each socket. Mutators are its consumer, so it is declared with them; the server validates each verdict's context against it at connect, so drift between authorize and mutators fails the upgrade with 4401 instead of surfacing mid-mutation. See [Auth & sessions](/guide/auth).
74
+
75
+ ### crudMutators
76
+
77
+ `(schema) => CrudMutators<S>`
78
+
79
+ The full-row last-write-wins pair — `sync.put` and `sync.del`, the mutations [collections](/reference/collections) emit for local `insert`/`update`/`delete`. `defineApp` includes them automatically (opt out with `crud: false`); calling this directly is only needed for hand-assembled registries. Typed against the schema — `sync.put` args are a union over the declared tables, so direct `mutate.sync.put(...)` calls type-check per table — and row payloads are validated by the engine's `put` like any other write.
80
+
81
+ ## The mutator runtime
82
+
83
+ ### MutatorTx
84
+
85
+ The authoritative view a mutator runs against, typed from the schema:
86
+
87
+ - `get(tbl, id)` — the stored row (output shape, defaults applied) or `null`.
88
+ - `list(tbl)` — every row as `{ id, data }`.
89
+ - `put(tbl, id, data)` — writes the input shape, stores the validated output.
90
+ - `del(tbl, id)` — removes the row.
91
+
92
+ Reads see the mutation's own buffered writes; writes flush to SQLite only if the mutator completes without error, and they commit in the same transaction as the client's `last_mutation_id` advance — the mutation's effects and its bookkeeping are atomic, which is the engine's core invariant. `get`/`list`/`del` accept unknown tables at runtime so [migrations](#migrations) can read and clean up tables that left the schema — only `put` is strict.
93
+
94
+ ### MutatorContext
95
+
96
+ The third argument every `apply` receives — how a mutator tells its two runs apart:
97
+
98
+ - `clientId` — the stable id of the pushing client: the SyncClient's own id in optimistic runs, the socket's attested id on the server, so both runs of one mutation see the same value.
99
+ - `principal` — the identity the worker's `authorize` hook stamped on the connection; `undefined` when no hook stamped one, and always `undefined` in optimistic runs (the client has no server verdict).
100
+ - `auth` — the verdict's context, validated against the `authContext` schema at connect; on the client, the value passed as the SyncClient [`auth`](/reference/sync-client#auth) option.
101
+ - `authoritative` — `true` on the server's run, `false` optimistically. Permission checks written as `if (ctx.authoritative && !allowed) throw` enforce on the server while letting the optimistic apply proceed; a server rejection rolls back through the normal permanent-error path.
102
+
103
+ ### AppError
104
+
105
+ `new AppError(code: string, message: string)`
106
+
107
+ Thrown by mutators to reject a mutation **permanently**: the engine discards the mutation's writes but still advances the client's `last_mutation_id` in the same transaction — a permanently rejected mutation is *done*, never retried, never blocking the queue behind it — and the rejection surfaces on the client as a [`MutationError`](/reference/sync-client#mutationerror) carrying this `code`, with the optimistic effect rolled back. Any **other** thrown error is treated as transient: the transaction rolls back, nothing advances, and the client retries — so reserve plain `Error` for genuine bugs, never business rules.
108
+
109
+ `code` is app-defined (`NotFound`, `ReadOnly`, …); the `EngineErrorCode` values — `InvalidArgs`, `UnknownMutator`, `RowTooLarge` — are reserved for the engine's own rejections, all equally permanent.
110
+
111
+ ## Migrations
112
+
113
+ `SchemaMigrationFn` is `(tx: MigrationTx) => void` — one entry in `defineApp`'s `migrations` record, rewriting rows stored under version `to - 1` into the shape expected at `to`. `null` marks a purely additive change: the stored version is restamped with no data rewrite, and existing cursors stay valid. `defineApp` normalizes the record into an ascending `SchemaMigration[]` (`{ to, migrate }`) on the definition.
114
+
115
+ `MigrationTx` is deliberately untyped by the current schema: a migration reads rows in their **old** shape (and may touch tables that have since left the schema), so the current row types would be lies. Reads come back as `Record<string, unknown>` — narrow what you touch — rather than `any`, so a typo'd field access still fails to compile. Writes are shape-free here; the *net result* of the whole chain is validated against the current schema at commit.
116
+
117
+ When a workspace wakes behind the current version, all pending steps replay against one write buffer inside one transaction: later steps read earlier steps' writes, everything commits atomically at a single new data version, and the *net result* of the chain is validated against the current schema at commit — intermediate shapes are transient, so shipped steps never need editing when a later version reshapes the same table. The full rollout story, including what clients experience during a deploy, is in [Schema evolution](/guide/schema-evolution).
118
+
119
+ ## Limits
120
+
121
+ | Constant | Value | On violation |
122
+ |---|---|---|
123
+ | `MAX_ROW_BYTES` | 700,000 bytes of JSON per row | permanent `RowTooLarge` rejection (400 via the admin API) |
124
+ | `MAX_PRESENCE_BYTES` | 8,192 bytes per presence state | error frame — never truncated or coerced |
125
+ | `MAX_ID_LENGTH` | 256 UTF-16 code units per row id | permanent `InvalidArgs` rejection |
126
+ | `TABLE_NAME_RE` | `/^[A-Za-z_][A-Za-z0-9_]{0,63}$/` | `defineSchema` throws at definition time |
127
+
128
+ The row cap exists so a single row always fits a WebSocket frame with room to spare; presence payloads are cursor-cadence ephemera, not documents.
129
+
130
+ ## Types
131
+
132
+ Helper types exported for building on the kit — most apps never name them, but they are the seams for generic code:
133
+
134
+ - `RowOf<S, K>` — a table's stored row shape (schema output, defaults applied).
135
+ - `RowInputOf<S, K>` — a table's writable row shape (schema input, defaults omissible).
136
+ - `TableName<S>` — the union of a schema's table names as string literals.
137
+ - `AuthContextOf<M>` — the validated auth-context type a registry declares; `unknown` when none.
138
+ - `PresenceOf<A>` — an app's presence payload type; `never` when no presence schema is declared.
139
+ - `PresencePeer<T>` — one peer as apps consume it: `{ clientId, principal?, state, receivedAt }`, identity server-attested.
140
+ - `EngineErrorCode` — `'InvalidArgs' | 'UnknownMutator' | 'RowTooLarge'`, the reserved rejection codes.
141
+ - `MutationArgs<Def>` — the argument tuple `mutate` accepts for one mutator definition.
142
+ - `AnySyncSchema` / `AnyMutators` — the bounds to constrain on when writing your own generics over a schema or registry (concrete results are assignable to these, not to the parameterized types).
143
+ - `AUTH_CONTEXT` — the symbol `defineMutators` stamps a registry's `authContext` schema under. Root-exported only so a package that re-exports its registry with declaration emit on can name the inferred type; read the context type through `AuthContextOf`, never the symbol.
@@ -0,0 +1,25 @@
1
+ # API reference
2
+
3
+ The reference is organized by what you're building against, not by package internals. Everything documented here is the supported surface; anything importable but undocumented (notably `@cf-sync/protocol/internal`) carries no compatibility promise.
4
+
5
+ | Page | Covers |
6
+ |---|---|
7
+ | [SyncClient](/reference/sync-client) | The client: constructor options, `mutate`, presence, lifecycle, errors, React hooks |
8
+ | [Collections](/reference/collections) | The TanStack DB adapter: `createCollections`, per-table options, reading with live queries |
9
+ | [defineApp & the definition kit](/reference/define-kit) | `defineApp` · `defineSchema` · `defineMutators` · `AppError` · migrations · limits |
10
+ | [Server](/reference/server) | `createWorkspaceDO`, the sync and admin routers, `authorize`, `workspaceAdmin` |
11
+ | [Test engine](/reference/testing) | `createTestEngine` — the real engine semantics in plain node |
12
+ | [Yjs fields](/reference/yjs) | The collaborative-text add-on: server extension, client handles, `useYjsField` |
13
+
14
+ ## Packages
15
+
16
+ | Package | Import from | Runs in |
17
+ |---|---|---|
18
+ | `@cf-sync/protocol` | both bundles — the shared definition kit | worker + browser + node |
19
+ | `@cf-sync/server` | the worker entry (plus `/testing` in node tests) | workerd (testing: node) |
20
+ | `@cf-sync/client` | the browser bundle (plus `/react`) | browser |
21
+ | `@cf-sync/yjs` | `/server`, `/client`, `/react` subpaths | per subpath |
22
+
23
+ `zod` and `@tanstack/db` are peer dependencies; `react`, `@tanstack/react-db`, and `yjs` are optional/add-on peers. The server's main entry imports `cloudflare:workers` — in node, import `@cf-sync/server/testing` instead ([why](/guide/testing)).
24
+
25
+ Every symbol here also carries its documentation as JSDoc — hovering it in your editor shows the same contracts, defaults, and examples.
@@ -0,0 +1,174 @@
1
+ # Server
2
+
3
+ The worker half of the engine from `@cf-sync/server`: `createWorkspaceDO` builds the Workspace Durable Object class from the shared [app definition](/reference/define-kit#defineapp), and the router factories (`createSyncFetch`, `createAdminFetch`) route traffic to it. The engine's surface is the sync protocol and the admin routes — never methods on the DO instance. The package also re-exports the whole define kit, so server-only code can import everything from one place.
4
+
5
+ ```ts
6
+ // worker/worker.ts
7
+ import { createWorkspaceDO, createSyncFetch } from '@cf-sync/server'
8
+ import { app } from '../src/schema' // the same defineApp value the client uses
9
+
10
+ export class WorkspaceDO extends createWorkspaceDO({ app }) {}
11
+
12
+ export default {
13
+ fetch: createSyncFetch<Env>({
14
+ namespace: (env) => env.WORKSPACE,
15
+ authorize: async (request, { workspaceId }) => true, // see /guide/auth
16
+ }),
17
+ }
18
+ ```
19
+
20
+ ## createWorkspaceDO
21
+
22
+ `(config: WorkspaceEngineConfig) => WorkspaceDOClass`
23
+
24
+ Builds the Workspace Durable Object class. Export the returned class from the worker entry and bind it in wrangler with `new_sqlite_classes` — the engine requires SQLite-backed storage, and a class declared with `new_classes` deploys fine and then fails at runtime on its first SQL access:
25
+
26
+ ```jsonc
27
+ // wrangler.jsonc
28
+ {
29
+ "durable_objects": {
30
+ "bindings": [{ "name": "WORKSPACE", "class_name": "WorkspaceDO" }]
31
+ },
32
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["WorkspaceDO"] }]
33
+ }
34
+ ```
35
+
36
+ Each workspace id resolves to one instance holding that workspace's rows, mutation log, and live sockets. The class is deliberately opaque (`WorkspaceDOClass`) — traffic reaches it through the routers below, never through instance methods.
37
+
38
+ Export it through an empty subclass, as above: a `class` declaration is a type as well as a value, which is what lets `wrangler types` emit `WORKSPACE: DurableObjectNamespace<WorkspaceDO>` (a bare `export const` leaves the generated Env referencing a type that doesn't exist). The subclass exists to *name* the class — keep the body empty. The engine's handlers (`fetch`, `webSocketMessage`, `webSocketClose`, `alarm`) are not extension points; overriding them breaks the invariants the engine maintains. Server-side behavior is added through [`extension`](#extension) instead.
39
+
40
+ ### app
41
+
42
+ `AppDefinition` · **required**
43
+
44
+ The shared [app definition](/reference/define-kit#defineapp) — the same `defineApp` object every client is constructed with: schema version, table schemas, mutator registry, and the migration chain. Every `tx.put` — from mutators, migrations, and admin imports — is validated against the target table's schema; the validated output (defaults applied) is what gets stored. When the DO wakes with data stored under an older version, the migration chain replays before any traffic and commits atomically at a single new data version; a stored version outside the declared chain, or a throwing step, quarantines the workspace rather than serving old-shaped data. See [Schema evolution](/guide/schema-evolution).
45
+
46
+ ### compaction
47
+
48
+ `CompactionConfig`
49
+
50
+ Tunes tombstone compaction, which runs on the workspace's periodic maintenance alarm to keep deleted-row bookkeeping from growing forever.
51
+
52
+ - `tombstoneRetentionVersions` — `number` · default `10_000`. How many data versions of tombstones to keep; older ones are hard-deleted on the alarm. A client whose cursor predates the youngest deleted tombstone can no longer catch up incrementally and re-bootstraps on its next connect — larger retention trades storage for fewer forced bootstraps of long-offline clients.
53
+ - `intervalMs` — `number` · default `21_600_000` (6 hours). Milliseconds between maintenance-alarm runs. The alarm is shared with the R2 export: the DO schedules at the smaller of the two configured intervals.
54
+ - `disabled` — `boolean` · default `false`. Skips tombstone compaction entirely — tombstones accrue unbounded. The maintenance alarm still runs when an R2 export is configured.
55
+
56
+ ### export
57
+
58
+ `ExportConfig`
59
+
60
+ Streams the workspace's mutation log to an R2 bucket as ndjson objects on the maintenance alarm — archive and analytics off the hot path. DO SQLite stays the system of record (it has point-in-time recovery of its own); R2 covers everything beyond it. Exports are idempotent: object keys embed the log-sequence range, so a re-export after a failed cursor update overwrites the same object. See [Operations](/guide/operations#r2-mutation-log-archive).
61
+
62
+ - `bucket` — `(env: Env) => R2Bucket` · **required**. Resolves the R2 bucket from the worker env. Annotate the parameter to type the whole DO's env: `(env: Env) => env.EXPORT_BUCKET`.
63
+ - `intervalMs` — `number` · default `300_000` (5 minutes). Milliseconds between export runs — the archive's worst-case staleness. Shares the maintenance alarm with compaction.
64
+ - `maxBatchRows` — `number` · default `5_000`. Log entries per exported object.
65
+ - `maxObjectsPerRun` — `number` · default `20`. Bound on objects written per maintenance run.
66
+ - `prefix` — `string` · default `"cf-sync"`. Key prefix; objects land at `<prefix>/<workspaceId>/mutation-log/<from>-<to>.ndjson`.
67
+
68
+ ### extension
69
+
70
+ `() => EngineExtension`
71
+
72
+ Binary-lane extension factory — e.g. `yjsFields()` from [`@cf-sync/yjs/server`](/reference/yjs). A factory, not an instance: it is invoked once per workspace DO instance, because instances of one class share an isolate and a single extension object would leak in-memory state across workspaces. See [EngineExtension](#engineextension) below.
73
+
74
+ ### logger
75
+
76
+ `EngineLogger` — `(level: 'warn' | 'error', message, context: EngineLogContext, ...detail) => void` · default: the console
77
+
78
+ Where the engine's diagnostics go — init failures, [schema-drift warnings](/guide/schema-evolution#drift-detection), internal errors. The default is visible in `wrangler tail`; inject to route them into your own logging pipeline. Messages arrive fully formatted (including the `[cf-sync]` prefix).
79
+
80
+ `context.workspaceId` names the workspace the diagnostic came from — instances of one DO class share an isolate, so without it a line cannot be traced back to a workspace. It is the id the workspace was addressed by, remembered from the first request it served, falling back to the Durable Object id for construction-time diagnostics and workspaces whose meta row is unloadable; never empty.
81
+
82
+ ```ts
83
+ logger: (level, message, { workspaceId }, ...detail) => {
84
+ console[level](JSON.stringify({ level, message, workspaceId, detail }))
85
+ }
86
+ ```
87
+
88
+ ## createSyncFetch · createSyncRoute
89
+
90
+ `(opts: SyncFetchOptions) => (request, env) => Promise<Response>` · `…Promise<Response | null>`
91
+
92
+ The worker router for sync WebSocket upgrades at `${pathPrefix}/<workspaceId>`. `createSyncRoute` is the composable form: it resolves to `null` when the request is not this route's traffic, so a worker entry chains routes with `??` and owns its own fallback; requests that *are* its traffic but malformed (missing websocket upgrade, missing clientId, failed authorize) return real Responses, never null. `createSyncFetch` is the same route with a built-in 404 fallback — the right shape when sync is the worker's only (or last) route.
93
+
94
+ ```ts
95
+ const sync = createSyncRoute<Env>({ namespace: (env) => env.WORKSPACE, authorize })
96
+ const admin = createAdminRoute<Env>({ namespace: (env) => env.WORKSPACE, authorize: bearerTokenAuth((env) => env.ADMIN_TOKEN) })
97
+ export default {
98
+ fetch: async (request: Request, env: Env) =>
99
+ (await sync(request, env)) ?? (await admin(request, env)) ?? new Response('not found', { status: 404 }),
100
+ }
101
+ ```
102
+
103
+ ### namespace
104
+
105
+ `(env: Env) => DurableObjectNamespace<any>` · **required**
106
+
107
+ Resolves the workspace Durable Object namespace from the worker env — typically `(env) => env.WORKSPACE`. Typed `DurableObjectNamespace<any>` so both a bare binding and the `DurableObjectNamespace<WorkspaceDO>` that `wrangler types` generates are accepted without a cast.
108
+
109
+ ### authorize
110
+
111
+ `'public' | ((request, { workspaceId, clientId, env }) => boolean | Response | AuthVerdict | Promise<…>)` · **required**
112
+
113
+ Connection-time authorization, run in the worker before the DO is reached. Required, so "forgot auth" cannot ship looking identical to "chose no auth" — the literal `'public'` is the explicit opt-out (anyone who can reach the worker can read and write every workspace; fine for a demo, written down where a reviewer will see it). v1 policy: workspace membership grants full access; mutation-level checks live in mutators, reading the verdict's stamps via `ctx`. Four return forms for the hook:
114
+
115
+ | Return | Effect |
116
+ |---|---|
117
+ | `true` | admit, no stamps |
118
+ | `false` | HTTP 403 — correct for non-browser callers |
119
+ | a `Response` | full control over the rejection |
120
+ | an `AuthVerdict` | distinguishable rejections and connection stamps |
121
+
122
+ `{ ok: true, principal?, context?, expiresAt? }` stamps `principal` and `context` onto the connection — mutators read them synchronously as `ctx.principal` / `ctx.auth`, validated against the app's `authContext` schema at upgrade, not mid-mutation. `expiresAt` (epoch ms) bounds how long the stamps stay trusted without being re-derived: past it, the DO closes the socket with 4300 and the reconnect re-runs `authorize`. Omitted means no expiry — apps with reliable revocation webhooks don't pay for one.
123
+
124
+ `{ ok: false, code?, reason? }` completes the upgrade and immediately closes it — a browser cannot observe the HTTP status of a failed upgrade, so the close frame is what makes rejections distinguishable from network errors, and the DO never wakes. `code` defaults to 4403 (permanent: the client stops reconnecting and calls [`onFatal`](/reference/sync-client#onfatal)); `reason` rides the close frame, capped at 123 UTF-8 bytes — short stable slugs (`membership-revoked`), not prose. The full auth story — stamps in mutators, expiry, revocation, close-code bands — is in [Auth & sessions](/guide/auth).
125
+
126
+ ### pathPrefix
127
+
128
+ `string` · default `"/sync"`
129
+
130
+ URL prefix for sync routes (`${prefix}/<workspaceId>`), matching the client's [`pathPrefix`](/reference/sync-client#pathprefix).
131
+
132
+ ## createAdminFetch · createAdminRoute
133
+
134
+ `(opts: AdminFetchOptions) => (request, env) => Promise<Response>` · `…Promise<Response | null>`
135
+
136
+ The worker router for the workspace admin surface at `${pathPrefix}/<workspaceId>/<op>` (default prefix `"/admin"`). Same route/fetch split as the sync pair. `namespace` works as above; `authorize` is **required** — admin operations read and destroy whole workspaces — and returns `boolean | Response` (no verdict form; there is no connection to stamp). It receives the operation name as `op: AdminOp` (`'stats' | 'export' | 'import' | 'reset' | 'disconnect'`), so a per-op policy — a read-only token that allows `stats` and `export` but not `reset` — is one `switch` away.
137
+
138
+ The endpoints, mirroring [Operations](/guide/operations):
139
+
140
+ | Route | Effect |
141
+ |---|---|
142
+ | `GET /admin/<workspaceId>/stats` | gauges + counters — rows, versions, live connections, db size |
143
+ | `GET /admin/<workspaceId>/export` | JSON snapshot of live rows (plus extension state) |
144
+ | `POST /admin/<workspaceId>/import` | replace state from a snapshot; live clients converge via reset poke |
145
+ | `POST /admin/<workspaceId>/reset` | wipe the workspace; new history under a fresh `backendId` |
146
+ | `POST /admin/<workspaceId>/disconnect` | kick or refresh live sessions (`{ principal?, clientId?, mode?, code?, reason? }`) |
147
+
148
+ ### bearerTokenAuth
149
+
150
+ `(token: (env: Env) => string | undefined) => authorize hook`
151
+
152
+ An `authorize` hook that checks `Authorization: Bearer <token>` against a secret from the env (`wrangler secret put ADMIN_TOKEN`), comparing in constant time. A missing or empty secret denies everything — an unset secret must fail closed, not open. Compatible with `createSyncFetch` too, for service-to-service sync clients.
153
+
154
+ ## workspaceAdmin
155
+
156
+ `(namespace: DurableObjectNamespace, workspaceId: string) => WorkspaceAdmin`
157
+
158
+ Typed admin surface over a workspace DO stub, for same-worker callers — app command handlers, billing webhooks — so server code never hand-builds admin HTTP requests against its own routes. It talks straight to the stub (no `createAdminFetch` in between), so it carries the caller's authority; external callers go through `createAdminFetch` and its authorize hook instead. A failing op throws with the operation name, HTTP status, and the DO's error message. See [Operations](/guide/operations#same-worker-callers).
159
+
160
+ - `stats()` — operational gauges and counters, designed to be scraped.
161
+ - `export()` — a JSON snapshot of every live row (plus extension state when one is registered), accepted back by `import`.
162
+ - `import(snapshot)` — replaces the workspace's rows atomically at a single new data version, resolving `{ imported, version }`. Live clients converge on their own: a reset poke re-bootstraps them in place, or — when the snapshot carries extension state — every socket is cycled with a refresh close instead.
163
+ - `reset()` — wipes the workspace and starts a new history under a fresh `backendId`, resolving `{ backendId }`. Also the one op a quarantined workspace still serves — the [recovery hatch](/guide/operations#reset-as-the-recovery-hatch).
164
+ - `disconnect(opts?)` — closes live sockets matching the selectors (`principal`, `clientId`, or neither for all sockets), resolving `{ disconnected }`. `mode: 'kick'` (default) closes permanently — the client stops reconnecting and calls `onFatal` with `code` (default 4403) and `reason` — while `'refresh'` closes with 4300 so the client reconnects through a fresh `authorize` run and picks up new stamps. See [revoking and refreshing](/guide/auth#revoking-and-refreshing-live-sessions).
165
+
166
+ ## EngineExtension
167
+
168
+ The binary-lane extension seam an add-on plugs into — [`@cf-sync/yjs/server`](/reference/yjs) is the canonical consumer. One config slot, types only: core imports nothing from any extension. `init(ctx)` runs on every wake inside initialization with the workspace's SQLite handle, a transaction wrapper, and the outbound delivery seam (`broadcast`/`send` route through core's per-socket delivery gate, so an extension cannot send to a socket core is already tearing down). `onBinaryMessage` receives every binary frame from a live socket — with the connection's auth stamps in its context — and must stay synchronous end-to-end, like every DO WebSocket handler. Optional hooks tie into the rest of the engine: `onAlarm`, `onExport`/`onImport` (round-trips extension state through admin export/import), `onReset`, and `onStats` (merged into the `stats` payload). Apps registering the shipped Yjs extension never touch this interface directly.
169
+
170
+ ## Custom routers
171
+
172
+ `encodeAuthStamps(stamps)` / `decodeAuthStamps(value)` and the `AUTH_HEADER` / `WORKSPACE_HEADER` constants exist for routers replacing `createSyncFetch`. The routers carry the authorize verdict's stamps (`{ principal?, context?, expiresAt? }`) to the DO in `AUTH_HEADER` as base64-encoded JSON, and name the workspace in `WORKSPACE_HEADER`. A custom router must reproduce the security-critical move: **strip any inbound `AUTH_HEADER` before setting its own**, so stamps cannot be spoofed from outside — the DO trusts whatever the router says. `encodeAuthStamps` serializes a verdict's stamps into the header value; `decodeAuthStamps` parses one back (the DO calls it at upgrade; a custom router only needs it to inspect its own header).
173
+
174
+ `rejectUpgrade(code, reason)` completes the seam: it accepts the upgrade and immediately closes it with the given code and reason — the browser-observable rejection the built-in routers use (a bare 403 is indistinguishable from a network error in a browser). A custom router should reject the same way.