@cardonjs/realtime-do 0.0.0-stage → 0.2.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matias Terradas
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,559 @@
1
- # Temporary Holding Version
1
+ # @cardonjs/realtime-do
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Real-time for Cardón apps on Cloudflare Durable Objects. A room holds hibernating WebSockets;
4
+ the API publishes small events to it after saving data; a reconnecting browser client receives
5
+ them and reloads what changed.
6
+
7
+ The WebSocket only signals "something changed". Events flow server → client and carry a hint
8
+ (ids), never the record itself. The database stays the source of truth: a client that
9
+ reconnects, or that missed events, reloads its state through the API.
10
+
11
+ - `defineRoom(options)` returns the Durable Object class to export from the Worker entry. It is
12
+ a plain class (no `cloudflare:workers` import, no RPC); the Worker talks to it through the
13
+ binding with internal `fetch` requests.
14
+ - `connectToRoom(namespace, room, request, options)` opens a socket from a route, after the
15
+ route authenticated the caller and authorized the room. Channels are chosen by the server.
16
+ - `realtime(namespace)` returns a `RealtimePublisher` (`publish`, `count`, `disconnect`,
17
+ `presence`) for the adapters factory.
18
+ - `@cardonjs/realtime-do/client`: `createRealtimeClient`, zero dependencies, for browsers.
19
+ - `@cardonjs/realtime-do/testing`: `memoryRealtime()`, an in-memory fake publisher.
20
+
21
+ Peer dependencies: `@cardonjs/core`. Types for `DurableObjectNamespace` and `DurableObjectState`
22
+ come from `@cloudflare/workers-types` (as in `@cardonjs/config/tsconfig.workers.json`). The client
23
+ needs only the DOM types.
24
+
25
+ For coding agents: `llms.txt`, shipped next to this README in the package, is a compact usage guide (public API, a minimal example, common mistakes).
26
+
27
+ ## Wrangler configuration
28
+
29
+ Bind the room class and create it with a migration (`new_sqlite_classes`: the room stores
30
+ only short-lived revocation markers, and new classes should use the SQLite backend, the only
31
+ one on the free plan):
32
+
33
+ ```toml
34
+ [[durable_objects.bindings]]
35
+ name = "BOARD_ROOMS"
36
+ class_name = "BoardRoom"
37
+
38
+ [[migrations]]
39
+ tag = "v1"
40
+ new_sqlite_classes = ["BoardRoom"]
41
+ ```
42
+
43
+ The connect route is rate limited per user with a
44
+ [rate limiting binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/)
45
+ (`period` is 10 or 60 seconds, and `workersRateLimiter` gets the same value):
46
+
47
+ ```toml
48
+ [[ratelimits]]
49
+ name = "CONNECT_LIMITER"
50
+ # Scoped to the Cloudflare account, not the Worker: unique per app, environment and limit.
51
+ namespace_id = "1301"
52
+ simple = { limit = 20, period = 60 }
53
+ ```
54
+
55
+ ## Worker
56
+
57
+ The example is a board app: members of a board see cards appear live. The room name is built
58
+ by the server from the board id (`board:<id>`), one Durable Object per board.
59
+
60
+ ```ts
61
+ import { getIdentity, requireAuth } from "@cardonjs/auth";
62
+ import {
63
+ type CardonEnv,
64
+ createApp,
65
+ created,
66
+ defineModule,
67
+ errorEnvelopeSchema,
68
+ ForbiddenError,
69
+ idSchema,
70
+ newId,
71
+ rateLimit,
72
+ rateLimitKeys,
73
+ successEnvelope,
74
+ workersRateLimiter,
75
+ } from "@cardonjs/core";
76
+ import { connectToRoom, defineRoom, realtime } from "@cardonjs/realtime-do";
77
+ import { createRoute, z } from "@hono/zod-openapi";
78
+
79
+ type Bindings = {
80
+ BOARD_ROOMS: DurableObjectNamespace;
81
+ CONNECT_LIMITER: RateLimit;
82
+ APP_ORIGIN: string;
83
+ DB: D1Database;
84
+ };
85
+ const adapters = (env: Bindings) => ({
86
+ auth: sessionCookieAuth(env), // your Authenticator: a same-site session cookie
87
+ boards: boardsRepository(env.DB), // your data access
88
+ live: realtime(env.BOARD_ROOMS),
89
+ connects: workersRateLimiter(env.CONNECT_LIMITER, { periodSeconds: 60 }),
90
+ });
91
+ type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
92
+
93
+ const boardParams = z.object({ boardId: idSchema });
94
+ const card = z.object({ id: z.string(), title: z.string() });
95
+ const errors = {
96
+ 403: {
97
+ description: "Not a member of the board",
98
+ content: { "application/json": { schema: errorEnvelopeSchema } },
99
+ },
100
+ };
101
+
102
+ const liveRoute = createRoute({
103
+ method: "get",
104
+ path: "/{boardId}/live",
105
+ tags: ["Boards"],
106
+ summary: "Open the board's live updates (WebSocket upgrade)",
107
+ // Per user, after the guard: saves the room wake-up and the membership query of each upgrade
108
+ // (the guard already ran; the app's global per-IP `rateLimit` is what bounds authentication).
109
+ middleware: rateLimit<AppEnv>({
110
+ name: "board-live",
111
+ limiter: (c) => c.var.adapters.connects,
112
+ key: rateLimitKeys.identity,
113
+ }),
114
+ request: { params: boardParams },
115
+ responses: {
116
+ 101: { description: "Switching to the WebSocket protocol" },
117
+ 400: {
118
+ description: "Not a WebSocket upgrade",
119
+ content: { "application/json": { schema: errorEnvelopeSchema } },
120
+ },
121
+ 429: {
122
+ description: "Too many connects, or too many connections",
123
+ content: { "application/json": { schema: errorEnvelopeSchema } },
124
+ },
125
+ ...errors,
126
+ },
127
+ });
128
+
129
+ const addCardRoute = createRoute({
130
+ method: "post",
131
+ path: "/{boardId}/cards",
132
+ tags: ["Boards"],
133
+ summary: "Add a card",
134
+ request: {
135
+ params: boardParams,
136
+ body: {
137
+ required: true,
138
+ content: { "application/json": { schema: z.object({ title: z.string().min(1).max(200) }) } },
139
+ },
140
+ },
141
+ responses: {
142
+ 201: {
143
+ description: "The new card",
144
+ content: { "application/json": { schema: successEnvelope(card) } },
145
+ },
146
+ ...errors,
147
+ },
148
+ });
149
+
150
+ const boardsModule = defineModule<AppEnv>({
151
+ name: "boards",
152
+ prefix: "/v1/boards",
153
+ routes: (app) => {
154
+ app.openapi(liveRoute, async (c) => {
155
+ const { boardId } = c.req.valid("param");
156
+ const identity = getIdentity(c); // requireAuth already ran: no session, no socket
157
+ // The app's own authorization of this room.
158
+ if (!(await c.var.adapters.boards.isMember(boardId, identity.id))) {
159
+ throw new ForbiddenError();
160
+ }
161
+ return connectToRoom(c.env.BOARD_ROOMS, `board:${boardId}`, c.req.raw, {
162
+ identity, // only id and kind reach the room
163
+ channels: ["cards"], // chosen by the server, never by the client
164
+ allowedOrigins: [c.env.APP_ORIGIN], // e.g. "https://app.example.com"
165
+ });
166
+ });
167
+
168
+ app.openapi(addCardRoute, async (c) => {
169
+ const { boardId } = c.req.valid("param");
170
+ const identity = getIdentity(c);
171
+ if (!(await c.var.adapters.boards.isMember(boardId, identity.id))) {
172
+ throw new ForbiddenError();
173
+ }
174
+ const saved = { id: newId(), title: c.req.valid("json").title };
175
+ await c.var.adapters.boards.addCard(boardId, saved);
176
+ // A signal after the data is saved: a failed publish must not fail the request.
177
+ c.executionCtx.waitUntil(
178
+ c.var.adapters.live
179
+ .publish(`board:${boardId}`, {
180
+ channel: "cards",
181
+ type: "card.created",
182
+ data: { id: saved.id },
183
+ })
184
+ .catch(() => c.var.logger.warn("realtime publish failed", { boardId })),
185
+ );
186
+ return created(c, saved);
187
+ });
188
+ },
189
+ });
190
+
191
+ const app = createApp(adapters, {
192
+ guard: requireAuth<AppEnv>({ authenticator: (c) => c.var.adapters.auth }),
193
+ }).register(boardsModule);
194
+
195
+ // The Durable Object class, exported under the `class_name` of the Wrangler config.
196
+ export const BoardRoom = defineRoom<Bindings>();
197
+
198
+ export default app;
199
+ ```
200
+
201
+ `connectToRoom` throws the core errors, so the app's error handler answers with the usual
202
+ envelope:
203
+
204
+ | Case | Error |
205
+ | --- | --- |
206
+ | Not a `GET` with `Upgrade: websocket` | `ValidationError` (400) |
207
+ | `Origin` missing or not exactly in `allowedOrigins` | `ForbiddenError` (403) |
208
+ | Room full, the identity has too many connections, or it was disconnected less than 60 s ago | `RateLimitedError` (429) |
209
+
210
+ The route's `rateLimit` (from `@cardonjs/core`) runs before the handler, after the guard: more
211
+ than 20 connects a minute from one user also answer `429` (with `Retry-After`), before the
212
+ membership check or the room are reached. It runs after the guard, so it does not bound the
213
+ cost of authentication; the app's `rateLimit` option (per IP, before the guard) does. The
214
+ binding counts per Cloudflare location and is approximate, which is enough to stop a reconnect
215
+ loop or a script; the room's own limits above stay exact.
216
+
217
+ The `Origin` check matters: browsers send the session cookie on a cross-site WebSocket
218
+ upgrade, so without it any site could open a socket as the user (cross-site WebSocket
219
+ hijacking). `allowedOrigins` is required and holds exact origins (`https://host[:port]`); an
220
+ empty list or `"*"` throws when the route runs. `http:` origins are accepted only for local
221
+ development (`localhost`, `*.localhost`, `127.0.0.1`, `[::1]`); any other `http:` origin
222
+ throws.
223
+
224
+ **Authorize in the route.** The membership check above is what keeps a user out of a room.
225
+ `onConnect` (see [Room options](#room-options)) runs after the socket is accepted and is not a
226
+ gate: if it throws, the error is logged and the connection stays.
227
+
228
+ The room trusts what the Worker sends: it is reachable only through the binding, and the connect
229
+ request is rebuilt by `connectToRoom` (no client header reaches it). **Never forward a client
230
+ request to the room stub** (`stub.fetch(c.req.raw)`, or any route that proxies to it): the room
231
+ would trust whatever that request says, identity included. Only `connectToRoom` and
232
+ `realtime()` may call it.
233
+
234
+ Authentication happens in the route, once per connection; `maxConnectionAgeSeconds` makes
235
+ clients come back through the route to authenticate again. After removing a user from the
236
+ board, `disconnect` closes their sockets on that room and shuts the door for a moment:
237
+
238
+ ```ts
239
+ await c.var.adapters.live.disconnect(`board:${boardId}`, { id: removedUserId, kind: "user" });
240
+ ```
241
+
242
+ It closes the identity's open sockets with 4001 and, for the next 60 seconds, the room refuses
243
+ that identity's connects (429). That covers a connect that passed the membership check just
244
+ before the removal and reaches the room just after it. If the user is added back within those
245
+ 60 seconds, their client reconnects once the window has passed (it retries with backoff).
246
+
247
+ ## Room options
248
+
249
+ ```ts
250
+ export const BoardRoom = defineRoom<Bindings>({
251
+ maxConnections: 1000, // per room
252
+ maxConnectionsPerIdentity: 5,
253
+ maxEventBytes: 16_384, // serialized frame, UTF-8 bytes
254
+ maxConnectionAgeSeconds: 3600,
255
+ // Optional hooks, also `onConnect`. They get
256
+ // `{ room, identity, channels, connectedAt, connections, identityConnections, env }`;
257
+ // `connections` is the open count after the change: 0 means the room is now empty.
258
+ onDisconnect: async ({ room, connections, env }) => {
259
+ if (connections === 0) await markBoardIdle(env.DB, room); // your code
260
+ },
261
+ });
262
+ ```
263
+
264
+ | Option | Default | Range |
265
+ | --- | --- | --- |
266
+ | `maxConnections` | 1000 | 1 to 32 768 |
267
+ | `maxConnectionsPerIdentity` | 5 (or `maxConnections` if smaller) | 1 to `maxConnections` |
268
+ | `maxEventBytes` | 16 384 | 256 to 1 048 576 |
269
+ | `maxConnectionAgeSeconds` | 3600 | 1 to 604 800 |
270
+
271
+ Options are checked when `defineRoom` runs; a bad value throws a `TypeError`.
272
+
273
+ - **Caps** count every socket the room still holds, open or closing: a client that never
274
+ answers a close frame keeps its slot until its connection ends, so it cannot pile up sockets.
275
+ `count()` and the hooks' `connections` count open sockets only, so they can be lower than
276
+ what the caps see.
277
+ - **Age**: each socket gets a random age between 90 % and 100 % of
278
+ `maxConnectionAgeSeconds` (never more), so sockets opened together do not expire together.
279
+ - **`onConnect`** runs after the socket is accepted and before the 101 response is returned,
280
+ so keep it short. It is not a gate: authorize in the route.
281
+ - **`onDisconnect`** runs once per socket, when its close completes. A client that never
282
+ answers the close frame delays it until its connection ends. `connectedAt` (a `Date`) tells
283
+ how long the connection lasted; `channels` is a frozen copy of its channels.
284
+ - **`identityConnections`**, in both hooks, is the open connections of the hook's identity
285
+ after the change: 1 in `onConnect` is its first connection in the room, 0 in `onDisconnect`
286
+ means its last one closed. The same id under another `kind` is counted apart.
287
+ - A hook that throws is logged (hook name and error name only: no identity, no message) and
288
+ never reaches clients or breaks the room.
289
+
290
+ ## Publishing
291
+
292
+ `realtime(env.BOARD_ROOMS)` is synchronous and does no I/O, so it is safe in the adapters
293
+ factory; it throws right away (with the Wrangler fix) when the value is not a Durable Object
294
+ namespace. Business logic depends on the `RealtimePublisher` type, not on the binding.
295
+
296
+ - `publish(room, event)` sends the event to every connection on `event.channel` and resolves
297
+ with `{ delivered }` (0 when nobody is connected). Arguments are validated before any call to
298
+ the room; an invalid event, or one larger than the room's `maxEventBytes`, is a `TypeError`.
299
+ - `count(room)` resolves with the open connections (expired ones are closed first and not
300
+ counted).
301
+ - `disconnect(room, { id, kind })` closes that identity's open connections in the room with
302
+ 4001, refuses its connects there for 60 seconds, and resolves with `{ closed }`.
303
+ - `presence(room, options?)` lists who is connected (see [Presence](#presence)).
304
+
305
+ Names and events:
306
+
307
+ - Room and channel: `^[A-Za-z0-9][A-Za-z0-9:._-]{0,127}$`. 1 to 8 channels per connection, no
308
+ repeats.
309
+ - Event `type`: `^[a-z0-9][a-z0-9._:-]{0,63}$`, e.g. `"card.created"`.
310
+ - Event `data`: optional, JSON only (no `undefined`, functions, non-finite numbers, cycles or
311
+ class instances). Keep it to ids: the client reloads the record.
312
+ - Identity id: 1 to 128 characters (UTF-16 code units), well-formed (no lone surrogates), no
313
+ control characters. The same id with another `kind` is another identity. The room never
314
+ puts the id in a tag or a storage key: it uses a SHA-256 of `kind:id`.
315
+
316
+ Frame sent to clients: `{"channel":"cards","type":"card.created","data":{"id":"…"}}` (`data`
317
+ omitted when absent).
318
+
319
+ ## Presence
320
+
321
+ `presence(room, options?)` tells the server who is connected to a room right now, since when,
322
+ and when each connection last answered a heartbeat. It reads what the room already holds (each
323
+ socket's attachment and the runtime's timestamp of its last auto-answered `"ping"`), so it
324
+ stores nothing and costs nothing while the room hibernates.
325
+
326
+ ```ts
327
+ // In a route of the boards module, after the membership check:
328
+ const { connections, total } = await c.var.adapters.live.presence(`board:${boardId}`, {
329
+ activeWithinSeconds: 60, // the browser client pings every 25 s
330
+ limit: 1000, // connections, not people: one user may hold several
331
+ });
332
+ // People only (services connect too, and one may share an id with a user), each once.
333
+ const online = [
334
+ ...new Set(
335
+ connections
336
+ .filter((connection) => connection.identity.kind === "user")
337
+ .map((connection) => connection.identity.id),
338
+ ),
339
+ ];
340
+ // More matches than `limit`: the list was cut, so show "1000+" rather than claim it is everyone.
341
+ const complete = total === connections.length;
342
+ ```
343
+
344
+ ```ts
345
+ async function isOnline(live: RealtimePublisher, room: string, userId: string) {
346
+ const { total } = await live.presence(room, {
347
+ identity: { id: userId, kind: "user" },
348
+ activeWithinSeconds: 60,
349
+ limit: 1,
350
+ });
351
+ return total > 0;
352
+ }
353
+ ```
354
+
355
+ `isOnline` answers a yes/no about any id it is given, so a route built on it can be used as a
356
+ probe. The route must authorize both the room (the caller is a member of the board) and the
357
+ caller's right to see that specific identity (for example, the target is a member of the same
358
+ board, or one of the caller's contacts). Never take the target id from the client without that
359
+ check. Join and leave signals (below) reveal timing as well: whoever receives them learns when
360
+ people come and go.
361
+
362
+ It resolves with `{ connections, total }`:
363
+
364
+ - `connections`: open connections, oldest `connectedAt` first, each
365
+ `{ identity: { id, kind }, channels, connectedAt, lastSeenAt }` (dates are `Date`; everything
366
+ is frozen). `lastSeenAt` is the last `"ping"` the room answered, or `connectedAt` when there was
367
+ none yet.
368
+ - `total`: how many matched before `limit`, so you know when the list was cut.
369
+
370
+ | Option | Default | Range | Effect |
371
+ | --- | --- | --- | --- |
372
+ | `identity` | none | `{ id, kind }` | only that identity's connections |
373
+ | `channel` | none | a channel name | only connections on that channel |
374
+ | `activeWithinSeconds` | none | 1 to 86 400 | only connections seen in the last N seconds |
375
+ | `limit` | 100 | 1 to 1000 | at most this many connections |
376
+
377
+ `identity` and `channel` together give their intersection. Arguments are validated before the
378
+ call (a `TypeError` that never includes the values) and again by the room. Expired connections
379
+ are closed first and not listed, like `count`; closing sockets are not listed either, nor a
380
+ socket whose stored data cannot be read back.
381
+
382
+ Cost: `identity` narrows the listing to that identity's sockets (through its tag), at most
383
+ `maxConnectionsPerIdentity`; `channel` to that channel's. Before listing, the room runs its lazy
384
+ expiry, which skips work while no socket can have expired yet but sweeps every socket once after
385
+ the room wakes up or when one may have expired. So a narrow query is usually small, and any query
386
+ is bounded by the room's `maxConnections`.
387
+
388
+ - **"Online" is your filter.** The room keeps no online flag: `activeWithinSeconds` decides.
389
+ The browser client pings every `pingIntervalMs` (25 s by default), so 60 tolerates one lost
390
+ ping. A dead connection stays listed, with an old `lastSeenAt`, until the runtime drops it
391
+ (the room has no timer), so filter with `activeWithinSeconds` when it matters.
392
+ - **Verified on Cloudflare** (2026-11-19, a deployed project generated from the starter): a
393
+ `"ping"` answered while the room hibernates moves `lastSeenAt`, and a connection that stops
394
+ pinging drops out of an `activeWithinSeconds` window.
395
+ - **Other clients must ping.** A client that does not use `@cardonjs/realtime-do/client` must
396
+ send the text `"ping"` regularly to count as active; any other message closes the socket
397
+ (1008).
398
+ - **Authorize first; minimize ids and timestamps.** Presence returns identity ids, and
399
+ `connectedAt` / `lastSeenAt` are activity data (when someone is around). It is reachable only
400
+ through the binding, but a route that exposes it must authorize the caller (above: the
401
+ membership check), and should not send other people's ids or times to clients without a
402
+ reason. Often a count or a yes/no (`isOnline`) is enough; when times are needed, coarsen them
403
+ (e.g. "online", "seen in the last hour").
404
+ - One room per query; for several rooms, query each.
405
+
406
+ The framework broadcasts nothing about presence. To tell clients that someone joined or left,
407
+ publish from the hooks when an identity's presence actually changes; a signal without ids is
408
+ enough, and clients reload through your authorized route:
409
+
410
+ ```ts
411
+ const presenceChanged = (env: Bindings, room: string) =>
412
+ realtime(env.BOARD_ROOMS)
413
+ .publish(room, { channel: "presence", type: "presence.changed" })
414
+ .catch(() => undefined); // a failed signal must not break the room
415
+
416
+ export const BoardRoom = defineRoom<Bindings>({
417
+ // Only when the identity's presence changes: its first connection, and after its last one.
418
+ // A second tab, or a reconnect while the old socket is still open, signals nothing.
419
+ onConnect: async ({ room, identityConnections, env }) => {
420
+ if (identityConnections === 1) await presenceChanged(env, room);
421
+ },
422
+ onDisconnect: async ({ room, identityConnections, env }) => {
423
+ if (identityConnections === 0) await presenceChanged(env, room);
424
+ },
425
+ });
426
+ ```
427
+
428
+ Connections that should see the signal join the `presence` channel in `connectToRoom`.
429
+ `onConnect` runs before the 101 response, so the publish adds to the connect's latency.
430
+ `identityConnections` counts the identity's open connections after the change (closing sockets
431
+ are not counted, as with `connections`).
432
+
433
+ Each signal makes every listening client call your route: with N clients, one join is N
434
+ requests and N `presence` calls on the same room, which handles one request at a time. A member
435
+ that loops connect and close, or a phone reconnecting on a flaky network, still signals on every
436
+ round; the connect route's rate limit (20 connects a minute per user, above) is what bounds that
437
+ churn. Keep the rest cheap:
438
+
439
+ - **Coalesce on the client.** Wait a few seconds, with jitter, before reloading, and reload once
440
+ per burst (example below), so clients do not all ask at the same moment.
441
+ - **Rate limit the presence route** per user, like the connect route. It may also cache its
442
+ answer per room for a few seconds (after the authorization check, keyed by room, and only
443
+ when the answer is the same for every caller allowed to see it).
444
+ - **Prefer narrow queries**: `identity` (a yes/no) or `total` with a small `limit`, rather than
445
+ listing the whole room.
446
+
447
+ ```ts
448
+ let pending: ReturnType<typeof setTimeout> | undefined;
449
+ const presenceClient = createRealtimeClient({
450
+ url: `/v1/boards/${boardId}/live`,
451
+ onEvent: (event) => {
452
+ if (event.type !== "presence.changed" || pending !== undefined) return;
453
+ // One reload per burst, 2 to 5 seconds later, spread across clients.
454
+ pending = setTimeout(
455
+ () => {
456
+ pending = undefined;
457
+ void reloadOnline(boardId);
458
+ },
459
+ 2000 + Math.random() * 3000,
460
+ );
461
+ },
462
+ onResync: () => reloadOnline(boardId),
463
+ });
464
+ ```
465
+
466
+ ## Browser client
467
+
468
+ ```ts
469
+ import { createRealtimeClient } from "@cardonjs/realtime-do/client";
470
+
471
+ const client = createRealtimeClient({
472
+ url: `/v1/boards/${boardId}/live`, // same-site: the session cookie goes with the upgrade
473
+ onEvent: (event) => {
474
+ if (event.channel === "cards") void reloadCards(boardId);
475
+ },
476
+ // Called on every reconnect and on each fallback poll while disconnected.
477
+ onResync: () => reloadBoard(boardId),
478
+ onStatus: (status) => showConnectionStatus(status),
479
+ });
480
+
481
+ // When leaving the page:
482
+ client.close();
483
+ ```
484
+
485
+ - A path is resolved against `location` (`https:` → `wss:`). `wss:` is required, except from
486
+ an `http:` page on a local development host (`localhost`, `*.localhost`, `127.0.0.1`,
487
+ `[::1]`) to a local host.
488
+ - Statuses: `"connecting"` → `"open"`; `"reconnecting"` while waiting to reconnect;
489
+ `"closed"` after `close()` or a protocol violation.
490
+ - Reconnects with exponential backoff and full jitter between `minBackoffMs` (1000) and
491
+ `maxBackoffMs` (30 000); the attempt counter resets after a connection stays open for 10 s.
492
+ - Sends `"ping"` every `pingIntervalMs` (25 000); without `"pong"` within `pongTimeoutMs`
493
+ (10 000) it closes the socket and reconnects. The room answers pings without waking up, and
494
+ each answered ping is what `presence` reports as `lastSeenAt`.
495
+ - While disconnected, calls `onResync` every `pollIntervalMs` (30 000; 0 disables it).
496
+ - Frames that are not well-formed events are dropped. Errors thrown (or rejections) from
497
+ `onEvent`, `onResync` and `onStatus` never break the client.
498
+ - `close()` stops the socket and every timer and reports `"closed"`; after it returns no
499
+ callback fires, also when it is called from inside `onEvent`, `onResync` or `onStatus`.
500
+ - **Stop on 401/403.** The client cannot tell a revoked session from a network failure. If
501
+ `onResync` gets a 401 or 403 from your API, call `client.close()` (and send the user to sign
502
+ in); otherwise the client keeps retrying with backoff.
503
+ - **No tokens in the URL.** Do not put a session token or API key in the socket URL's query
504
+ string: URLs end up in logs and history. The upgrade is authenticated by the same-site
505
+ session cookie.
506
+
507
+ ## Limits and close codes
508
+
509
+ | Close code | Meaning | Client |
510
+ | --- | --- | --- |
511
+ | 1008 | Protocol violation: the client sent something other than `"ping"` | stops (`"closed"`) |
512
+ | 4000 | Connection past its age (see `maxConnectionAgeSeconds`): authenticate again | reconnects after a random delay below `minBackoffMs` |
513
+ | 4001 | Disconnected by the server (`disconnect`) | reconnects with backoff; the route decides |
514
+
515
+ Connection age is checked lazily (there is no alarm): an expired socket is closed the next time
516
+ the room handles a connect, a publish, a count or a presence query.
517
+
518
+ Cloudflare limits the room is built within (checked against workerd): 10 tags per hibernating
519
+ WebSocket (up to 8 channels plus 1 identity tag of 74 ASCII characters), 256 bytes per tag,
520
+ 16 384 bytes per attachment, 2 048 characters for the auto-response request and response.
521
+
522
+ The room keeps nothing about a connection in instance memory: channels and the hashed identity
523
+ are the socket's tags; the room name, identity, channels, connection time and expiry are its
524
+ attachment; revocation markers are in Durable Object storage. Roles and email are not stored
525
+ (they would go stale). The runtime can evict an idle room while its sockets stay open; the
526
+ next event builds a new instance that finds them again.
527
+
528
+ ## Testing (`@cardonjs/realtime-do/testing`)
529
+
530
+ ```ts
531
+ import { memoryRealtime } from "@cardonjs/realtime-do/testing";
532
+
533
+ const live = memoryRealtime();
534
+ // ...run a route with `live` as the `live` adapter, then:
535
+ expect(live.published).toEqual([
536
+ { room: `board:${boardId}`, event: { channel: "cards", type: "card.created", data: { id } } },
537
+ ]);
538
+ ```
539
+
540
+ `memoryRealtime()` validates with the same rules and records `published`, `disconnected`
541
+ (`{ room, identity: { id, kind } }`) and `presenceQueries` (`{ room, query }`, the validated
542
+ query with `limit` filled in), so a test can check that a forbidden path never asked for
543
+ presence, or that a route scoped its query (`identity`, `limit`); `clear()` empties them.
544
+ There are no connections: `count(room)` and `publish`'s `delivered` return what `setCount(room,
545
+ n)` set (default 0). `presence(room, options)` lists what `setPresence(room, connections)` set
546
+ (`{ identity, channels, connectedAt, lastSeenAt? }[]`, `lastSeenAt` defaulting to `connectedAt`;
547
+ times after `Date.now()` are a `TypeError`, as the room never reports them), with the room's
548
+ filters, order and limit; `activeWithinSeconds` is measured against `Date.now()`,
549
+ so fake timers apply. Test-only.
550
+
551
+ ## Not covered
552
+
553
+ - **Cross-origin clients.** Browsers authenticate the upgrade with a same-site cookie; there are
554
+ no tokens in URLs (do not add any to the query string). A one-time ticket for clients on another site is added when a project needs
555
+ it.
556
+ - Client → server messages (other than the keep-alive ping), message history or replay,
557
+ subscriptions after connect, binary frames, alarms.
558
+ - Presence broadcast by the framework, presence across rooms in one query, custom
559
+ per-connection metadata, and closing idle connections on a timer.
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Reconnecting browser client for a room. Zero dependencies and no Workers types: it runs in the
3
+ * browser. Import it from `@cardonjs/realtime-do/client`.
4
+ *
5
+ * The socket only signals "something changed": events are hints, and `onResync` reloads the
6
+ * state from the API after every reconnect and on each fallback poll while disconnected.
7
+ */
8
+ import { type RealtimeEvent } from "./validation.js";
9
+ export type { JsonValue, RealtimeEvent } from "./validation.js";
10
+ export type ConnectionStatus = "connecting" | "open" | "reconnecting" | "closed";
11
+ export interface RealtimeClientOptions {
12
+ /** `wss://…`, or a path resolved against `location` (`/v1/boards/1/live`). */
13
+ readonly url: string;
14
+ onEvent(event: RealtimeEvent): void;
15
+ /** Reload state: called on every reconnect and on each fallback poll while disconnected. */
16
+ onResync(): void | Promise<void>;
17
+ /** Called on every status change (not for the initial `"connecting"`). */
18
+ onStatus?(status: ConnectionStatus): void;
19
+ /** Default 30 000; 0 disables fallback polling. */
20
+ readonly pollIntervalMs?: number;
21
+ /** Default 25 000. */
22
+ readonly pingIntervalMs?: number;
23
+ /** Default 10 000. */
24
+ readonly pongTimeoutMs?: number;
25
+ /** Default 1000. */
26
+ readonly minBackoffMs?: number;
27
+ /** Default 30 000. */
28
+ readonly maxBackoffMs?: number;
29
+ /** Injectable for tests. Default: the global `WebSocket`. */
30
+ readonly WebSocket?: typeof WebSocket;
31
+ /** Injectable for tests. Default: `Math.random`. */
32
+ readonly random?: () => number;
33
+ }
34
+ export interface RealtimeClient {
35
+ readonly status: ConnectionStatus;
36
+ /**
37
+ * Stops timers and the socket, then reports `"closed"`. Once it returns, no callback fires
38
+ * again, also when it is called from inside `onEvent`, `onResync` or `onStatus`.
39
+ */
40
+ close(): void;
41
+ }
42
+ /**
43
+ * Opens the socket and keeps it open: exponential backoff with full jitter between
44
+ * `minBackoffMs` and `maxBackoffMs` (reset once a connection stays open for 10 s), `"ping"`
45
+ * every `pingIntervalMs` with a `pongTimeoutMs` deadline, and fallback polling through
46
+ * `onResync` while disconnected.
47
+ *
48
+ * Close codes: 1008 stops for good (status `"closed"`); 4000 reconnects after a random delay
49
+ * below `minBackoffMs` (sockets that expire together do not come back together); anything
50
+ * else reconnects with backoff.
51
+ *
52
+ * Call `close()` when the API refuses the user (e.g. `onResync` gets a 401 or 403): the
53
+ * client cannot tell, and keeps retrying otherwise.
54
+ */
55
+ export declare function createRealtimeClient(options: RealtimeClientOptions): RealtimeClient;
56
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAoC,KAAK,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEvF,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,MAAM,gBAAgB,GAAG,YAAY,GAAG,MAAM,GAAG,cAAc,GAAG,QAAQ,CAAC;AAEjF,MAAM,WAAW,qBAAqB;IACpC,8EAA8E;IAC9E,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI,CAAC;IACpC,4FAA4F;IAC5F,QAAQ,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACjC,0EAA0E;IAC1E,QAAQ,CAAC,CAAC,MAAM,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAC1C,mDAAmD;IACnD,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC,sBAAsB;IACtB,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC,sBAAsB;IACtB,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,oBAAoB;IACpB,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,sBAAsB;IACtB,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,6DAA6D;IAC7D,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,SAAS,CAAC;IACtC,oDAAoD;IACpD,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;CAChC;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,MAAM,EAAE,gBAAgB,CAAC;IAClC;;;OAGG;IACH,KAAK,IAAI,IAAI,CAAC;CACf;AA4GD;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,cAAc,CAiLnF"}