@hadoku/game-server 0.0.0-stage → 0.1.6

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 (119) hide show
  1. package/LICENSE +21 -0
  2. package/dist/base-path.d.ts +29 -0
  3. package/dist/base-path.js +30 -0
  4. package/dist/busy.d.ts +40 -0
  5. package/dist/busy.js +23 -0
  6. package/dist/capacity.d.ts +9 -0
  7. package/dist/capacity.js +6 -0
  8. package/dist/config.d.ts +247 -0
  9. package/dist/config.js +271 -0
  10. package/dist/edge-auth.d.ts +43 -0
  11. package/dist/edge-auth.js +47 -0
  12. package/dist/erase/anonymise.d.ts +7 -0
  13. package/dist/erase/anonymise.js +7 -0
  14. package/dist/erase/index.d.ts +18 -0
  15. package/dist/erase/index.js +20 -0
  16. package/dist/erase/legacy-ids.d.ts +7 -0
  17. package/dist/erase/legacy-ids.js +24 -0
  18. package/dist/erase/recordings.d.ts +26 -0
  19. package/dist/erase/recordings.js +128 -0
  20. package/dist/erase/rooms.d.ts +63 -0
  21. package/dist/erase/rooms.js +67 -0
  22. package/dist/gate.d.ts +27 -0
  23. package/dist/gate.js +15 -0
  24. package/dist/http/client-events.d.ts +25 -0
  25. package/dist/http/client-events.js +15 -0
  26. package/dist/http/page.d.ts +26 -0
  27. package/dist/http/page.js +35 -0
  28. package/dist/http/prepared.d.ts +14 -0
  29. package/dist/http/prepared.js +16 -0
  30. package/dist/http/request.d.ts +59 -0
  31. package/dist/http/request.js +37 -0
  32. package/dist/http/room-core.d.ts +160 -0
  33. package/dist/http/room-core.js +278 -0
  34. package/dist/http/trim.d.ts +23 -0
  35. package/dist/http/trim.js +76 -0
  36. package/dist/http/usage.d.ts +22 -0
  37. package/dist/http/usage.js +16 -0
  38. package/dist/kernel.d.ts +4 -0
  39. package/dist/kernel.js +26 -0
  40. package/dist/log.d.ts +9 -0
  41. package/dist/log.js +9 -0
  42. package/dist/people.d.ts +105 -0
  43. package/dist/people.js +145 -0
  44. package/dist/play/clock.d.ts +39 -0
  45. package/dist/play/clock.js +81 -0
  46. package/dist/play/diagnostics.d.ts +21 -0
  47. package/dist/play/diagnostics.js +35 -0
  48. package/dist/play/engine-runtime.d.ts +200 -0
  49. package/dist/play/engine-runtime.js +309 -0
  50. package/dist/play/game-adapter.d.ts +158 -0
  51. package/dist/play/game-adapter.js +1 -0
  52. package/dist/play/host.d.ts +482 -0
  53. package/dist/play/host.js +950 -0
  54. package/dist/play/jvm-transport.d.ts +25 -0
  55. package/dist/play/jvm-transport.js +1 -0
  56. package/dist/play/local-jvm.d.ts +325 -0
  57. package/dist/play/local-jvm.js +829 -0
  58. package/dist/play/match/hosted.d.ts +92 -0
  59. package/dist/play/match/hosted.js +151 -0
  60. package/dist/play/match/outcome.d.ts +26 -0
  61. package/dist/play/match/outcome.js +21 -0
  62. package/dist/play/match/shell.d.ts +378 -0
  63. package/dist/play/match/shell.js +613 -0
  64. package/dist/play/recording/retention.d.ts +36 -0
  65. package/dist/play/recording/retention.js +89 -0
  66. package/dist/play/recording/writer.d.ts +185 -0
  67. package/dist/play/recording/writer.js +90 -0
  68. package/dist/play/relay-socket.d.ts +128 -0
  69. package/dist/play/relay-socket.js +194 -0
  70. package/dist/play/runtimes/in-process.d.ts +47 -0
  71. package/dist/play/runtimes/in-process.js +43 -0
  72. package/dist/play/runtimes/relay-match.d.ts +166 -0
  73. package/dist/play/runtimes/relay-match.js +240 -0
  74. package/dist/play/runtimes/relay.d.ts +128 -0
  75. package/dist/play/runtimes/relay.js +183 -0
  76. package/dist/play/runtimes/streamed.d.ts +116 -0
  77. package/dist/play/runtimes/streamed.js +148 -0
  78. package/dist/play/start-queue.d.ts +65 -0
  79. package/dist/play/start-queue.js +187 -0
  80. package/dist/room/avatar.d.ts +1 -0
  81. package/dist/room/avatar.js +28 -0
  82. package/dist/room/caller.d.ts +21 -0
  83. package/dist/room/caller.js +1 -0
  84. package/dist/room/constants.d.ts +27 -0
  85. package/dist/room/constants.js +27 -0
  86. package/dist/room/events.d.ts +59 -0
  87. package/dist/room/events.js +174 -0
  88. package/dist/room/identity.d.ts +89 -0
  89. package/dist/room/identity.js +98 -0
  90. package/dist/room/lobby.d.ts +426 -0
  91. package/dist/room/lobby.js +880 -0
  92. package/dist/room/membership.d.ts +64 -0
  93. package/dist/room/membership.js +76 -0
  94. package/dist/room/provisioning.d.ts +22 -0
  95. package/dist/room/provisioning.js +46 -0
  96. package/dist/room/record.d.ts +63 -0
  97. package/dist/room/record.js +39 -0
  98. package/dist/room/room-list.d.ts +67 -0
  99. package/dist/room/room-list.js +66 -0
  100. package/dist/room/seats.d.ts +39 -0
  101. package/dist/room/seats.js +58 -0
  102. package/dist/room/session.d.ts +91 -0
  103. package/dist/room/session.js +156 -0
  104. package/dist/room/socket-auth.d.ts +2 -0
  105. package/dist/room/socket-auth.js +10 -0
  106. package/dist/room/watching.d.ts +35 -0
  107. package/dist/room/watching.js +72 -0
  108. package/dist/room/watchparty-link.d.ts +1 -0
  109. package/dist/room/watchparty-link.js +17 -0
  110. package/dist/stream/alloc.d.ts +115 -0
  111. package/dist/stream/alloc.js +368 -0
  112. package/dist/stream/index.d.ts +66 -0
  113. package/dist/stream/index.js +293 -0
  114. package/dist/telemetry.d.ts +46 -0
  115. package/dist/telemetry.js +25 -0
  116. package/dist/testPort.d.ts +1 -0
  117. package/dist/testPort.js +28 -0
  118. package/package.json +35 -4
  119. package/README.md +0 -3
@@ -0,0 +1,880 @@
1
+ /**
2
+ * The lobby core: which rooms exist, who is in them, who leads them and holds which seat, kept on
3
+ * disk, for any game type. A game type plugs in through `RoomTypeHooks` (its own part of the record,
4
+ * its seat rules, its view, what leaving or a Ready costs it); this file never names a game's field.
5
+ * Magic's lobby (`games/magic/server/src/room/lobby.ts`) is this core with Magic's hooks, and a game
6
+ * with nothing of its own to keep (bomberman) plays on `plainRoomType`.
7
+ *
8
+ * ## Persistence: write-through, through `@wolffm/rooms-server/store`
9
+ *
10
+ * A deploy restarts the server several times a day, so every mutation writes that room's snapshot
11
+ * synchronously (`FileRoomStore`'s atomic temp-file-and-rename) before the call returns: no debounce
12
+ * window for a deploy to fall into, no flush-on-SIGTERM to get right. Rooms are stored in the store's
13
+ * own snapshot format (`STORE_VERSION`) and read back through `decodeSnapshot`, so an unreadable or
14
+ * future-format record is QUARANTINED (moved aside intact), never half-applied or silently dropped.
15
+ *
16
+ * The snapshot's `members` are the room's members; each member's `app` blob carries their Ready and
17
+ * their per-room state. The room-level `app` blob (`StoredRoomApp`) carries name, creator, leader,
18
+ * game type, the game seats, the game's own part (`RoomTypeHooks.encode`), and the password's salt
19
+ * and scrypt hash.
20
+ *
21
+ * ## The password is privacy between friends, not authentication
22
+ *
23
+ * Everything here is behind the member gate at the edge. A room password keeps a sibling out of your
24
+ * game; it is not a security boundary. It is still handled with care, because a person may reuse a
25
+ * password they use elsewhere: scrypt with a per-room salt, never logged (nor its hash or salt), kept
26
+ * in a private map rather than on the record so dumping a record cannot print it, and compared with
27
+ * `timingSafeEqual` (`provisioning.ts`).
28
+ *
29
+ * ## Only durable callers may create or join
30
+ *
31
+ * An ephemeral participant id is a per-request random value: it could never be matched on a second
32
+ * request, and the store drops non-durable members from every snapshot. So `create`/`join` refuse an
33
+ * ephemeral caller (the HTTP layer answers 403) rather than seat a member who vanishes on restart.
34
+ */
35
+ import { STORE_VERSION, SnapshotUnreadableError, decodeSnapshot, } from '@wolffm/rooms-server/store';
36
+ import { createSeatTable, isDurableParticipantId } from '@wolffm/rooms-protocol';
37
+ import { addMember, createMembershipLedger, setReady as ledgerSetReady } from '@wolffm/rooms-server';
38
+ import { seatsOpenAt } from '@wolffm/platform-wire/events';
39
+ import { sameLook } from '@wolffm/platform-wire/look';
40
+ import { ROOM_ID_RE } from '@wolffm/platform-wire/room-feed';
41
+ import { replaceIds } from "../erase/anonymise.js";
42
+ import { avatarIdOf } from "./avatar.js";
43
+ import { ROOM_STALE_MS, UNNAMED } from "./constants.js";
44
+ import { addRoomMember, isMemberReady, isRoomMember, passwordAdmits, removeRoomMember, setMemberReady } from "./membership.js";
45
+ import { makeSecret, mintRoomId } from "./provisioning.js";
46
+ import { AI_SEAT, CLOSED_SEAT, leaveGameSeat, memberSeats, setGameSeat, takeGameSeat } from "./record.js";
47
+ import { isOfferedRoom, isSweepableRoom, NO_BUSY_HOOK, sortRoomsByCreation } from "./room-list.js";
48
+ import { watchpartyRoomId } from "./watchparty-link.js";
49
+ /** The fewest seats a room is left with when its seats are closed: one player and one more. */
50
+ export const MIN_OPEN_SEATS = 2;
51
+ /** The room-level app blob's version. Additive fields never bump it: each reads with a default. */
52
+ export const ROOM_APP_VERSION = 2;
53
+ /** The generic half of a room's view. */
54
+ function platformView(room, locked, seats) {
55
+ return {
56
+ id: room.id,
57
+ name: room.name,
58
+ creator: room.creator,
59
+ leader: room.leader,
60
+ gameType: room.gameType,
61
+ locked,
62
+ members: room.members.map((m) => ({
63
+ id: m.id,
64
+ name: m.name,
65
+ joinedAt: new Date(m.joinedAt).toISOString(),
66
+ ready: isMemberReady(room, m.id),
67
+ // Spread, not `avatarId: m.avatarId`: the key is ABSENT for a member with none, so an
68
+ // in-process reader and a JSON reader see the same two states.
69
+ ...(m.avatarId === undefined ? {} : { avatarId: m.avatarId }),
70
+ ...(m.look === undefined ? {} : { look: m.look }),
71
+ })),
72
+ seats,
73
+ createdAt: new Date(room.createdAt).toISOString(),
74
+ testing: room.testing,
75
+ scheduledFor: room.scheduledFor === undefined ? null : new Date(room.scheduledFor).toISOString(),
76
+ };
77
+ }
78
+ function isSecret(v) {
79
+ return typeof v === 'object' && v !== null && typeof v.salt === 'string' && typeof v.hash === 'string';
80
+ }
81
+ /**
82
+ * The room-level codec: the platform's fields here, the game seats and game part through the room's
83
+ * type. Its errors name the FIELD, never a value: the message reaches the quarantine reason and the
84
+ * log, and a value here could be the hash.
85
+ */
86
+ export function roomAppCodec(typeOf) {
87
+ const app = {
88
+ version: ROOM_APP_VERSION,
89
+ serialize: (value) => structuredClone(typeOf(value.gameType)?.writes?.(value) ?? value),
90
+ deserialize(raw, version, ctx) {
91
+ if (typeof raw !== 'object' || raw === null)
92
+ throw new Error('app is not an object');
93
+ if (version < 1 || version > ROOM_APP_VERSION)
94
+ throw new Error('app version is not one this build reads');
95
+ const a = raw;
96
+ if (typeof a.name !== 'string')
97
+ throw new Error('app.name is not a string');
98
+ if (typeof a.creator !== 'string')
99
+ throw new Error('app.creator is not a string');
100
+ if (typeof a.leader !== 'string')
101
+ throw new Error('app.leader is not a string');
102
+ const hooks = typeof a.gameType === 'string' ? typeOf(a.gameType) : undefined;
103
+ if (hooks === undefined)
104
+ throw new Error('app.gameType is not a known game type');
105
+ if (a.testing !== undefined && typeof a.testing !== 'boolean')
106
+ throw new Error('app.testing is invalid');
107
+ if (a.scheduledFor !== undefined && typeof a.scheduledFor !== 'number')
108
+ throw new Error('app.scheduledFor is invalid');
109
+ if (a.secret !== null && !isSecret(a.secret))
110
+ throw new Error('app.secret is invalid');
111
+ const { seats, game } = hooks.decode(a, version, { roomId: ctx.roomId });
112
+ return {
113
+ name: a.name,
114
+ creator: a.creator,
115
+ leader: a.leader,
116
+ gameType: a.gameType,
117
+ testing: a.testing === true,
118
+ ...(a.scheduledFor === undefined ? {} : { scheduledFor: a.scheduledFor }),
119
+ secret: a.secret === null ? null : { salt: a.secret.salt, hash: a.secret.hash },
120
+ seats,
121
+ game,
122
+ };
123
+ },
124
+ };
125
+ return { app };
126
+ }
127
+ function unboxState(app) {
128
+ if (typeof app !== 'object' || app === null || !('state' in app))
129
+ return undefined;
130
+ return app.state;
131
+ }
132
+ /** Anything but a stored `true` is not ready — including a member blob from before the field. */
133
+ function unboxReady(app) {
134
+ if (typeof app !== 'object' || app === null)
135
+ return false;
136
+ return app.ready === true;
137
+ }
138
+ /**
139
+ * The lobby core. `V` is the view a room of the hosting game reads as (the platform's fields and
140
+ * the type's part); `I` the create input. A game's lobby extends it with its own operations, which
141
+ * reach the rooms through the protected members below.
142
+ */
143
+ export class RoomLobby {
144
+ store;
145
+ now;
146
+ log;
147
+ #typeOf;
148
+ #watchpartyRoom;
149
+ #codec;
150
+ #rooms = new Map();
151
+ /** Kept apart from the records so no dump of a record can carry them. */
152
+ #secrets = new Map();
153
+ /** In memory only: a read is not a mutation and must not write a file. */
154
+ #touchedAt = new Map();
155
+ /** Room files still being deleted (`#forget`): `removed` waits for them. */
156
+ #removing = new Set();
157
+ #avatarListeners = new Set();
158
+ #changeListeners = new Set();
159
+ /**
160
+ * The newest `createdAt` minted or restored so far. A created room's stamp is forced at least 1 ms
161
+ * past the last one, so the list is creation order deterministically (the tie-break is the random
162
+ * room id), across a restart too, because the stamp is what is persisted.
163
+ */
164
+ #lastCreatedAt = 0;
165
+ #relayRoomOpened = () => { };
166
+ constructor(opts) {
167
+ this.store = opts.store;
168
+ this.now = opts.now;
169
+ this.log = opts.log;
170
+ this.#typeOf = opts.typeOf;
171
+ this.#watchpartyRoom = opts.watchpartyRoom;
172
+ this.#codec = roomAppCodec(opts.typeOf);
173
+ }
174
+ /** `room`'s own hooks. A room is only ever installed with a type that has them (`openRoomStore`, `#insert`). */
175
+ hooksOf(room) {
176
+ return this.#typeOf(room.gameType);
177
+ }
178
+ /** The room by id, of whatever type. */
179
+ room(roomId) {
180
+ return this.#rooms.get(roomId);
181
+ }
182
+ rooms() {
183
+ return this.#rooms.values();
184
+ }
185
+ /** Boot only: install a room decoded from disk. */
186
+ install(room, secret) {
187
+ this.#rooms.set(room.id, room);
188
+ this.#lastCreatedAt = Math.max(this.#lastCreatedAt, room.createdAt);
189
+ if (secret !== null)
190
+ this.#secrets.set(room.id, secret);
191
+ this.hooksOf(room).restored?.(room);
192
+ }
193
+ view(room) {
194
+ const hooks = this.hooksOf(room);
195
+ const seats = hooks.seatsView?.(room) ?? memberSeats(room);
196
+ return { ...platformView(room, this.#secrets.has(room.id), seats), ...hooks.view(room) };
197
+ }
198
+ /** Save `room` and tell every `onChange` listener. Every mutation ends here. */
199
+ persist(room) {
200
+ const hooks = this.hooksOf(room);
201
+ hooks.beforePersist?.(room);
202
+ const now = this.now();
203
+ room.updatedAt = now;
204
+ const members = room.members.map((m) => {
205
+ // No name and no avatar id (R12): a member is saved as who they are, not as what they
206
+ // were called. Both come back from their next request (`rename`, the avatar assert).
207
+ const ready = isMemberReady(room, m.id);
208
+ return {
209
+ participantId: m.id,
210
+ ...(m.userId === null ? {} : { accountId: m.userId }),
211
+ joinedAt: m.joinedAt,
212
+ lastSeen: m.joinedAt,
213
+ // Boxed, so a state of `null` survives a restart as `null`, and `ready` rides the same
214
+ // blob. A member with neither writes `null`.
215
+ app: m.state === undefined && !ready ? null : { state: structuredClone(m.state), ready },
216
+ };
217
+ });
218
+ const app = {
219
+ name: room.name,
220
+ creator: room.creator,
221
+ leader: room.leader,
222
+ gameType: room.gameType,
223
+ testing: room.testing,
224
+ ...(room.scheduledFor === undefined ? {} : { scheduledFor: room.scheduledFor }),
225
+ secret: this.#secrets.get(room.id) ?? null,
226
+ seats: [...room.seats],
227
+ game: hooks.encode(room),
228
+ };
229
+ const snapshot = {
230
+ storeVersion: STORE_VERSION,
231
+ roomId: room.id,
232
+ roomKey: room.id,
233
+ lastEventSeq: 0,
234
+ createdAt: room.createdAt,
235
+ updatedAt: now,
236
+ members,
237
+ usedAvatars: [],
238
+ seats: createSeatTable(null),
239
+ app: this.#codec.app.serialize(app),
240
+ appVersion: ROOM_APP_VERSION,
241
+ };
242
+ this.store.saveSync(snapshot);
243
+ this.changed(room.id);
244
+ }
245
+ /** Tell every `onChange` listener `roomId` reads differently now, with nothing written. */
246
+ changed(roomId) {
247
+ for (const listener of [...this.#changeListeners]) {
248
+ try {
249
+ listener(roomId);
250
+ }
251
+ catch (err) {
252
+ // A broken subscriber must not undo a change that is already stored.
253
+ this.log({ event: 'room-change-listener-failed', roomId, error: err.message });
254
+ }
255
+ }
256
+ }
257
+ /**
258
+ * Be told every time a room is written, created or forgotten. Every mutation goes through one
259
+ * persist, so this is every change a read could see and nothing else: a read (`touch`, `get`,
260
+ * `list`) never fires it. Returns the unsubscribe.
261
+ */
262
+ onChange(listener) {
263
+ this.#changeListeners.add(listener);
264
+ return () => {
265
+ this.#changeListeners.delete(listener);
266
+ };
267
+ }
268
+ /**
269
+ * Told once, at boot, how a room whose type is its own match (`RoomTypeHooks.relaySeats`) opens
270
+ * that match: called the moment such a room is created, and at once for every such room already
271
+ * open (rooms restored from disk, which no match outlived). Unset, such a room has no match behind it.
272
+ */
273
+ onRelayRoomOpened(hook) {
274
+ this.#relayRoomOpened = hook;
275
+ for (const room of this.#rooms.values())
276
+ this.#openRelayMatch(room);
277
+ }
278
+ #openRelayMatch(room) {
279
+ const seats = this.hooksOf(room).relaySeats;
280
+ if (seats !== undefined)
281
+ this.#relayRoomOpened(room.id, seats, room.gameType);
282
+ }
283
+ list() {
284
+ return sortRoomsByCreation([...this.#rooms.values()]).map((r) => this.view(r));
285
+ }
286
+ /**
287
+ * The rooms the front page offers: `list()` minus the rooms nobody has touched for `staleMs`. A
288
+ * room with a game in progress is always offered. Same order as `list()`.
289
+ */
290
+ offered(staleMs = ROOM_STALE_MS) {
291
+ const now = this.now();
292
+ return sortRoomsByCreation([...this.#rooms.values()].filter((r) => isOfferedRoom(r, this.hooksOf(r).busy, now, staleMs, this.#touchedAt.get(r.id)))).map((r) => this.view(r));
293
+ }
294
+ /** Record that `memberId` has `roomId` open now. A non-member or unknown room is ignored. */
295
+ touch(roomId, memberId) {
296
+ if (this.isMember(roomId, memberId))
297
+ this.#touchedAt.set(roomId, this.now());
298
+ }
299
+ get(roomId) {
300
+ const room = this.#rooms.get(roomId);
301
+ return room === undefined ? undefined : this.view(room);
302
+ }
303
+ /** Whether `memberId` is a member of `roomId`. False when there is no such room. */
304
+ isMember(roomId, memberId) {
305
+ const room = this.#rooms.get(roomId);
306
+ return room !== undefined && isRoomMember(room, memberId);
307
+ }
308
+ /** Per-member opaque state owned by the game's routes (the deck a seat holds). Not part of the view. undefined when unset / no room / not a member. */
309
+ playerState(roomId, memberId) {
310
+ const member = this.#rooms.get(roomId)?.members.find((m) => m.id === memberId);
311
+ return member?.state === undefined ? undefined : structuredClone(member.state);
312
+ }
313
+ /** false when there is no such room or memberId is not a member. Persisted. */
314
+ setPlayerState(roomId, memberId, state) {
315
+ const room = this.#rooms.get(roomId);
316
+ const member = room?.members.find((m) => m.id === memberId);
317
+ if (room === undefined || member === undefined)
318
+ return false;
319
+ member.state = state === undefined ? undefined : structuredClone(state);
320
+ this.persist(room);
321
+ return true;
322
+ }
323
+ /** The members who play, in seat order. */
324
+ playersOf(room) {
325
+ return this.hooksOf(room).players?.(room) ?? memberSeats(room).filter((s) => s !== null);
326
+ }
327
+ /**
328
+ * Everyone in a room is a player or a spectator, whatever the room plays (the operator,
329
+ * 2026-11-02). A newcomer takes the first open seat, only on entering, never on a member's return
330
+ * (someone who chose to watch stays watching), and never ahead of a member already in the room
331
+ * without a seat: at a party the watcher who waited takes the loser's seat, not the loser coming
332
+ * back in (`e2e/turnover.spec.ts`). Nothing moves while the room's seats are shut for its event.
333
+ */
334
+ #autoSeat(room, memberId) {
335
+ if (this.seatsShut(room) !== null)
336
+ return;
337
+ const players = this.playersOf(room);
338
+ if (room.members.some((m) => m.id !== memberId && !players.includes(m.id)))
339
+ return;
340
+ const how = this.hooksOf(room).autoSeat?.(room, memberId) ?? 'game-seat';
341
+ if (how !== 'game-seat')
342
+ return;
343
+ const open = room.seats.indexOf(null);
344
+ if (open === -1)
345
+ return;
346
+ setGameSeat(room, open, memberId);
347
+ this.log({ event: 'seat-auto', roomId: room.id, seat: open, memberId });
348
+ }
349
+ /** `seatsShutUntil`, for a room in hand. */
350
+ seatsShut(room) {
351
+ if (room.scheduledFor === undefined)
352
+ return null;
353
+ const opens = seatsOpenAt(room.scheduledFor);
354
+ return this.now() < opens ? opens : null;
355
+ }
356
+ /**
357
+ * When a room made for an event opens its seats (`seatsOpenAt`), while they are still shut by the
358
+ * lobby's clock: until then nobody sits, is seated on joining or on Ready, and nothing deals.
359
+ * Null once they are open, for a room no event made, and for no such room.
360
+ */
361
+ seatsShutUntil(roomId) {
362
+ const room = this.#rooms.get(roomId);
363
+ return room === undefined ? null : this.seatsShut(room);
364
+ }
365
+ /**
366
+ * The seat this member holds in the room's game (the view's `seats`), or null: watching, not a
367
+ * member, or no such room. What a relay match seats a socket by, so the relay and every screen
368
+ * name the same seat holders.
369
+ */
370
+ gameSeatOf(roomId, memberId) {
371
+ const room = this.#rooms.get(roomId);
372
+ if (room === undefined)
373
+ return null;
374
+ const seat = (this.hooksOf(room).seatsView?.(room) ?? memberSeats(room)).indexOf(memberId);
375
+ return seat === -1 ? null : seat;
376
+ }
377
+ /**
378
+ * A member steps out. Removed from `members`; their state and Ready go with their row. If they
379
+ * led the room, leadership passes to whichever remaining member joined EARLIEST (R16). What it
380
+ * costs their game is the type's (`RoomTypeHooks.leaving`). A room left by its last member is not
381
+ * deleted here (the idle sweep owns deletion) but leaves `offered()` the instant it empties.
382
+ * `no-room` and `not-member` are both answered the same 404 by the HTTP layer.
383
+ */
384
+ leave(roomId, memberId) {
385
+ const room = this.#rooms.get(roomId);
386
+ if (room === undefined)
387
+ return { ok: false, reason: 'no-room' };
388
+ if (!isRoomMember(room, memberId))
389
+ return { ok: false, reason: 'not-member' };
390
+ const cost = this.hooksOf(room).leaving?.(room, memberId) ?? {};
391
+ // R16: leadership (whoever remains joined earliest) passes on here if `memberId` held it.
392
+ removeRoomMember(room, memberId);
393
+ this.persist(room);
394
+ this.log({ event: 'room-left', roomId, members: room.members.length, newLeader: room.leader });
395
+ return { ok: true, room: this.view(room), ...cost };
396
+ }
397
+ create(caller, input) {
398
+ if (!isDurableParticipantId(caller.id))
399
+ return { ok: false, reason: 'not-durable' };
400
+ let id = mintRoomId();
401
+ while (this.#rooms.has(id))
402
+ id = mintRoomId();
403
+ return { ok: true, room: this.#insert(id, caller, input) };
404
+ }
405
+ /**
406
+ * The room a watchparty room's game slot binds to (D21): `wp-` plus a digest of the watchparty
407
+ * room, so everyone in that room arrives at the same table without anyone passing an id around.
408
+ * Made on first use with the caller as its creator and leader, joined after that.
409
+ */
410
+ bindWatchparty(caller, watchpartyRoom) {
411
+ if (!isDurableParticipantId(caller.id))
412
+ return { ok: false, reason: 'not-durable' };
413
+ const id = watchpartyRoomId(watchpartyRoom);
414
+ if (this.#rooms.has(id))
415
+ return this.join(id, caller);
416
+ return { ok: true, room: this.#insert(id, caller, this.#watchpartyRoom), alreadyMember: false };
417
+ }
418
+ #insert(id, caller, input) {
419
+ const hooks = this.#typeOf(input.gameType);
420
+ if (hooks === undefined)
421
+ throw new Error(`no room type ${input.gameType}`);
422
+ const now = Math.max(this.now(), this.#lastCreatedAt + 1);
423
+ this.#lastCreatedAt = now;
424
+ const ledger = createMembershipLedger();
425
+ addMember(ledger, caller.id, now);
426
+ const room = {
427
+ id,
428
+ name: input.name,
429
+ creator: caller.id,
430
+ leader: caller.id,
431
+ gameType: input.gameType,
432
+ testing: input.testing === true,
433
+ ...(input.scheduledFor === undefined ? {} : { scheduledFor: input.scheduledFor }),
434
+ ...hooks.newGame(input, id),
435
+ createdAt: now,
436
+ updatedAt: now,
437
+ members: [{ id: caller.id, userId: caller.userId, name: caller.name, joinedAt: now, state: undefined }],
438
+ ledger,
439
+ };
440
+ this.#rooms.set(id, room);
441
+ this.#openRelayMatch(room);
442
+ this.#autoSeat(room, caller.id);
443
+ if (input.password !== undefined && input.password !== '')
444
+ this.#secrets.set(id, makeSecret(input.password));
445
+ this.persist(room);
446
+ const said = hooks.created?.(room) ?? {};
447
+ this.log({ event: 'room-created', roomId: id, gameType: room.gameType, ...said, locked: this.#secrets.has(id) });
448
+ return this.view(room);
449
+ }
450
+ /** Idempotent for an existing member, who needs no password again. */
451
+ join(roomId, caller, password) {
452
+ if (!isDurableParticipantId(caller.id))
453
+ return { ok: false, reason: 'not-durable' };
454
+ const room = this.#rooms.get(roomId);
455
+ if (room === undefined)
456
+ return { ok: false, reason: 'no-match' };
457
+ if (isRoomMember(room, caller.id))
458
+ return { ok: true, room: this.view(room), alreadyMember: true };
459
+ if (!passwordAdmits(this.#secrets.get(roomId), password))
460
+ return { ok: false, reason: 'no-match' };
461
+ const now = this.now();
462
+ // An empty ledger's first member becomes its leader (an emptied room's new arrival leads it).
463
+ addRoomMember(room, { id: caller.id, userId: caller.userId, name: caller.name, joinedAt: now, state: undefined }, now);
464
+ this.#autoSeat(room, caller.id);
465
+ this.persist(room);
466
+ this.log({ event: 'room-joined', roomId, members: room.members.length });
467
+ return { ok: true, room: this.view(room), alreadyMember: false };
468
+ }
469
+ /**
470
+ * Call `caller.id` by `caller.name` in every room they are a member of. The name was copied once, at
471
+ * join, so a key renamed in the registry kept its first name in every room it had joined
472
+ * (2026-10-26). Writes only the rooms whose copy moved.
473
+ */
474
+ rename(caller) {
475
+ for (const room of this.#rooms.values()) {
476
+ const member = room.members.find((m) => m.id === caller.id);
477
+ if (member === undefined || member.name === caller.name)
478
+ continue;
479
+ member.name = caller.name;
480
+ this.persist(room);
481
+ }
482
+ }
483
+ /** false when there is no such room or the caller is not a member. Persisted. */
484
+ setReady(roomId, memberId, ready) {
485
+ const room = this.#rooms.get(roomId);
486
+ if (room === undefined || !isRoomMember(room, memberId))
487
+ return false;
488
+ const hooks = this.hooksOf(room);
489
+ if (hooks.ready?.(room, memberId, ready) === 'keep')
490
+ return true;
491
+ setMemberReady(room, memberId, ready);
492
+ this.persist(room);
493
+ this.log({ event: 'room-ready', roomId, ready });
494
+ hooks.seatsChanged?.(room);
495
+ return true;
496
+ }
497
+ /**
498
+ * The member's OWN avatar, and nobody else's: `memberId` is always a derived participant id, so a
499
+ * browser cannot name a row that is not its own. Three states in, two stored: a non-blank string
500
+ * sets it; `null`, `''`, whitespace, an over-long value and a non-string clear it (`avatarIdOf`).
501
+ * `false` only when there is no such room or member. Written only when it changed.
502
+ */
503
+ setAvatar(roomId, memberId, avatarId) {
504
+ const room = this.#rooms.get(roomId);
505
+ const member = room?.members.find((m) => m.id === memberId);
506
+ if (room === undefined || member === undefined)
507
+ return false;
508
+ const next = avatarIdOf(avatarId);
509
+ // Idempotent, and no write when nothing changed: a member's account is written onto the room
510
+ // on every arrival and every change to it. `true` either way: the room is in the asked state.
511
+ if (next === member.avatarId)
512
+ return true;
513
+ if (next === undefined)
514
+ delete member.avatarId;
515
+ else
516
+ member.avatarId = next;
517
+ this.persist(room);
518
+ this.#announceAvatar(roomId, member.id, member.avatarId ?? null);
519
+ return true;
520
+ }
521
+ /** Each member's registry userId, for looking up how they look. Never part of a view. */
522
+ usersOf(roomId) {
523
+ const room = this.#rooms.get(roomId);
524
+ if (room === undefined)
525
+ return [];
526
+ return room.members.flatMap((m) => (m.userId === null ? [] : [{ memberId: m.id, userId: m.userId }]));
527
+ }
528
+ /**
529
+ * A member's avatar picture and cosmetics, as prefs-api answered for them. In memory only: looked
530
+ * up again after a restart. A real change is announced as an avatar change, so a running match
531
+ * re-sends its seats, and to `onChange` with nothing written. `false` only when there is no such room or member.
532
+ */
533
+ setLook(roomId, memberId, look) {
534
+ const room = this.#rooms.get(roomId);
535
+ const member = room?.members.find((m) => m.id === memberId);
536
+ if (room === undefined || member === undefined)
537
+ return false;
538
+ if (sameLook(member.look, look))
539
+ return true;
540
+ if (look === undefined)
541
+ delete member.look;
542
+ else
543
+ member.look = look;
544
+ this.log({ event: 'room-look', roomId, picture: look?.picture !== undefined, worn: Object.keys(look?.cosmetics ?? {}).length });
545
+ this.#announceAvatar(roomId, memberId, member.avatarId ?? null);
546
+ this.changed(roomId);
547
+ return true;
548
+ }
549
+ #announceAvatar(roomId, memberId, avatarId) {
550
+ // The id itself, not the member's: which character somebody picked is not a secret.
551
+ this.log({ event: 'room-avatar', roomId, avatarId });
552
+ for (const listener of [...this.#avatarListeners]) {
553
+ try {
554
+ listener({ roomId, memberId, avatarId });
555
+ }
556
+ catch (err) {
557
+ this.log({ event: 'room-avatar-listener-failed', roomId, error: err.message });
558
+ }
559
+ }
560
+ }
561
+ /** Be told when a member's avatar actually CHANGES (never on an idempotent re-assert). Returns the unsubscribe. */
562
+ onAvatarChange(listener) {
563
+ this.#avatarListeners.add(listener);
564
+ return () => {
565
+ this.#avatarListeners.delete(listener);
566
+ };
567
+ }
568
+ /** The room by id when it seats through its game seats, with the refusal every seat op shares otherwise. */
569
+ #seatRoom(roomId, memberId) {
570
+ const room = this.#rooms.get(roomId);
571
+ if (room === undefined)
572
+ return { refused: 'no-room' };
573
+ if (!isRoomMember(room, memberId))
574
+ return { refused: 'not-member' };
575
+ const hooks = this.hooksOf(room);
576
+ // `not-draft`, the wire's name for a room that does not seat through its game seats.
577
+ if (!hooks.usesSeats(room))
578
+ return { refused: 'not-draft' };
579
+ if (hooks.seatsFixed(room))
580
+ return { refused: 'not-lobby' };
581
+ return { room, hooks };
582
+ }
583
+ /** Whether `seat` is one a seat op may act on: one the room has, or the one past the last (which grows it), never past its ceiling. */
584
+ #inReach(room, hooks, seat) {
585
+ return Number.isInteger(seat) && seat >= 0 && seat < hooks.seatCeiling(room) && seat <= room.seats.length;
586
+ }
587
+ /**
588
+ * Take a game seat. `seat` absent takes the first open one (their own counts as open), growing the
589
+ * room by one past the last when none is; given, it must be open and in reach. Moves the caller from
590
+ * any seat they held.
591
+ */
592
+ sitSeat(roomId, memberId, seat) {
593
+ const found = this.#seatRoom(roomId, memberId);
594
+ if ('refused' in found)
595
+ return { ok: false, reason: found.refused };
596
+ const { room, hooks } = found;
597
+ if (this.seatsShut(room) !== null)
598
+ return { ok: false, reason: 'not-open' };
599
+ if (seat !== undefined && !this.#inReach(room, hooks, seat))
600
+ return { ok: false, reason: 'bad-seat' };
601
+ const already = room.seats.indexOf(memberId);
602
+ let target = seat;
603
+ if (target === undefined) {
604
+ const open = room.seats.findIndex((id, i) => id === null || i === already);
605
+ target = open === -1 ? room.seats.length : open;
606
+ if (target >= hooks.seatCeiling(room))
607
+ return { ok: false, reason: 'pod-full' };
608
+ }
609
+ else if (target !== already && (room.seats[target] ?? null) !== null) {
610
+ return { ok: false, reason: 'seat-taken' };
611
+ }
612
+ hooks.growSeats(room, target);
613
+ takeGameSeat(room, memberId, target);
614
+ hooks.trimSeats(room);
615
+ this.persist(room);
616
+ this.log({ event: 'pod-sit', roomId, memberId, seat: target });
617
+ hooks.seatsChanged?.(room);
618
+ return { ok: true, room: this.view(room) };
619
+ }
620
+ /** Give up a game seat. Idempotent: not seated is not a failure. */
621
+ standSeat(roomId, memberId) {
622
+ const found = this.#seatRoom(roomId, memberId);
623
+ if ('refused' in found)
624
+ return { ok: false, reason: found.refused };
625
+ const { room, hooks } = found;
626
+ if (!leaveGameSeat(room, memberId))
627
+ return { ok: true, room: this.view(room) };
628
+ hooks.trimSeats(room);
629
+ this.persist(room);
630
+ this.log({ event: 'pod-stand', roomId, memberId });
631
+ hooks.seatsChanged?.(room);
632
+ return { ok: true, room: this.view(room) };
633
+ }
634
+ /** Put the AI in an open seat (`on`), or take it out. Any member. */
635
+ aiSeat(roomId, memberId, seat, on) {
636
+ const found = this.#seatRoom(roomId, memberId);
637
+ if ('refused' in found)
638
+ return { ok: false, reason: found.refused };
639
+ const { room, hooks } = found;
640
+ if (hooks.fieldFixed?.(room) === true)
641
+ return { ok: false, reason: 'historical' };
642
+ if (on && this.seatsShut(room) !== null)
643
+ return { ok: false, reason: 'not-open' };
644
+ if (!this.#inReach(room, hooks, seat) || (!on && seat >= room.seats.length))
645
+ return { ok: false, reason: 'bad-seat' };
646
+ const now = room.seats[seat] ?? null;
647
+ if (on ? now === AI_SEAT : now === null)
648
+ return { ok: true, room: this.view(room) };
649
+ if (now !== (on ? null : AI_SEAT))
650
+ return { ok: false, reason: 'seat-taken' };
651
+ hooks.growSeats(room, seat);
652
+ setGameSeat(room, seat, on ? AI_SEAT : null);
653
+ hooks.aiSeated?.(room, seat, on);
654
+ hooks.trimSeats(room);
655
+ this.persist(room);
656
+ this.log({ event: on ? 'pod-ai-sit' : 'pod-ai-stand', roomId, memberId, seat });
657
+ hooks.seatsChanged?.(room);
658
+ return { ok: true, room: this.view(room) };
659
+ }
660
+ /** Close an empty seat, or open a closed one: the leader's; never fewer than `MIN_OPEN_SEATS` open. */
661
+ closeSeat(roomId, memberId, seat, closed) {
662
+ const room = this.#rooms.get(roomId);
663
+ if (room === undefined)
664
+ return { ok: false, reason: 'no-room' };
665
+ if (!isRoomMember(room, memberId))
666
+ return { ok: false, reason: 'not-member' };
667
+ if (room.leader !== memberId)
668
+ return { ok: false, reason: 'not-leader' };
669
+ const found = this.#seatRoom(roomId, memberId);
670
+ if ('refused' in found)
671
+ return { ok: false, reason: found.refused };
672
+ const { hooks } = found;
673
+ if (hooks.fieldFixed?.(room) === true)
674
+ return { ok: false, reason: 'historical' };
675
+ if (!this.#inReach(room, hooks, seat) || seat >= room.seats.length)
676
+ return { ok: false, reason: 'bad-seat' };
677
+ const now = room.seats[seat] ?? null;
678
+ if (closed ? now === CLOSED_SEAT : now === null)
679
+ return { ok: true, room: this.view(room) };
680
+ if (now !== (closed ? null : CLOSED_SEAT))
681
+ return { ok: false, reason: 'seat-taken' };
682
+ const size = () => room.seats.filter((s) => s !== CLOSED_SEAT).length;
683
+ if (closed && size() <= MIN_OPEN_SEATS)
684
+ return { ok: false, reason: 'too-few' };
685
+ setGameSeat(room, seat, closed ? CLOSED_SEAT : null);
686
+ hooks.trimSeats(room);
687
+ this.persist(room);
688
+ this.log({ event: closed ? 'pod-seat-closed' : 'pod-seat-opened', roomId, memberId, seat, size: size() });
689
+ return { ok: true, room: this.view(room) };
690
+ }
691
+ /**
692
+ * Forget every room untouched for longer than `idleMs` (or its type's own idle window), on disk as
693
+ * well as in memory. Never a room with a live game, never one its type spares. Returns the ids dropped.
694
+ */
695
+ sweep(idleMs) {
696
+ const dropped = [];
697
+ const now = this.now();
698
+ for (const [id, room] of this.#rooms) {
699
+ const busy = this.hooksOf(room).busy;
700
+ if (!isSweepableRoom(room, busy, now, idleMs))
701
+ continue;
702
+ this.hooksOf(room).ending?.(room, 'sweep');
703
+ this.#forget(id);
704
+ dropped.push(id);
705
+ this.log({ event: 'room-forgotten', roomId: id, idleMs: idleMs ?? busy.defaultIdleMs(room) });
706
+ }
707
+ return dropped;
708
+ }
709
+ /** Resolves once every room forgotten so far is gone from disk too (a failed delete is logged as `room-forget-failed`). */
710
+ async removed() {
711
+ await Promise.all([...this.#removing]);
712
+ }
713
+ /**
714
+ * Account erase: every room that still names one of `ids` names `to` instead, and is saved. Answers
715
+ * how many rooms changed. The person leaves first (`leave`), so leadership has passed on.
716
+ */
717
+ anonymise(ids, to) {
718
+ let changed = 0;
719
+ for (const room of this.#rooms.values()) {
720
+ this.hooksOf(room).anonymise?.(room, ids);
721
+ if (replaceIds(room, ids, to) === 0)
722
+ continue;
723
+ changed++;
724
+ this.persist(room);
725
+ }
726
+ return changed;
727
+ }
728
+ /** Move the start of the event a room was made for, and its seats' opening with it. False when there is no such room. */
729
+ reschedule(roomId, at) {
730
+ const room = this.#rooms.get(roomId);
731
+ if (room === undefined)
732
+ return false;
733
+ room.scheduledFor = at;
734
+ this.persist(room);
735
+ return true;
736
+ }
737
+ /**
738
+ * The owner ends the room for everyone: it is forgotten, as the sweep forgets one, and its type keeps
739
+ * what it played first. Answers the matches it was playing, for the caller to stop. Any admin in a
740
+ * testing room may close it: the HTTP layer has already checked admin and membership.
741
+ */
742
+ close(roomId, callerId) {
743
+ const room = this.#rooms.get(roomId);
744
+ if (room === undefined)
745
+ return { ok: false, reason: 'no-room' };
746
+ if (room.leader !== callerId && !room.testing)
747
+ return { ok: false, reason: 'not-leader' };
748
+ const hooks = this.hooksOf(room);
749
+ hooks.ending?.(room, 'close');
750
+ const matches = hooks.liveMatches(room);
751
+ this.#forget(roomId);
752
+ this.log({ event: 'room-closed', roomId, matches: matches.length });
753
+ return { ok: true, matches };
754
+ }
755
+ /** Gone from the list the moment it leaves the map, and from disk best-effort. */
756
+ #forget(id) {
757
+ const room = this.#rooms.get(id);
758
+ if (room !== undefined)
759
+ this.hooksOf(room).ending?.(room, 'forget');
760
+ this.#rooms.delete(id);
761
+ this.#secrets.delete(id);
762
+ this.#touchedAt.delete(id);
763
+ // Logged, because a store that cannot delete must not resurrect the room on the next boot silently.
764
+ const removing = this.store.remove(id).catch((err) => {
765
+ this.log({ event: 'room-forget-failed', roomId: id, err: String(err) });
766
+ });
767
+ this.#removing.add(removing);
768
+ void removing.finally(() => this.#removing.delete(removing));
769
+ this.changed(id);
770
+ }
771
+ /**
772
+ * Read every room file back, through `typeOf`: once, before the lobby is used. A record that cannot
773
+ * be read is quarantined and logged by room id and reason; the reason names what was wrong, never
774
+ * the bytes, which could include a password hash. Answers how many rooms are open.
775
+ */
776
+ async open() {
777
+ const store = this.store;
778
+ const codec = this.#codec;
779
+ for (const roomId of await store.list()) {
780
+ const quarantine = async (reason) => {
781
+ await store.quarantine(roomId, reason);
782
+ this.log({ event: 'room-quarantined', roomId, reason });
783
+ };
784
+ let snapshot;
785
+ try {
786
+ snapshot = await store.load(roomId);
787
+ }
788
+ catch (err) {
789
+ // JSON.parse's message quotes the input, so it is NOT passed on.
790
+ if (err instanceof SyntaxError) {
791
+ await quarantine('malformed: not JSON');
792
+ continue;
793
+ }
794
+ throw err;
795
+ }
796
+ if (snapshot === null)
797
+ continue;
798
+ try {
799
+ if (!ROOM_ID_RE.test(roomId))
800
+ throw new SnapshotUnreadableError('malformed', roomId, 'room id');
801
+ const decoded = decodeSnapshot(snapshot, codec, { roomId, restoreId: `boot-${this.now()}`, restoredAt: this.now() });
802
+ const app = decoded.app;
803
+ const { dropHolds, game } = this.#typeOf(app.gameType).restore(app, roomId);
804
+ const members = [];
805
+ // Rebuilt, not persisted; `leaderId` is set explicitly below, from disk.
806
+ const ledger = createMembershipLedger();
807
+ for (const m of decoded.members) {
808
+ // Nothing names or dresses a member on disk (R12): they are `UNNAMED` and wear no
809
+ // character until their account is read again. Ready is kept across the restart.
810
+ addMember(ledger, m.participantId, m.joinedAt);
811
+ if (!dropHolds && unboxReady(m.app))
812
+ ledgerSetReady(ledger, m.participantId, true);
813
+ members.push({ id: m.participantId, userId: m.accountId ?? null, name: UNNAMED, joinedAt: m.joinedAt, state: dropHolds ? undefined : unboxState(m.app) });
814
+ }
815
+ ledger.leaderId = app.leader;
816
+ this.install({
817
+ id: roomId,
818
+ name: app.name,
819
+ creator: app.creator,
820
+ leader: app.leader,
821
+ gameType: app.gameType,
822
+ testing: app.testing === true,
823
+ ...(app.scheduledFor === undefined ? {} : { scheduledFor: app.scheduledFor }),
824
+ seats: app.seats,
825
+ game: game(members),
826
+ createdAt: decoded.createdAt,
827
+ // The raw snapshot's clock: when this room was last touched by the process that wrote it.
828
+ updatedAt: snapshot.updatedAt,
829
+ members,
830
+ ledger,
831
+ }, app.secret);
832
+ }
833
+ catch (err) {
834
+ if (err instanceof SnapshotUnreadableError) {
835
+ await quarantine(`${err.reason}: ${err.message}`);
836
+ continue;
837
+ }
838
+ throw err;
839
+ }
840
+ }
841
+ return this.#rooms.size;
842
+ }
843
+ }
844
+ /** A stored seat list: every seat a holder's id, a marker, or open. */
845
+ function isStoredSeats(v) {
846
+ return Array.isArray(v) && v.every((s) => s === null || typeof s === 'string');
847
+ }
848
+ /**
849
+ * The room type of a game that keeps nothing of its own in the room (bomberman): no game part, its
850
+ * players in the platform's game seats, opened with `seats` of them and growing to `max`, an AI or a
851
+ * closed seat in any open one. `relaySeats` when the room is its own relay match.
852
+ */
853
+ export function plainRoomType(size) {
854
+ const open = () => new Array(size.seats).fill(null);
855
+ return {
856
+ newGame: () => ({ seats: open(), game: {} }),
857
+ encode: () => ({}),
858
+ decode(app) {
859
+ if (app.seats !== undefined && !isStoredSeats(app.seats))
860
+ throw new Error('app.seats is invalid');
861
+ return { seats: app.seats === undefined ? open() : [...app.seats], game: {} };
862
+ },
863
+ restore: () => ({ dropHolds: false, game: () => ({}) }),
864
+ view: () => ({}),
865
+ busy: NO_BUSY_HOOK,
866
+ liveMatches: () => [],
867
+ usesSeats: () => true,
868
+ seatsFixed: () => false,
869
+ seatCeiling: () => size.max,
870
+ growSeats(room, seat) {
871
+ while (room.seats.length <= seat)
872
+ room.seats = [...room.seats, null];
873
+ },
874
+ trimSeats(room) {
875
+ while (room.seats.length > size.seats && room.seats.at(-1) === null)
876
+ room.seats = room.seats.slice(0, -1);
877
+ },
878
+ ...(size.relaySeats === undefined ? {} : { relaySeats: size.relaySeats }),
879
+ };
880
+ }