@narumitw/pi-chat 0.1.6 → 0.1.8

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.
Files changed (49) hide show
  1. package/README.md +17 -34
  2. package/dist/chunks/{chat-view-EZ24L3LM.js → chat-view-7OBZGYZM.ts} +2 -2
  3. package/dist/chunks/chat-view-7OBZGYZM.ts.map +7 -0
  4. package/dist/chunks/{chunk-ZR2JESR5.js → chunk-7FD7DDSU.ts} +6 -36
  5. package/dist/chunks/chunk-7FD7DDSU.ts.map +7 -0
  6. package/dist/chunks/{chunk-XYZZR6DW.js → chunk-EOZIFFAD.ts} +6 -23
  7. package/dist/chunks/chunk-EOZIFFAD.ts.map +7 -0
  8. package/dist/chunks/{chunk-UE3UAOJX.js → chunk-LN3NAZRC.ts} +1 -1
  9. package/dist/chunks/{chunk-UE3UAOJX.js.map → chunk-LN3NAZRC.ts.map} +1 -1
  10. package/dist/chunks/{chunk-OQLAKS7O.js → chunk-MHSYNYS3.ts} +4 -7
  11. package/dist/chunks/chunk-MHSYNYS3.ts.map +7 -0
  12. package/dist/chunks/{chunk-UQPD3L6X.js → chunk-WUCSLYAK.ts} +1 -1
  13. package/dist/chunks/chunk-WUCSLYAK.ts.map +7 -0
  14. package/dist/chunks/{directory-network-EWFZFLGK.js → directory-network-6OPGA4EH.ts} +7 -19
  15. package/dist/chunks/directory-network-6OPGA4EH.ts.map +7 -0
  16. package/dist/chunks/{menu-2KEDM6NJ.js → menu-S7MZCVYM.ts} +5 -5
  17. package/dist/chunks/menu-S7MZCVYM.ts.map +7 -0
  18. package/dist/chunks/{network-MXCIGGQ2.js → network-Y4Z4JJ5J.ts} +3 -3
  19. package/dist/chunks/network-Y4Z4JJ5J.ts.map +7 -0
  20. package/dist/chunks/{widget-4OBABJDY.js → widget-QT53EBN6.ts} +4 -10
  21. package/dist/chunks/widget-QT53EBN6.ts.map +7 -0
  22. package/dist/index.ts +20 -66
  23. package/dist/index.ts.map +2 -2
  24. package/package.json +54 -55
  25. package/src/chat-session.ts +571 -594
  26. package/src/chat-view.ts +221 -226
  27. package/src/directory-network.ts +347 -365
  28. package/src/external.d.ts +56 -66
  29. package/src/identity.ts +74 -88
  30. package/src/menu.ts +535 -541
  31. package/src/network-contract.ts +5 -5
  32. package/src/network.ts +154 -157
  33. package/src/nickname.ts +6 -6
  34. package/src/pi-chat.ts +700 -774
  35. package/src/protocol.ts +296 -335
  36. package/src/public-room-directory.ts +276 -310
  37. package/src/room.ts +54 -58
  38. package/src/settings.ts +234 -259
  39. package/src/text.ts +57 -57
  40. package/src/widget.ts +56 -72
  41. package/dist/chunks/chat-view-EZ24L3LM.js.map +0 -7
  42. package/dist/chunks/chunk-OQLAKS7O.js.map +0 -7
  43. package/dist/chunks/chunk-UQPD3L6X.js.map +0 -7
  44. package/dist/chunks/chunk-XYZZR6DW.js.map +0 -7
  45. package/dist/chunks/chunk-ZR2JESR5.js.map +0 -7
  46. package/dist/chunks/directory-network-EWFZFLGK.js.map +0 -7
  47. package/dist/chunks/menu-2KEDM6NJ.js.map +0 -7
  48. package/dist/chunks/network-MXCIGGQ2.js.map +0 -7
  49. package/dist/chunks/widget-4OBABJDY.js.map +0 -7
@@ -1,12 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import type { ChatIdentity } from "./identity.js";
3
3
  import { signIdentityPayload, verifyIdentityPayload } from "./identity.js";
4
- import {
5
- createPublicRoom,
6
- MAX_EVENT_AGE_MS,
7
- MAX_FRAME_BYTES,
8
- MAX_GOSSIP_HOPS,
9
- } from "./protocol.js";
4
+ import { createPublicRoom, MAX_EVENT_AGE_MS, MAX_FRAME_BYTES, MAX_GOSSIP_HOPS } from "./protocol.js";
10
5
 
11
6
  const MAX_EVENT_FUTURE_MS = 60_000;
12
7
  const DIRECTORY_RECORD_TTL_MS = 90_000;
@@ -18,369 +13,340 @@ const PUBLIC_KEY = /^[0-9a-f]{64}$/u;
18
13
  const SIGNATURE = /^[A-Za-z0-9_-]{86}$/u;
19
14
 
20
15
  export const PUBLIC_ROOM_DIRECTORY_TOPIC = createHash("sha256")
21
- .update("pi-chat/public-room-directory/v2", "utf8")
22
- .digest();
16
+ .update("pi-chat/public-room-directory/v2", "utf8")
17
+ .digest();
23
18
 
24
19
  export interface DirectoryPresence {
25
- v: 2;
26
- kind: "directory-presence";
27
- slug: string;
28
- origin: string;
29
- id: string;
30
- issuedAt: number;
31
- status: "online" | "leaving";
32
- signature: string;
20
+ v: 2;
21
+ kind: "directory-presence";
22
+ slug: string;
23
+ origin: string;
24
+ id: string;
25
+ issuedAt: number;
26
+ status: "online" | "leaving";
27
+ signature: string;
33
28
  }
34
29
 
35
30
  export interface DirectoryWireMessage {
36
- v: 2;
37
- type: "directory";
38
- event: DirectoryPresence;
39
- hops: number;
40
- partial?: true;
31
+ v: 2;
32
+ type: "directory";
33
+ event: DirectoryPresence;
34
+ hops: number;
35
+ partial?: true;
41
36
  }
42
37
 
43
38
  export interface PublicRoomListing {
44
- slug: string;
45
- estimatedParticipants: number;
39
+ slug: string;
40
+ estimatedParticipants: number;
46
41
  }
47
42
 
48
43
  export interface PublicRoomBrowseResult {
49
- rooms: PublicRoomListing[];
50
- partial: boolean;
44
+ rooms: PublicRoomListing[];
45
+ partial: boolean;
51
46
  }
52
47
 
53
48
  export interface DirectoryCatalogOptions {
54
- now?: () => number;
55
- maxRecords?: number;
56
- maxRooms?: number;
49
+ now?: () => number;
50
+ maxRecords?: number;
51
+ maxRooms?: number;
57
52
  }
58
53
 
59
54
  interface SeenRecord {
60
- key: string;
61
- expiresAt: number;
55
+ key: string;
56
+ expiresAt: number;
62
57
  }
63
58
 
64
59
  export class DirectoryCatalog {
65
- private readonly now: () => number;
66
- private readonly maxRecords: number;
67
- private readonly maxRooms: number;
68
- private readonly records = new Map<string, DirectoryPresence>();
69
- private readonly seen = new Map<string, number>();
70
- private readonly seenOrder: SeenRecord[] = [];
71
- private truncated = false;
72
-
73
- constructor(options: DirectoryCatalogOptions = {}) {
74
- this.now = options.now ?? Date.now;
75
- this.maxRecords = positiveBound(options.maxRecords, MAX_DIRECTORY_RECORDS);
76
- this.maxRooms = positiveBound(options.maxRooms, MAX_DIRECTORY_ROOMS);
77
- }
78
-
79
- accept(event: DirectoryPresence): boolean {
80
- const now = this.now();
81
- if (!verifyDirectoryPresence(event, now)) return false;
82
- const seenKey = `${event.origin}:${event.id}`;
83
- if (this.hasSeen(seenKey)) return false;
84
- this.remember(seenKey);
85
- const existing = this.records.get(event.origin);
86
- if (
87
- existing &&
88
- (existing.issuedAt > event.issuedAt ||
89
- (existing.issuedAt === event.issuedAt && existing.id.localeCompare(event.id) >= 0))
90
- ) {
91
- return false;
92
- }
93
- if (!existing && this.records.size >= this.maxRecords) {
94
- this.truncated = true;
95
- return false;
96
- }
97
- const knownSlugs = new Set(
98
- [...this.records.values()]
99
- .filter(({ status }) => status === "online")
100
- .map(({ slug }) => slug),
101
- );
102
- if (
103
- event.status === "online" &&
104
- !knownSlugs.has(event.slug) &&
105
- knownSlugs.size >= this.maxRooms
106
- ) {
107
- this.truncated = true;
108
- return false;
109
- }
110
- this.records.set(event.origin, event);
111
- return true;
112
- }
113
-
114
- snapshot(): PublicRoomBrowseResult {
115
- this.prune();
116
- const counts = new Map<string, number>();
117
- for (const event of this.records.values()) {
118
- if (event.status === "online") {
119
- counts.set(event.slug, (counts.get(event.slug) ?? 0) + 1);
120
- }
121
- }
122
- return {
123
- rooms: sortDirectoryRooms(
124
- [...counts].map(([slug, estimatedParticipants]) => ({ slug, estimatedParticipants })),
125
- ),
126
- partial: this.truncated,
127
- };
128
- }
129
-
130
- currentEvents(): DirectoryPresence[] {
131
- this.prune();
132
- return [...this.records.values()].sort(
133
- (left, right) => right.issuedAt - left.issuedAt || left.origin.localeCompare(right.origin),
134
- );
135
- }
136
-
137
- markPartial(): void {
138
- this.truncated = true;
139
- }
140
-
141
- private prune(): void {
142
- const now = this.now();
143
- for (const [origin, event] of this.records) {
144
- const ttl = event.status === "leaving" ? MAX_EVENT_AGE_MS : DIRECTORY_RECORD_TTL_MS;
145
- if (event.issuedAt < now - ttl) this.records.delete(origin);
146
- }
147
- this.pruneSeen();
148
- }
149
-
150
- private hasSeen(key: string): boolean {
151
- this.pruneSeen();
152
- return this.seen.has(key);
153
- }
154
-
155
- private remember(key: string): void {
156
- const expiresAt = this.now() + DIRECTORY_SEEN_TTL_MS;
157
- this.seen.set(key, expiresAt);
158
- this.seenOrder.push({ key, expiresAt });
159
- while (this.seen.size > MAX_DIRECTORY_SEEN) {
160
- const removed = this.seenOrder.shift();
161
- if (removed && this.seen.get(removed.key) === removed.expiresAt) {
162
- this.seen.delete(removed.key);
163
- }
164
- }
165
- }
166
-
167
- private pruneSeen(): void {
168
- const now = this.now();
169
- while (this.seenOrder[0] && this.seenOrder[0].expiresAt <= now) {
170
- const removed = this.seenOrder.shift();
171
- if (removed && this.seen.get(removed.key) === removed.expiresAt) {
172
- this.seen.delete(removed.key);
173
- }
174
- }
175
- }
60
+ private readonly now: () => number;
61
+ private readonly maxRecords: number;
62
+ private readonly maxRooms: number;
63
+ private readonly records = new Map<string, DirectoryPresence>();
64
+ private readonly seen = new Map<string, number>();
65
+ private readonly seenOrder: SeenRecord[] = [];
66
+ private truncated = false;
67
+
68
+ constructor(options: DirectoryCatalogOptions = {}) {
69
+ this.now = options.now ?? Date.now;
70
+ this.maxRecords = positiveBound(options.maxRecords, MAX_DIRECTORY_RECORDS);
71
+ this.maxRooms = positiveBound(options.maxRooms, MAX_DIRECTORY_ROOMS);
72
+ }
73
+
74
+ accept(event: DirectoryPresence): boolean {
75
+ const now = this.now();
76
+ if (!verifyDirectoryPresence(event, now)) return false;
77
+ const seenKey = `${event.origin}:${event.id}`;
78
+ if (this.hasSeen(seenKey)) return false;
79
+ this.remember(seenKey);
80
+ const existing = this.records.get(event.origin);
81
+ if (
82
+ existing &&
83
+ (existing.issuedAt > event.issuedAt ||
84
+ (existing.issuedAt === event.issuedAt && existing.id.localeCompare(event.id) >= 0))
85
+ ) {
86
+ return false;
87
+ }
88
+ if (!existing && this.records.size >= this.maxRecords) {
89
+ this.truncated = true;
90
+ return false;
91
+ }
92
+ const knownSlugs = new Set(
93
+ [...this.records.values()].filter(({ status }) => status === "online").map(({ slug }) => slug),
94
+ );
95
+ if (event.status === "online" && !knownSlugs.has(event.slug) && knownSlugs.size >= this.maxRooms) {
96
+ this.truncated = true;
97
+ return false;
98
+ }
99
+ this.records.set(event.origin, event);
100
+ return true;
101
+ }
102
+
103
+ snapshot(): PublicRoomBrowseResult {
104
+ this.prune();
105
+ const counts = new Map<string, number>();
106
+ for (const event of this.records.values()) {
107
+ if (event.status === "online") {
108
+ counts.set(event.slug, (counts.get(event.slug) ?? 0) + 1);
109
+ }
110
+ }
111
+ return {
112
+ rooms: sortDirectoryRooms([...counts].map(([slug, estimatedParticipants]) => ({ slug, estimatedParticipants }))),
113
+ partial: this.truncated,
114
+ };
115
+ }
116
+
117
+ currentEvents(): DirectoryPresence[] {
118
+ this.prune();
119
+ return [...this.records.values()].sort(
120
+ (left, right) => right.issuedAt - left.issuedAt || left.origin.localeCompare(right.origin),
121
+ );
122
+ }
123
+
124
+ markPartial(): void {
125
+ this.truncated = true;
126
+ }
127
+
128
+ private prune(): void {
129
+ const now = this.now();
130
+ for (const [origin, event] of this.records) {
131
+ const ttl = event.status === "leaving" ? MAX_EVENT_AGE_MS : DIRECTORY_RECORD_TTL_MS;
132
+ if (event.issuedAt < now - ttl) this.records.delete(origin);
133
+ }
134
+ this.pruneSeen();
135
+ }
136
+
137
+ private hasSeen(key: string): boolean {
138
+ this.pruneSeen();
139
+ return this.seen.has(key);
140
+ }
141
+
142
+ private remember(key: string): void {
143
+ const expiresAt = this.now() + DIRECTORY_SEEN_TTL_MS;
144
+ this.seen.set(key, expiresAt);
145
+ this.seenOrder.push({ key, expiresAt });
146
+ while (this.seen.size > MAX_DIRECTORY_SEEN) {
147
+ const removed = this.seenOrder.shift();
148
+ if (removed && this.seen.get(removed.key) === removed.expiresAt) {
149
+ this.seen.delete(removed.key);
150
+ }
151
+ }
152
+ }
153
+
154
+ private pruneSeen(): void {
155
+ const now = this.now();
156
+ while (this.seenOrder[0] && this.seenOrder[0].expiresAt <= now) {
157
+ const removed = this.seenOrder.shift();
158
+ if (removed && this.seen.get(removed.key) === removed.expiresAt) {
159
+ this.seen.delete(removed.key);
160
+ }
161
+ }
162
+ }
176
163
  }
177
164
 
178
165
  export function createDirectoryPresence(
179
- identity: ChatIdentity,
180
- slugValue: string,
181
- status: DirectoryPresence["status"],
182
- issuedAt: number,
183
- id: string,
166
+ identity: ChatIdentity,
167
+ slugValue: string,
168
+ status: DirectoryPresence["status"],
169
+ issuedAt: number,
170
+ id: string,
184
171
  ): DirectoryPresence {
185
- const slug = validatedSlug(slugValue);
186
- if (!slug) throw new Error("A public room slug must use lowercase letters, numbers, or hyphens.");
187
- if (status !== "online" && status !== "leaving") {
188
- throw new Error("Directory presence state is invalid.");
189
- }
190
- if (!Number.isSafeInteger(issuedAt) || issuedAt < 0) {
191
- throw new Error("Directory presence timestamp is invalid.");
192
- }
193
- if (!validId(id)) throw new Error("Directory presence id is invalid.");
194
- const unsigned: Omit<DirectoryPresence, "signature"> = {
195
- v: 2,
196
- kind: "directory-presence",
197
- slug,
198
- origin: identity.publicKey.toString("hex"),
199
- id,
200
- issuedAt,
201
- status,
202
- };
203
- return {
204
- ...unsigned,
205
- signature: signIdentityPayload(identity, canonicalDirectoryPresence(unsigned)),
206
- };
172
+ const slug = validatedSlug(slugValue);
173
+ if (!slug) throw new Error("A public room slug must use lowercase letters, numbers, or hyphens.");
174
+ if (status !== "online" && status !== "leaving") {
175
+ throw new Error("Directory presence state is invalid.");
176
+ }
177
+ if (!Number.isSafeInteger(issuedAt) || issuedAt < 0) {
178
+ throw new Error("Directory presence timestamp is invalid.");
179
+ }
180
+ if (!validId(id)) throw new Error("Directory presence id is invalid.");
181
+ const unsigned: Omit<DirectoryPresence, "signature"> = {
182
+ v: 2,
183
+ kind: "directory-presence",
184
+ slug,
185
+ origin: identity.publicKey.toString("hex"),
186
+ id,
187
+ issuedAt,
188
+ status,
189
+ };
190
+ return {
191
+ ...unsigned,
192
+ signature: signIdentityPayload(identity, canonicalDirectoryPresence(unsigned)),
193
+ };
207
194
  }
208
195
 
209
196
  export function verifyDirectoryPresence(value: DirectoryPresence, now = Date.now()): boolean {
210
- const event = parseDirectoryPresence(value);
211
- if (!event) return false;
212
- if (event.issuedAt < now - MAX_EVENT_AGE_MS || event.issuedAt > now + MAX_EVENT_FUTURE_MS) {
213
- return false;
214
- }
215
- const { signature, ...unsigned } = event;
216
- return verifyIdentityPayload(
217
- Buffer.from(event.origin, "hex"),
218
- canonicalDirectoryPresence(unsigned),
219
- signature,
220
- );
197
+ const event = parseDirectoryPresence(value);
198
+ if (!event) return false;
199
+ if (event.issuedAt < now - MAX_EVENT_AGE_MS || event.issuedAt > now + MAX_EVENT_FUTURE_MS) {
200
+ return false;
201
+ }
202
+ const { signature, ...unsigned } = event;
203
+ return verifyIdentityPayload(Buffer.from(event.origin, "hex"), canonicalDirectoryPresence(unsigned), signature);
221
204
  }
222
205
 
223
206
  export function createDirectoryWireMessage(
224
- event: DirectoryPresence,
225
- hops = MAX_GOSSIP_HOPS,
226
- partial = false,
207
+ event: DirectoryPresence,
208
+ hops = MAX_GOSSIP_HOPS,
209
+ partial = false,
227
210
  ): DirectoryWireMessage {
228
- if (!Number.isSafeInteger(hops) || hops < 1 || hops > MAX_GOSSIP_HOPS) {
229
- throw new Error("Directory gossip hop budget is invalid.");
230
- }
231
- return { v: 2, type: "directory", event, hops, ...(partial ? { partial: true as const } : {}) };
211
+ if (!Number.isSafeInteger(hops) || hops < 1 || hops > MAX_GOSSIP_HOPS) {
212
+ throw new Error("Directory gossip hop budget is invalid.");
213
+ }
214
+ return { v: 2, type: "directory", event, hops, ...(partial ? { partial: true as const } : {}) };
232
215
  }
233
216
 
234
217
  export function parseDirectoryWireMessage(value: unknown): DirectoryWireMessage | undefined {
235
- if (
236
- !isRecord(value) ||
237
- value.v !== 2 ||
238
- value.type !== "directory" ||
239
- !Number.isSafeInteger(value.hops) ||
240
- (value.hops as number) < 1 ||
241
- (value.hops as number) > MAX_GOSSIP_HOPS
242
- ) {
243
- return undefined;
244
- }
245
- if (value.partial !== undefined && value.partial !== true) return undefined;
246
- const event = parseDirectoryPresence(value.event);
247
- return event
248
- ? {
249
- v: 2,
250
- type: "directory",
251
- event,
252
- hops: value.hops as number,
253
- ...(value.partial === true ? { partial: true as const } : {}),
254
- }
255
- : undefined;
218
+ if (
219
+ !isRecord(value) ||
220
+ value.v !== 2 ||
221
+ value.type !== "directory" ||
222
+ !Number.isSafeInteger(value.hops) ||
223
+ (value.hops as number) < 1 ||
224
+ (value.hops as number) > MAX_GOSSIP_HOPS
225
+ ) {
226
+ return undefined;
227
+ }
228
+ if (value.partial !== undefined && value.partial !== true) return undefined;
229
+ const event = parseDirectoryPresence(value.event);
230
+ return event
231
+ ? {
232
+ v: 2,
233
+ type: "directory",
234
+ event,
235
+ hops: value.hops as number,
236
+ ...(value.partial === true ? { partial: true as const } : {}),
237
+ }
238
+ : undefined;
256
239
  }
257
240
 
258
241
  export function encodeDirectoryFrame(message: DirectoryWireMessage): Buffer {
259
- const payload = Buffer.from(JSON.stringify(message), "utf8");
260
- if (payload.length > MAX_FRAME_BYTES) throw new Error("Directory frame exceeds the size limit.");
261
- const header = Buffer.allocUnsafe(4);
262
- header.writeUInt32BE(payload.length);
263
- return Buffer.concat([header, payload]);
242
+ const payload = Buffer.from(JSON.stringify(message), "utf8");
243
+ if (payload.length > MAX_FRAME_BYTES) throw new Error("Directory frame exceeds the size limit.");
244
+ const header = Buffer.allocUnsafe(4);
245
+ header.writeUInt32BE(payload.length);
246
+ return Buffer.concat([header, payload]);
264
247
  }
265
248
 
266
249
  export class DirectoryFrameDecoder {
267
- private buffer = Buffer.alloc(0);
268
-
269
- push(chunk: Uint8Array): DirectoryWireMessage[] {
270
- if (chunk.byteLength === 0) return [];
271
- const incoming = Buffer.from(chunk);
272
- const messages: DirectoryWireMessage[] = [];
273
- let offset = 0;
274
- while (offset < incoming.length) {
275
- if (this.buffer.length < 4) {
276
- const headerBytes = Math.min(4 - this.buffer.length, incoming.length - offset);
277
- this.buffer = Buffer.concat([this.buffer, incoming.subarray(offset, offset + headerBytes)]);
278
- offset += headerBytes;
279
- if (this.buffer.length < 4) break;
280
- }
281
- const length = this.buffer.readUInt32BE(0);
282
- if (length > MAX_FRAME_BYTES) {
283
- this.buffer = Buffer.alloc(0);
284
- throw new Error("Directory frame exceeds the size limit.");
285
- }
286
- const frameBytes = length + 4;
287
- if (this.buffer.length < frameBytes) {
288
- const payloadBytes = Math.min(frameBytes - this.buffer.length, incoming.length - offset);
289
- this.buffer = Buffer.concat([
290
- this.buffer,
291
- incoming.subarray(offset, offset + payloadBytes),
292
- ]);
293
- offset += payloadBytes;
294
- if (this.buffer.length < frameBytes) break;
295
- }
296
- const payload = this.buffer.subarray(4, frameBytes);
297
- this.buffer = Buffer.alloc(0);
298
- let value: unknown;
299
- try {
300
- value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(payload)) as unknown;
301
- } catch {
302
- throw new Error("Directory frame is not valid UTF-8 JSON.");
303
- }
304
- const parsed = parseDirectoryWireMessage(value);
305
- if (!parsed) throw new Error("Directory frame has an invalid message shape.");
306
- messages.push(parsed);
307
- }
308
- return messages;
309
- }
250
+ private buffer = Buffer.alloc(0);
251
+
252
+ push(chunk: Uint8Array): DirectoryWireMessage[] {
253
+ if (chunk.byteLength === 0) return [];
254
+ const incoming = Buffer.from(chunk);
255
+ const messages: DirectoryWireMessage[] = [];
256
+ let offset = 0;
257
+ while (offset < incoming.length) {
258
+ if (this.buffer.length < 4) {
259
+ const headerBytes = Math.min(4 - this.buffer.length, incoming.length - offset);
260
+ this.buffer = Buffer.concat([this.buffer, incoming.subarray(offset, offset + headerBytes)]);
261
+ offset += headerBytes;
262
+ if (this.buffer.length < 4) break;
263
+ }
264
+ const length = this.buffer.readUInt32BE(0);
265
+ if (length > MAX_FRAME_BYTES) {
266
+ this.buffer = Buffer.alloc(0);
267
+ throw new Error("Directory frame exceeds the size limit.");
268
+ }
269
+ const frameBytes = length + 4;
270
+ if (this.buffer.length < frameBytes) {
271
+ const payloadBytes = Math.min(frameBytes - this.buffer.length, incoming.length - offset);
272
+ this.buffer = Buffer.concat([this.buffer, incoming.subarray(offset, offset + payloadBytes)]);
273
+ offset += payloadBytes;
274
+ if (this.buffer.length < frameBytes) break;
275
+ }
276
+ const payload = this.buffer.subarray(4, frameBytes);
277
+ this.buffer = Buffer.alloc(0);
278
+ let value: unknown;
279
+ try {
280
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(payload)) as unknown;
281
+ } catch {
282
+ throw new Error("Directory frame is not valid UTF-8 JSON.");
283
+ }
284
+ const parsed = parseDirectoryWireMessage(value);
285
+ if (!parsed) throw new Error("Directory frame has an invalid message shape.");
286
+ messages.push(parsed);
287
+ }
288
+ return messages;
289
+ }
310
290
  }
311
291
 
312
292
  export function sortDirectoryRooms(rooms: readonly PublicRoomListing[]): PublicRoomListing[] {
313
- return [...rooms].sort(
314
- (left, right) =>
315
- right.estimatedParticipants - left.estimatedParticipants ||
316
- left.slug.localeCompare(right.slug),
317
- );
293
+ return [...rooms].sort(
294
+ (left, right) => right.estimatedParticipants - left.estimatedParticipants || left.slug.localeCompare(right.slug),
295
+ );
318
296
  }
319
297
 
320
298
  function parseDirectoryPresence(value: unknown): DirectoryPresence | undefined {
321
- if (
322
- !isRecord(value) ||
323
- value.v !== 2 ||
324
- value.kind !== "directory-presence" ||
325
- !validatedSlug(value.slug) ||
326
- !PUBLIC_KEY.test(String(value.origin)) ||
327
- !validId(value.id) ||
328
- !Number.isSafeInteger(value.issuedAt) ||
329
- (value.issuedAt as number) < 0 ||
330
- (value.status !== "online" && value.status !== "leaving") ||
331
- typeof value.signature !== "string" ||
332
- !SIGNATURE.test(value.signature)
333
- ) {
334
- return undefined;
335
- }
336
- return {
337
- v: 2,
338
- kind: "directory-presence",
339
- slug: value.slug as string,
340
- origin: value.origin as string,
341
- id: value.id,
342
- issuedAt: value.issuedAt as number,
343
- status: value.status,
344
- signature: value.signature,
345
- };
299
+ if (
300
+ !isRecord(value) ||
301
+ value.v !== 2 ||
302
+ value.kind !== "directory-presence" ||
303
+ !validatedSlug(value.slug) ||
304
+ !PUBLIC_KEY.test(String(value.origin)) ||
305
+ !validId(value.id) ||
306
+ !Number.isSafeInteger(value.issuedAt) ||
307
+ (value.issuedAt as number) < 0 ||
308
+ (value.status !== "online" && value.status !== "leaving") ||
309
+ typeof value.signature !== "string" ||
310
+ !SIGNATURE.test(value.signature)
311
+ ) {
312
+ return undefined;
313
+ }
314
+ return {
315
+ v: 2,
316
+ kind: "directory-presence",
317
+ slug: value.slug as string,
318
+ origin: value.origin as string,
319
+ id: value.id,
320
+ issuedAt: value.issuedAt as number,
321
+ status: value.status,
322
+ signature: value.signature,
323
+ };
346
324
  }
347
325
 
348
326
  function canonicalDirectoryPresence(event: Omit<DirectoryPresence, "signature">): Buffer {
349
- return Buffer.from(
350
- JSON.stringify([
351
- 2,
352
- "directory-presence",
353
- event.slug,
354
- event.origin,
355
- event.id,
356
- event.issuedAt,
357
- event.status,
358
- ]),
359
- "utf8",
360
- );
327
+ return Buffer.from(
328
+ JSON.stringify([2, "directory-presence", event.slug, event.origin, event.id, event.issuedAt, event.status]),
329
+ "utf8",
330
+ );
361
331
  }
362
332
 
363
333
  function validatedSlug(value: unknown): string | undefined {
364
- if (typeof value !== "string") return undefined;
365
- try {
366
- return createPublicRoom(value).slug;
367
- } catch {
368
- return undefined;
369
- }
334
+ if (typeof value !== "string") return undefined;
335
+ try {
336
+ return createPublicRoom(value).slug;
337
+ } catch {
338
+ return undefined;
339
+ }
370
340
  }
371
341
 
372
342
  function positiveBound(value: number | undefined, fallback: number): number {
373
- return Number.isSafeInteger(value) && (value ?? 0) > 0
374
- ? Math.min(value ?? fallback, fallback)
375
- : fallback;
343
+ return Number.isSafeInteger(value) && (value ?? 0) > 0 ? Math.min(value ?? fallback, fallback) : fallback;
376
344
  }
377
345
 
378
346
  function validId(value: unknown): value is string {
379
- return (
380
- typeof value === "string" && value.length > 0 && value.length <= 64 && !/\p{Cc}/u.test(value)
381
- );
347
+ return typeof value === "string" && value.length > 0 && value.length <= 64 && !/\p{Cc}/u.test(value);
382
348
  }
383
349
 
384
350
  function isRecord(value: unknown): value is Record<string, unknown> {
385
- return typeof value === "object" && value !== null && !Array.isArray(value);
351
+ return typeof value === "object" && value !== null && !Array.isArray(value);
386
352
  }