@cardonjs/realtime-do 0.0.0-stage → 0.3.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,88 @@
1
+ /**
2
+ * Presence: who is connected to a room, since when, and when the room last answered their
3
+ * `"ping"`. The query and the selection (filters, order, limit) are shared by the room, the
4
+ * publisher and the fake, so the three agree. Every failure is a `TypeError` whose message never
5
+ * includes the value (identity ids are personal data).
6
+ */
7
+ import { validIdentity } from "./protocol.js";
8
+ import { assertValidChannel, assertValidChannels } from "./validation.js";
9
+ export const DEFAULT_PRESENCE_LIMIT = 100;
10
+ export const MAX_PRESENCE_LIMIT = 1000;
11
+ export const MAX_ACTIVE_WITHIN_SECONDS = 86_400;
12
+ function integerIn(name, value, min, max) {
13
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
14
+ throw new TypeError(`realtime: presence ${name} must be an integer from ${min} to ${max}.`);
15
+ }
16
+ return value;
17
+ }
18
+ /** Validates presence options (`undefined` means none) and returns a frozen query. */
19
+ export function validPresenceQuery(options) {
20
+ if (options === undefined)
21
+ return Object.freeze({ limit: DEFAULT_PRESENCE_LIMIT });
22
+ if (typeof options !== "object" || options === null || Array.isArray(options)) {
23
+ throw new TypeError("realtime: presence options must be an object.");
24
+ }
25
+ const { identity, channel, activeWithinSeconds, limit } = options;
26
+ const query = {
27
+ limit: limit === undefined
28
+ ? DEFAULT_PRESENCE_LIMIT
29
+ : integerIn("limit", limit, 1, MAX_PRESENCE_LIMIT),
30
+ };
31
+ if (identity !== undefined)
32
+ query.identity = validIdentity(identity);
33
+ if (channel !== undefined) {
34
+ assertValidChannel(channel);
35
+ query.channel = channel;
36
+ }
37
+ if (activeWithinSeconds !== undefined) {
38
+ query.activeWithinSeconds = integerIn("activeWithinSeconds", activeWithinSeconds, 1, MAX_ACTIVE_WITHIN_SECONDS);
39
+ }
40
+ return Object.freeze(query);
41
+ }
42
+ /** True when `value` is a usable epoch-milliseconds time. */
43
+ export function isTime(value) {
44
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
45
+ }
46
+ /**
47
+ * Applies the query to the connections: filters, oldest first (a stable sort, so ties keep the
48
+ * input order), then `limit`. `total` counts the matches before `limit`.
49
+ */
50
+ export function selectPresence(records, query, now) {
51
+ const since = query.activeWithinSeconds === undefined
52
+ ? Number.NEGATIVE_INFINITY
53
+ : now - query.activeWithinSeconds * 1000;
54
+ const { identity, channel } = query;
55
+ const matches = records
56
+ .filter((record) => (identity === undefined ||
57
+ (record.identity.id === identity.id && record.identity.kind === identity.kind)) &&
58
+ (channel === undefined || record.channels.includes(channel)) &&
59
+ record.lastSeenAt >= since)
60
+ .sort((a, b) => a.connectedAt - b.connectedAt);
61
+ return { records: matches.slice(0, query.limit), total: matches.length };
62
+ }
63
+ /** The public, frozen form of a record. */
64
+ export function presenceConnection(record) {
65
+ return Object.freeze({
66
+ identity: Object.freeze({ id: record.identity.id, kind: record.identity.kind }),
67
+ channels: Object.freeze([...record.channels]),
68
+ connectedAt: new Date(record.connectedAt),
69
+ lastSeenAt: new Date(record.lastSeenAt),
70
+ });
71
+ }
72
+ /**
73
+ * Parses one entry of the room's answer. Throws a `TypeError` (without the value) when it is not
74
+ * well-formed.
75
+ */
76
+ export function presenceRecord(value) {
77
+ if (typeof value !== "object" || value === null) {
78
+ throw new TypeError("realtime: a presence entry must be an object.");
79
+ }
80
+ const { identity, channels, connectedAt, lastSeenAt } = value;
81
+ const valid = validIdentity(identity);
82
+ assertValidChannels(channels);
83
+ if (!isTime(connectedAt) || !isTime(lastSeenAt) || lastSeenAt < connectedAt) {
84
+ throw new TypeError("realtime: a presence entry must hold valid times.");
85
+ }
86
+ return { identity: valid, channels: [...channels], connectedAt, lastSeenAt };
87
+ }
88
+ //# sourceMappingURL=presence.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"presence.js","sourceRoot":"","sources":["../src/presence.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,O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AI,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,UAAU,GAAG,WAAW,EAAE,CAAC;QAC5E,MAAM,IAAI,SAAS,CAAC,mDAAmD,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,GAAG,QAAQ,CAAC,EAAE,WAAW,EAAE,UAAU,EAAE,CAAC;AAC/E,CAAC"}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The internal protocol between the Worker-side helpers (`connectToRoom`, `realtime`) and the
3
+ * room. Requests travel only through the Durable Object binding, so the room trusts what they
4
+ * carry; it still validates it, because a malformed value must never reach a socket tag.
5
+ */
6
+ /**
7
+ * Who holds a connection. Roles and email are not stored: they would go stale. `"guest"` is a
8
+ * caller without an account, e.g. the holder of an access token (`id`: the token's record id).
9
+ */
10
+ export interface RoomIdentity {
11
+ readonly id: string;
12
+ readonly kind: "user" | "service" | "guest";
13
+ }
14
+ /** Base URL of the internal requests. Never leaves the binding. */
15
+ export declare const INTERNAL_ORIGIN = "https://realtime-do.internal";
16
+ export declare const PATH: {
17
+ readonly connect: "/connect";
18
+ readonly publish: "/publish";
19
+ readonly count: "/count";
20
+ readonly disconnect: "/disconnect";
21
+ /** POST `{ query }` (see `validPresenceQuery`); answers `{ connections, total }`, times in ms. */
22
+ readonly presence: "/presence";
23
+ /**
24
+ * POST `{ room, identity, channels, ttlSeconds, connectionExpiresAt? }` (epoch ms); answers
25
+ * `{ ticket, expiresAt }` once (epoch ms), 429 over the caps or during a revocation window.
26
+ */
27
+ readonly ticket: "/ticket";
28
+ /**
29
+ * GET upgrade with `{ room, ticket }` in `CONNECT_HEADER`; consumes the ticket, then connects
30
+ * like `connect` with the stored identity and channels. 401 for any ticket failure.
31
+ */
32
+ readonly ticketConnect: "/ticket-connect";
33
+ };
34
+ /**
35
+ * Carries the connect parameters: JSON with everything outside printable ASCII escaped
36
+ * (`asciiJson`), because header values are bytes and a GET upgrade has no body.
37
+ */
38
+ export declare const CONNECT_HEADER = "x-cardon-realtime-connect";
39
+ /** Close codes. 1008: protocol violation; 4000: re-authenticate; 4001: closed by the server. */
40
+ export declare const CLOSE_PROTOCOL = 1008;
41
+ export declare const CLOSE_REAUTHENTICATE = 4000;
42
+ export declare const CLOSE_DISCONNECTED = 4001;
43
+ /** JSON with every character outside printable ASCII escaped, so it is a valid header value. */
44
+ export declare function asciiJson(value: unknown): string;
45
+ /**
46
+ * The socket tag of an identity, also the key of its revocation marker: `#identity:` + hex
47
+ * SHA-256 of `kind:id`. Fixed length (74 ASCII characters) and opaque, so a raw id never
48
+ * reaches a tag, a runtime error message or a log, and the same id under two kinds is two
49
+ * identities. Tags starting with `#` cannot collide with channels (letter or digit first).
50
+ */
51
+ export declare function identityTag(identity: RoomIdentity): Promise<string>;
52
+ /** The start of every ticket's storage key (see `ticketKey`). */
53
+ export declare const TICKET_KEY_PREFIX = "#ticket:";
54
+ /**
55
+ * The storage key of a pending ticket: `#ticket:` + hex SHA-256 of the ticket. The ticket itself
56
+ * is never stored; with 256 random bits a plain hash cannot be reversed or guessed.
57
+ */
58
+ export declare function ticketKey(ticket: string): Promise<string>;
59
+ /** The start of every identity tag (see `identityTag`). */
60
+ export declare const IDENTITY_TAG_PREFIX = "#identity:";
61
+ export declare function assertValidIdentityId(id: unknown): asserts id is string;
62
+ /** A frozen copy holding only `id` and `kind`. */
63
+ export declare function validIdentity(identity: unknown): RoomIdentity;
64
+ /**
65
+ * Fails fast when the value is not a Durable Object namespace binding (for example `env.ROOMS`
66
+ * is `undefined` because the binding is missing). Never includes the value.
67
+ */
68
+ export declare function assertNamespace(namespace: unknown, caller: string): asserts namespace is DurableObjectNamespace;
69
+ export declare function roomStub(namespace: DurableObjectNamespace, room: string): DurableObjectStub;
70
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;GAIG;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AE,OAAO,EAClB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,SAAS,IAAI,sBAAsB,CAY7C;AAED,wBAAgB,QAAQ,CAAC,SAAS,EAAE,sBAAsB,EAAE,IAAI,EAAE,MAAM,GAAG,iBAAiB,CAE3F"}
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The internal protocol between the Worker-side helpers (`connectToRoom`, `realtime`) and the
3
+ * room. Requests travel only through the Durable Object binding, so the room trusts what they
4
+ * carry; it still validates it, because a malformed value must never reach a socket tag.
5
+ */
6
+ /** Base URL of the internal requests. Never leaves the binding. */
7
+ export const INTERNAL_ORIGIN = "https://realtime-do.internal";
8
+ export const PATH = {
9
+ connect: "/connect",
10
+ publish: "/publish",
11
+ count: "/count",
12
+ disconnect: "/disconnect",
13
+ /** POST `{ query }` (see `validPresenceQuery`); answers `{ connections, total }`, times in ms. */
14
+ presence: "/presence",
15
+ /**
16
+ * POST `{ room, identity, channels, ttlSeconds, connectionExpiresAt? }` (epoch ms); answers
17
+ * `{ ticket, expiresAt }` once (epoch ms), 429 over the caps or during a revocation window.
18
+ */
19
+ ticket: "/ticket",
20
+ /**
21
+ * GET upgrade with `{ room, ticket }` in `CONNECT_HEADER`; consumes the ticket, then connects
22
+ * like `connect` with the stored identity and channels. 401 for any ticket failure.
23
+ */
24
+ ticketConnect: "/ticket-connect",
25
+ };
26
+ /**
27
+ * Carries the connect parameters: JSON with everything outside printable ASCII escaped
28
+ * (`asciiJson`), because header values are bytes and a GET upgrade has no body.
29
+ */
30
+ export const CONNECT_HEADER = "x-cardon-realtime-connect";
31
+ /** Close codes. 1008: protocol violation; 4000: re-authenticate; 4001: closed by the server. */
32
+ export const CLOSE_PROTOCOL = 1008;
33
+ export const CLOSE_REAUTHENTICATE = 4000;
34
+ export const CLOSE_DISCONNECTED = 4001;
35
+ const MAX_IDENTITY_ID = 128;
36
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it rejects.
37
+ const CONTROL = /[\u0000-\u001f\u007f]/;
38
+ /** A lone surrogate, i.e. not well-formed UTF-16 (`isWellFormed()`, which ES2022 lacks). */
39
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
40
+ /** JSON with every character outside printable ASCII escaped, so it is a valid header value. */
41
+ export function asciiJson(value) {
42
+ return JSON.stringify(value).replace(/[^\x20-\x7e]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
43
+ }
44
+ function hex(bytes) {
45
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
46
+ }
47
+ /**
48
+ * The socket tag of an identity, also the key of its revocation marker: `#identity:` + hex
49
+ * SHA-256 of `kind:id`. Fixed length (74 ASCII characters) and opaque, so a raw id never
50
+ * reaches a tag, a runtime error message or a log, and the same id under two kinds is two
51
+ * identities. Tags starting with `#` cannot collide with channels (letter or digit first).
52
+ */
53
+ export async function identityTag(identity) {
54
+ const input = new TextEncoder().encode(`${identity.kind}:${identity.id}`);
55
+ return `${IDENTITY_TAG_PREFIX}${hex(await crypto.subtle.digest("SHA-256", input))}`;
56
+ }
57
+ /** The start of every ticket's storage key (see `ticketKey`). */
58
+ export const TICKET_KEY_PREFIX = "#ticket:";
59
+ /**
60
+ * The storage key of a pending ticket: `#ticket:` + hex SHA-256 of the ticket. The ticket itself
61
+ * is never stored; with 256 random bits a plain hash cannot be reversed or guessed.
62
+ */
63
+ export async function ticketKey(ticket) {
64
+ const input = new TextEncoder().encode(ticket);
65
+ return `${TICKET_KEY_PREFIX}${hex(await crypto.subtle.digest("SHA-256", input))}`;
66
+ }
67
+ /** The start of every identity tag (see `identityTag`). */
68
+ export const IDENTITY_TAG_PREFIX = "#identity:";
69
+ export function assertValidIdentityId(id) {
70
+ if (typeof id !== "string" ||
71
+ id.length < 1 ||
72
+ id.length > MAX_IDENTITY_ID ||
73
+ CONTROL.test(id) ||
74
+ LONE_SURROGATE.test(id)) {
75
+ throw new TypeError(`realtime: the identity id must be well-formed UTF-16, 1 to ${MAX_IDENTITY_ID} characters, without control characters.`);
76
+ }
77
+ }
78
+ /** A frozen copy holding only `id` and `kind`. */
79
+ export function validIdentity(identity) {
80
+ if (typeof identity !== "object" || identity === null) {
81
+ throw new TypeError("realtime: identity must be an object with id and kind.");
82
+ }
83
+ const { id, kind } = identity;
84
+ assertValidIdentityId(id);
85
+ if (kind !== "user" && kind !== "service" && kind !== "guest") {
86
+ throw new TypeError('realtime: identity.kind must be "user", "service" or "guest".');
87
+ }
88
+ return Object.freeze({ id, kind });
89
+ }
90
+ /**
91
+ * Fails fast when the value is not a Durable Object namespace binding (for example `env.ROOMS`
92
+ * is `undefined` because the binding is missing). Never includes the value.
93
+ */
94
+ export function assertNamespace(namespace, caller) {
95
+ const candidate = namespace;
96
+ if (typeof candidate !== "object" ||
97
+ candidate === null ||
98
+ typeof candidate.idFromName !== "function" ||
99
+ typeof candidate.get !== "function") {
100
+ throw new TypeError(`${caller}: expected a Durable Object namespace binding. Declare it in the Wrangler config under [[durable_objects.bindings]] (name and class_name of the room class) and add a migration with new_sqlite_classes for that class.`);
101
+ }
102
+ }
103
+ export function roomStub(namespace, room) {
104
+ return namespace.get(namespace.idFromName(room));
105
+ }
106
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAWH,mEAAmE;AACnE,MAAM,CAAC,MAAM,eAAe,GAAG,8BAA8B,CAAC;AAC9D,MAAM,CAAC,MAAM,IAAI,GAAG;IAClB,OAAO,EAAE,UAAU;IACnB,OAAO,EAAE,UAAU;IACnB,KAAK,EAAE,QAAQ;IACf,UAAU,EAAE,aAAa;IACzB,kGAAkG;IAClG,QAAQ,EAAE,WAAW;IACrB;;;OAGG;IACH,MAAM,EAAE,SAAS;IACjB;;;OAGG;IACH,aAAa,EAAE,iBAAiB;C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AAC;IACvF,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;AACrC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,eAAe,CAC7B,SAAkB,EAClB,MAAc;IAEd,MAAM,SAAS,GAAG,SAA+D,CAAC;IAClF,IACE,OAAO,SAAS,KAAK,QAAQ;QAC7B,SAAS,KAAK,IAAI;QAClB,OAAO,SAAS,CAAC,UAAU,KAAK,UAAU;QAC1C,OAAO,SAAS,CAAC,GAAG,KAAK,UAAU,EACnC,CAAC;QACD,MAAM,IAAI,SAAS,CACjB,GAAG,MAAM,yNAAyN,CACnO,CAAC;IACJ,CAAC;AACH,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,SAAiC,EAAE,IAAY;IACtE,OAAO,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;AACnD,CAAC"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Publishes to rooms from the API. Business logic depends on `RealtimePublisher`, received
3
+ * through the adapters, not on the binding.
4
+ */
5
+ import { type Presence, type PresenceOptions } from "./presence.js";
6
+ import { type RoomIdentity } from "./protocol.js";
7
+ import { type RealtimeEvent } from "./validation.js";
8
+ export interface RealtimePublisher {
9
+ /** Sends the event to every connection on `event.channel`. Resolves with how many got it. */
10
+ publish(room: string, event: RealtimeEvent): Promise<{
11
+ delivered: number;
12
+ }>;
13
+ /** Open connections in the room (expired ones are closed first and not counted). */
14
+ count(room: string): Promise<number>;
15
+ /**
16
+ * After access is revoked: closes the identity's open connections in the room with 4001,
17
+ * deletes its pending tickets and, for the next 60 seconds, refuses its new connections and
18
+ * tickets there (429), so a connect that passed the route's check just before the revocation
19
+ * cannot land afterwards. Resolves with how many open connections were closed.
20
+ */
21
+ disconnect(room: string, identity: RoomIdentity): Promise<{
22
+ closed: number;
23
+ }>;
24
+ /**
25
+ * Open connections in the room (expired ones are closed first and not listed), oldest first,
26
+ * with their identity, channels, connect time and last answered `"ping"`. Filters:
27
+ * `identity`, `channel` (both: their intersection), `activeWithinSeconds` (1 to 86 400);
28
+ * `limit` (default 100, 1 to 1000) caps the list and `total` says how many matched. Returns
29
+ * identity ids: authorize the caller before exposing it.
30
+ */
31
+ presence(room: string, options?: PresenceOptions): Promise<Presence>;
32
+ }
33
+ /**
34
+ * A `RealtimePublisher` over the room's Durable Object namespace. Synchronous and without I/O,
35
+ * so it is safe inside the adapters factory. Every argument is validated before any call to the
36
+ * room. The event size is checked against 1 MiB here and against `maxEventBytes` by the room.
37
+ */
38
+ export declare function realtime(namespace: DurableObjectNamespace): RealtimePublisher;
39
+ //# sourceMappingURL=publisher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publisher.d.ts","sourceRoot":"","sources":["../src/publisher.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,KAAK,QAAQ,EACb,KAAK,eAAe,EAKrB,MAAM,eAAe,CAAC;AACvB,OAAO,EAIL,KAAK,YAAY,EAGlB,MAAM,eAAe,CAAC;AACvB,OAAO,EAGL,KAAK,aAAa,EAEnB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,WAAW,iBAAiB;IAChC,6FAA6F;IAC7F,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC5E,oFAAoF;IACpF,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACrC;;;;;OAKG;IACH,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC9E;;;;;;OAMG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACtE;AAkED;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,SAAS,EAAE,sBAAsB,GAAG,iBAAiB,CA0C7E"}
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Publishes to rooms from the API. Business logic depends on `RealtimePublisher`, received
3
+ * through the adapters, not on the binding.
4
+ */
5
+ import { presenceConnection, presenceRecord, validPresenceQuery, } from "./presence.js";
6
+ import { assertNamespace, INTERNAL_ORIGIN, PATH, roomStub, validIdentity, } from "./protocol.js";
7
+ import { assertValidRoom, MAX_EVENT_BYTES_LIMIT, validEvent, } from "./validation.js";
8
+ function isCount(value) {
9
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
10
+ }
11
+ /** Checks the status and returns the JSON body; never includes the request's values. */
12
+ async function readBody(response, what, rejected) {
13
+ if (response.status === 400) {
14
+ await response.body?.cancel();
15
+ throw new TypeError(`realtime: the room rejected the ${what} (${rejected}).`);
16
+ }
17
+ if (!response.ok) {
18
+ await response.body?.cancel();
19
+ throw new Error(`realtime: the room answered the ${what} with status ${response.status}.`);
20
+ }
21
+ try {
22
+ return await response.json();
23
+ }
24
+ catch {
25
+ // A parse error quotes the body, which may hold identity ids.
26
+ throw new Error(`realtime: the room answered the ${what} without JSON.`);
27
+ }
28
+ }
29
+ async function readCount(response, key, what, rejected) {
30
+ const body = (await readBody(response, what, rejected));
31
+ const value = body?.[key];
32
+ if (!isCount(value))
33
+ throw new Error(`realtime: the room answered the ${what} without a count.`);
34
+ return value;
35
+ }
36
+ /** Parses the room's presence answer strictly: frozen, dates as `Date`, at most `limit`. */
37
+ async function readPresence(response, limit) {
38
+ const body = (await readBody(response, "presence query", "invalid query"));
39
+ const total = body?.total;
40
+ const list = body?.connections;
41
+ if (!isCount(total) ||
42
+ !Array.isArray(list) ||
43
+ list.length > limit ||
44
+ list.length > total ||
45
+ (list.length < limit && list.length !== total)) {
46
+ throw new Error("realtime: the room answered the presence query without a valid list.");
47
+ }
48
+ let records;
49
+ try {
50
+ records = list.map((entry) => presenceRecord(entry));
51
+ }
52
+ catch {
53
+ // The entry is not echoed: it holds identity ids.
54
+ throw new Error("realtime: the room answered the presence query with an invalid entry.");
55
+ }
56
+ return Object.freeze({
57
+ connections: Object.freeze(records.map(presenceConnection)),
58
+ total,
59
+ });
60
+ }
61
+ /**
62
+ * A `RealtimePublisher` over the room's Durable Object namespace. Synchronous and without I/O,
63
+ * so it is safe inside the adapters factory. Every argument is validated before any call to the
64
+ * room. The event size is checked against 1 MiB here and against `maxEventBytes` by the room.
65
+ */
66
+ export function realtime(namespace) {
67
+ assertNamespace(namespace, "realtime");
68
+ const post = (room, path, body) => roomStub(namespace, room).fetch(`${INTERNAL_ORIGIN}${path}`, {
69
+ method: "POST",
70
+ headers: { "content-type": "application/json" },
71
+ body: JSON.stringify(body),
72
+ });
73
+ return Object.freeze({
74
+ async publish(room, event) {
75
+ assertValidRoom(room);
76
+ const valid = validEvent(event, MAX_EVENT_BYTES_LIMIT);
77
+ const response = await post(room, PATH.publish, { event: valid });
78
+ return {
79
+ delivered: await readCount(response, "delivered", "publish", "invalid event, or larger than the room's maxEventBytes"),
80
+ };
81
+ },
82
+ async count(room) {
83
+ assertValidRoom(room);
84
+ const response = await roomStub(namespace, room).fetch(`${INTERNAL_ORIGIN}${PATH.count}`);
85
+ return readCount(response, "count", "count", "invalid request");
86
+ },
87
+ async disconnect(room, identity) {
88
+ assertValidRoom(room);
89
+ const valid = validIdentity(identity);
90
+ const response = await post(room, PATH.disconnect, { identity: valid });
91
+ return { closed: await readCount(response, "closed", "disconnect", "invalid identity") };
92
+ },
93
+ async presence(room, options) {
94
+ assertValidRoom(room);
95
+ const query = validPresenceQuery(options);
96
+ const response = await post(room, PATH.presence, { query });
97
+ return readPresence(response, query.limit);
98
+ },
99
+ });
100
+ }
101
+ //# sourceMappingURL=publisher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publisher.js","sourceRoot":"","sources":["../src/publisher.ts"],"names":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;YACnD,eAAe,CAAC,IAAI,CAAC,CAAC;YACtB,MAAM,KAAK,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAC;YACtC,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;YACxE,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC,QAAQ,EAAE,QAAQ,EAAE,YAAY,EAAE,kBAAkB,CAAC,EAAE,CAAC;QAC3F,CAAC;QACD,KAAK,CAAC,QAAQ,CAAC,IAAY,EAAE,OAAyB;YACpD,eAAe,CAAC,IAAI,CAAC,CAAC;YACtB,MAAM,KAAK,GAAG,kBAAkB,CAAC,OAAO,CAAC,CAAC;YAC1C,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;YAC5D,OAAO,YAAY,CAAC,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;QAC7C,CAAC;KACF,CAAC,CAAC;AACL,CAAC"}
package/dist/room.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The room: a plain Durable Object class (no `cloudflare:workers` import, no RPC) that holds
3
+ * hibernating WebSockets. The Worker talks to it with `stub.fetch` on internal URLs.
4
+ *
5
+ * Nothing about a connection lives in instance memory: channels and the identity (hashed) are
6
+ * the socket's tags, everything else is in its attachment, and revocation markers are in
7
+ * Durable Object storage, so the room behaves the same after the runtime evicts the instance
8
+ * and wakes it again for the next event. The only in-memory value is a cache (the earliest
9
+ * expiry), rebuilt by a full sweep after a wake-up.
10
+ */
11
+ import { type RoomIdentity } from "./protocol.js";
12
+ export interface RoomHookContext<Env> {
13
+ readonly room: string;
14
+ readonly identity: RoomIdentity;
15
+ /** The connection's channels (a frozen copy). */
16
+ readonly channels: readonly string[];
17
+ /** When the connection was accepted; in `onDisconnect`, how long it lasted is now minus this. */
18
+ readonly connectedAt: Date;
19
+ /**
20
+ * Open connections after the change; 0 means the room is now empty. Sockets that are closing
21
+ * are not counted here, but they still count against the caps until the runtime drops them.
22
+ */
23
+ readonly connections: number;
24
+ /**
25
+ * Open connections of this identity in the room after the change, counted the same way:
26
+ * 1 in `onConnect` is its first connection, 0 in `onDisconnect` means its last one closed.
27
+ */
28
+ readonly identityConnections: number;
29
+ readonly env: Env;
30
+ }
31
+ export interface RoomOptions<Env = unknown> {
32
+ /** Default 1000, at most 32 768. */
33
+ readonly maxConnections?: number;
34
+ /** Default 5, at most `maxConnections`. */
35
+ readonly maxConnectionsPerIdentity?: number;
36
+ /** Size limit of a serialized event, in UTF-8 bytes. Default 16 384, 256 to 1 048 576. */
37
+ readonly maxEventBytes?: number;
38
+ /**
39
+ * Default 3600, 1 to 604 800 (7 days). Each socket gets a random age between 90 % and 100 %
40
+ * of it, so sockets opened together do not all expire together.
41
+ */
42
+ readonly maxConnectionAgeSeconds?: number;
43
+ /**
44
+ * Runs after the socket is accepted, before the 101 response. **Not a gate**: a throw is
45
+ * logged and the connection stays. Authorize in the route, before `connectToRoom`.
46
+ */
47
+ onConnect?(context: RoomHookContext<Env>): void | Promise<void>;
48
+ /**
49
+ * Runs once per socket when its close completes (the runtime calls `webSocketClose`), so a
50
+ * peer that never answers a close frame delays it.
51
+ */
52
+ onDisconnect?(context: RoomHookContext<Env>): void | Promise<void>;
53
+ }
54
+ /** The class `defineRoom` returns. Export it from the Worker entry under the configured name. */
55
+ export type RoomClass<Env = unknown> = new (state: DurableObjectState, env: Env) => DurableObject;
56
+ /** Returns the Durable Object class the project exports from its Worker entry. */
57
+ export declare function defineRoom<Env = unknown>(options?: RoomOptions<Env>): RoomClass<Env>;
58
+ //# sourceMappingURL=room.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"room.d.ts","sourceRoot":"","sources":["../src/room.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AASH,OAAO,EAQL,KAAK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