@journey-to-code/rooms 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js ADDED
@@ -0,0 +1,1037 @@
1
+ // Rooms: turn-based games (or anything with private per-person state) over @zubra/sync.
2
+ //
3
+ // The server is the only writer. A page never writes a document; it sends a move to
4
+ // `POST <mount>/<id>/act`, the room's `act` decides it, and the server writes every seat's view.
5
+ // `authorize` lets a player read only their own seat's view, so a hand stays in one browser.
6
+ //
7
+ // Collections:
8
+ // rooms/<id> public: seats (names, bots), whether it started, a summary,
9
+ // and the deadline that's running, if any (everyone reads)
10
+ // views/<id>/<seat> one seat's view of the game (that seat only)
11
+ // views/<id>/watch what someone watching may see: nobody's hand (everyone, if watching is allowed)
12
+ // games/<id> options, seed, when it was dealt, and seat holders (server only)
13
+ // moves/<id> every move and its time, one field per move, for replays (server only)
14
+ // chat/<id> the table's chat, one field per message (everyone)
15
+ import { createSyncServer, memoryLog } from "@zubra/sync/server";
16
+ export class RefusedMove extends Error {
17
+ name = "RefusedMove";
18
+ }
19
+ /** What a removed chat message says instead. */
20
+ export const REMOVED_TEXT = "(removed by a moderator)";
21
+ /** How long a message may be, and how often one player may send. */
22
+ export const CHAT_LIMIT = 280;
23
+ const CHAT_GAP_MS = 400;
24
+ /** setTimeout can't wait longer than this (about 24.8 days): a longer deadline wakes and waits again. */
25
+ const LONGEST_TIMEOUT = 2 ** 31 - 1;
26
+ const COOKIE = "rooms_player";
27
+ const ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
28
+ const randomId = (n) => Array.from(crypto.getRandomValues(new Uint8Array(n)), (b) => ALPHABET[b % ALPHABET.length]).join("");
29
+ /** A new player id: the secret a browser's cookie holds. */
30
+ export const newPlayerId = () => randomId(24);
31
+ /** Whether the browser reached us over HTTPS: directly, or through a proxy that says so (Railway). */
32
+ export function overHttps(request) {
33
+ if (!request)
34
+ return false;
35
+ const forwarded = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
36
+ if (forwarded)
37
+ return forwarded === "https";
38
+ try {
39
+ return new URL(request.url).protocol === "https:";
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ /**
46
+ * The Set-Cookie value that makes a browser this player, for a year. Over HTTPS it's also Secure, so
47
+ * the browser never sends it over plain http; plain-http development (localhost) still works.
48
+ */
49
+ export const playerCookie = (player, request) => `${COOKIE}=${player}; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000${overHttps(request) ? "; Secure" : ""}`;
50
+ export function playerOf(request) {
51
+ const cookie = request.headers.get("cookie") ?? "";
52
+ const match = cookie.match(new RegExp(`(?:^|;\\s*)${COOKIE}=([a-z0-9]+)`));
53
+ return match?.[1] ?? null;
54
+ }
55
+ const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } });
56
+ export function createRooms(def, options = {}) {
57
+ const mount = (options.mount ?? "/rooms").replace(/\/$/, "");
58
+ const fixedDelay = options.botDelay;
59
+ const grace = options.deadlineGrace ?? 5000;
60
+ const seatsFor = (o) => (typeof def.seats === "function" ? def.seats(o) : def.seats);
61
+ /** Run an app's hook without letting it break the room. */
62
+ const safely = (fn) => {
63
+ try {
64
+ fn();
65
+ }
66
+ catch (e) {
67
+ console.error("rooms: a hook threw", e);
68
+ }
69
+ };
70
+ const newSeed = options.seed ?? (() => crypto.getRandomValues(new Uint32Array(1))[0]);
71
+ const newId = options.id ?? (() => randomId(6));
72
+ const live = new Map();
73
+ const sync = createSyncServer({
74
+ mount: options.syncMount ?? "/_zb/sync",
75
+ log: options.log ?? memoryLog({ keep: "latest" }),
76
+ authorize: async ({ request, collection, key, kind }) => {
77
+ if (kind === "change")
78
+ return false; // the server is the only writer
79
+ if (collection === "rooms")
80
+ return true; // reading, and presence (who's at the table)
81
+ if (collection === "chat" && kind === "read")
82
+ return true;
83
+ if (collection === "views" && kind === "read") {
84
+ // The watch view holds only what every seat can already see.
85
+ if (key.endsWith("/watch"))
86
+ return (await options.spectators?.()) ?? true;
87
+ const [id, seat] = splitViewKey(key);
88
+ // A table of computer players has no hands to keep secret.
89
+ if ((await room(id))?.watchable)
90
+ return true;
91
+ const player = playerOf(request);
92
+ return player !== null && (await game(id))?.holders[seat] === player;
93
+ }
94
+ return false; // games and moves are the server's alone
95
+ },
96
+ });
97
+ const docs = sync.documents();
98
+ const splitViewKey = (key) => {
99
+ const at = key.lastIndexOf("/");
100
+ return [key.slice(0, at), Number(key.slice(at + 1))];
101
+ };
102
+ const game = async (id) => (await docs).get("games", id);
103
+ const room = async (id) => (await docs).get("rooms", id);
104
+ /** The live state of a room, replaying its move log after a restart. */
105
+ async function stateOf(id) {
106
+ const entry = live.get(id);
107
+ if (entry)
108
+ return entry;
109
+ // Two requests for a room that isn't in memory share one restore: a second copy of the room
110
+ // would mean a second deadline, and a timeout applied twice.
111
+ let pending = restoring.get(id);
112
+ if (!pending) {
113
+ pending = restore(id).finally(() => restoring.delete(id));
114
+ restoring.set(id, pending);
115
+ }
116
+ return pending;
117
+ }
118
+ const restoring = new Map();
119
+ async function restore(id) {
120
+ const r = await room(id);
121
+ const g = await game(id);
122
+ const entry = { state: null, moves: 0, version: r?.version ?? 0, bot: null, timer: null, last: Date.now(), table: tableOf(r, g), deadline: null, paused: g?.pausedMs ?? 0, pausedAt: g?.pausedAt ?? null };
123
+ if (g?.seed != null) {
124
+ // A game dealt before moves had times starts its clock now, for good: writing it down means
125
+ // every later replay counts from the same moment.
126
+ const startedAt = g.startedAt ?? Date.now();
127
+ if (g.startedAt == null)
128
+ void sync.write("games", id, { startedAt });
129
+ let state = def.setup(g.options, g.seed);
130
+ const log = (await docs).get("moves", id) ?? {};
131
+ const count = Object.keys(log).filter((k) => /^\d+$/.test(k)).length;
132
+ // Each move gets the time it was first decided at, so a game with clocks replays to the same
133
+ // state. A move from before times were kept took no time at all.
134
+ let last = startedAt;
135
+ for (let n = 0; n < count; n++) {
136
+ const { seat, move, at } = log[String(n)];
137
+ const when = Math.max(at ?? last, last);
138
+ state = def.act(state, seat, move, { at: when, elapsed: when - last });
139
+ last = when;
140
+ }
141
+ entry.state = state;
142
+ entry.moves = count;
143
+ entry.last = last;
144
+ }
145
+ live.set(id, entry);
146
+ // The clock kept running while the server was away: the deadline is where it was, measured from
147
+ // the last move's own time. If that has already passed, the seat gets a moment's grace first.
148
+ arm(id, entry, true);
149
+ const now = deadlineDoc(entry);
150
+ if (now?.at !== r?.deadline?.at || now?.seat !== r?.deadline?.seat)
151
+ void sync.write("rooms", id, { deadline: now });
152
+ return entry;
153
+ }
154
+ const tableOf = (r, g) => ({
155
+ // A room from before it had settings plays with the defaults.
156
+ settings: g?.settings ?? def.settings?.(undefined) ?? null,
157
+ seats: r?.seats ?? [],
158
+ });
159
+ /** The game's own clock: the server's, less the time the game has spent paused. It stands still during a pause. */
160
+ const gameNow = (entry) => (entry.pausedAt ?? Date.now()) - entry.paused;
161
+ /** The deadline as pages see it, in server time. */
162
+ const deadlineDoc = (entry) => (entry.deadline ? { at: entry.deadline.at + entry.paused, seat: entry.deadline.seat } : null);
163
+ function disarm(entry) {
164
+ if (entry.deadline?.timer)
165
+ clearTimeout(entry.deadline.timer);
166
+ entry.deadline = null;
167
+ }
168
+ /**
169
+ * Ask the game for its deadline in this state and set the one timer that keeps it. `sudden` is for a
170
+ * deadline nobody at the table saw coming (a restart, a changed setting): it's never closer than the
171
+ * grace period, unless the one it replaces already was. Returns whether there is one now.
172
+ */
173
+ function arm(id, entry, sudden = false) {
174
+ const before = entry.deadline ? entry.deadline.at + entry.paused : null;
175
+ disarm(entry);
176
+ // A paused game has no clock: it is armed again, with the time it had left, when it is resumed.
177
+ if (entry.pausedAt !== null)
178
+ return false;
179
+ if (!def.deadline || entry.state === null || def.finished?.(entry.state))
180
+ return false;
181
+ let due = null;
182
+ try {
183
+ due = def.deadline(entry.state, entry.table);
184
+ }
185
+ catch (e) {
186
+ console.error(`rooms: the deadline of ${id} threw`, e);
187
+ }
188
+ const asked = due ? (due.at ?? (due.after === undefined ? NaN : entry.last + due.after)) : NaN;
189
+ if (!due || !Number.isFinite(asked))
190
+ return false;
191
+ // The game asks in game time; the grace and the timers are the server's.
192
+ let wall = Math.round(asked) + entry.paused;
193
+ // The grace never puts off a deadline that was already armed, or asking twice would be a way to stall.
194
+ if (sudden)
195
+ wall = Math.max(wall, Math.min(Date.now() + grace, before ?? Infinity));
196
+ const at = wall - entry.paused;
197
+ const armed = { at, fire: at + Math.max(0, due.grace ?? 0), seat: due.seat, timer: null };
198
+ const wait = () => {
199
+ armed.timer = setTimeout(() => {
200
+ armed.timer = null;
201
+ if (entry.deadline !== armed)
202
+ return; // a move got in first
203
+ if (Date.now() < armed.fire + entry.paused)
204
+ return wait(); // longer than one timer can sleep, or the timer woke early
205
+ timeUp(id, entry, armed);
206
+ }, Math.min(Math.max(armed.fire + entry.paused - Date.now(), 0), LONGEST_TIMEOUT));
207
+ };
208
+ entry.deadline = armed;
209
+ wait();
210
+ return true;
211
+ }
212
+ /**
213
+ * Time ran out: make the game's timeout move, exactly as if the seat had sent it. Everything up to
214
+ * recording the move happens with no await, and a move that got in first has already put this
215
+ * deadline away (see apply), so a move and a timeout can never both land on the same state.
216
+ */
217
+ function timeUp(id, entry, armed) {
218
+ entry.deadline = null;
219
+ if (entry.pausedAt !== null)
220
+ return; // paused: no clock runs
221
+ let applied = null;
222
+ try {
223
+ const due = entry.state === null ? null : def.deadline(entry.state, entry.table);
224
+ const move = due && due.seat === armed.seat ? due.move() : null;
225
+ if (move !== null)
226
+ applied = { before: apply(id, entry, armed.seat, move), move };
227
+ }
228
+ catch (e) {
229
+ console.error(`rooms: the timeout move in ${id} for seat ${armed.seat} was refused`, e);
230
+ }
231
+ // Nothing to do for that seat: the game waits, and pages stop counting down.
232
+ if (!applied)
233
+ return void sync.write("rooms", id, { deadline: null });
234
+ void settle(id, entry, applied.before, armed.seat, applied.move, true);
235
+ }
236
+ /** After any move: tell everyone, then let the bots and the clock carry on (or put the game away). */
237
+ async function settle(id, entry, before, seat, move, timeout = false, admin = false) {
238
+ const after = entry.state;
239
+ await publish(id, entry);
240
+ void moved(id, before, after, seat, move, timeout, admin);
241
+ if (!forgetIfFinished(id, entry))
242
+ void driveBots(id);
243
+ }
244
+ /** Messages per room, counted once from the log and then kept here. */
245
+ const chatCount = new Map();
246
+ const lastSaid = new Map();
247
+ /** Add a message to a room's chat, as a seat. Bots speak through this too. */
248
+ async function say(id, seat, text) {
249
+ const clean = text.replace(/\s+/g, " ").trim().slice(0, CHAT_LIMIT);
250
+ if (!clean)
251
+ return "Say something first.";
252
+ const r = await room(id);
253
+ const who = r?.seats[seat];
254
+ if (!r || !who)
255
+ return "No such seat.";
256
+ return append(id, { seat, name: who.name ?? `Seat ${seat + 1}`, text: clean, at: Date.now(), bot: who.bot });
257
+ }
258
+ /** Put a message in a room's chat, numbering it after the ones already there. */
259
+ async function append(id, message) {
260
+ if (!chatCount.has(id)) {
261
+ const existing = (await docs).get("chat", id) ?? {};
262
+ chatCount.set(id, Object.keys(existing).filter((k) => /^m\d+$/.test(k)).length);
263
+ }
264
+ const n = chatCount.get(id);
265
+ chatCount.set(id, n + 1);
266
+ await sync.write("chat", id, { [`m${String(n).padStart(6, "0")}`]: message });
267
+ return message;
268
+ }
269
+ /**
270
+ * A notice from the server to everyone at a table, in the chat ("The host paused the game"). It is not a
271
+ * seat's message: `seat` is -1, `notice` is true and `name` is `from`. Resolves to the message, or a problem.
272
+ */
273
+ async function announce(id, text, from = "The host") {
274
+ const clean = text.replace(/\s+/g, " ").trim().slice(0, CHAT_LIMIT);
275
+ if (!clean)
276
+ return "Say something first.";
277
+ if (!(await room(id)))
278
+ return "No such table.";
279
+ return append(id, { seat: -1, name: from.replace(/\s+/g, " ").trim().slice(0, 40) || "The host", text: clean, at: Date.now(), bot: false, notice: true });
280
+ }
281
+ /** Open a new room with these options. Resolves to its id. */
282
+ async function create(roomOptions, given) {
283
+ const id = newId();
284
+ const n = seatsFor(roomOptions);
285
+ const settings = def.settings ? def.settings(given) : null;
286
+ await sync.write("games", id, { options: roomOptions, settings, seed: null, holders: Array(n).fill(null) });
287
+ await sync.write("rooms", id, { seats: Array.from({ length: n }, () => ({ name: null, bot: false })), info: def.info?.(roomOptions) ?? null, settings, started: false, summary: null, version: 0 });
288
+ return id;
289
+ }
290
+ /**
291
+ * Seat a player (by their player id) or a bot, from server code, before the game starts. An app
292
+ * that sets up a table itself (a challenge, say) uses these instead of the HTTP endpoints.
293
+ */
294
+ async function seatPlayer(id, seat, player, name) {
295
+ const g = await game(id);
296
+ const r = await room(id);
297
+ if (!g || !r || r.started)
298
+ throw new Error("That table isn't open.");
299
+ const holders = g.holders.map((h) => (h === player ? null : h));
300
+ holders[seat] = player;
301
+ const seats = r.seats.map((s, i) => (holders[i] === null && !s.bot ? { name: null, bot: false } : s));
302
+ seats[seat] = { name: name.trim().slice(0, 20) || "Player", bot: false };
303
+ await sync.write("games", id, { holders });
304
+ await sync.write("rooms", id, { seats });
305
+ await seatsChanged(id);
306
+ }
307
+ async function seatBot(id, seat, name) {
308
+ const r = await room(id);
309
+ if (!r || r.started)
310
+ throw new Error("That table isn't open.");
311
+ const seats = [...r.seats];
312
+ seats[seat] = { name, bot: true };
313
+ await sync.write("rooms", id, { seats });
314
+ await seatsChanged(id);
315
+ }
316
+ /** Free a person's seat before the game starts (they left, say). Resolves to whether anyone was there. */
317
+ async function unseat(id, seat) {
318
+ const g = await game(id);
319
+ const r = await room(id);
320
+ if (!g || !r || r.started || !g.holders[seat])
321
+ return false;
322
+ const holders = [...g.holders];
323
+ holders[seat] = null;
324
+ const seats = [...r.seats];
325
+ seats[seat] = { name: null, bot: false };
326
+ await sync.write("games", id, { holders });
327
+ await sync.write("rooms", id, { seats });
328
+ await seatsChanged(id);
329
+ return true;
330
+ }
331
+ /**
332
+ * Take a person's seat away and sit a bot there, at any point. In a game that's been dealt, the bot
333
+ * plays on from where they were. Resolves to whether anyone was there.
334
+ */
335
+ async function replaceWithBot(id, seat, name) {
336
+ const g = await game(id);
337
+ const r = await room(id);
338
+ if (!g || !r || !g.holders[seat])
339
+ return false;
340
+ const holders = [...g.holders];
341
+ holders[seat] = null;
342
+ const seats = [...r.seats];
343
+ seats[seat] = { name, bot: true };
344
+ await sync.write("games", id, { holders });
345
+ await sync.write("rooms", id, { seats });
346
+ if (!r.started)
347
+ return await seatsChanged(id), true;
348
+ if (r.closed)
349
+ return true; // nothing plays on at a closed table
350
+ const entry = await stateOf(id);
351
+ entry.table = { ...entry.table, seats };
352
+ stopBot(entry);
353
+ // A clock that was running on the person isn't the bot's: work it out again.
354
+ if (def.deadline && entry.state !== null) {
355
+ const before = deadlineDoc(entry);
356
+ arm(id, entry, true);
357
+ const now = deadlineDoc(entry);
358
+ if (before?.at !== now?.at || before?.seat !== now?.seat)
359
+ void sync.write("rooms", id, { deadline: now });
360
+ }
361
+ void driveBots(id);
362
+ return true;
363
+ }
364
+ /** Tell the app the seats changed. */
365
+ async function seatsChanged(id) {
366
+ if (!options.onSeats)
367
+ return;
368
+ const r = await room(id);
369
+ if (r)
370
+ safely(() => options.onSeats({ id, room: r }));
371
+ }
372
+ /** Deal: from a seated player's request, or from server code. Resolves to a problem, or null. */
373
+ async function start(id) {
374
+ const g = await game(id);
375
+ const r = await room(id);
376
+ if (!g || !r)
377
+ return "No such table.";
378
+ if (r.started)
379
+ return null;
380
+ if (r.seats.some((s, i) => !s.bot && !g.holders[i]))
381
+ return "Every seat needs a player or a bot.";
382
+ const seed = newSeed();
383
+ const entry = await stateOf(id);
384
+ if (entry.state !== null)
385
+ return null; // two people pressed Deal at once
386
+ const startedAt = Date.now();
387
+ entry.paused = 0;
388
+ entry.pausedAt = null;
389
+ entry.state = def.setup(g.options, seed);
390
+ entry.moves = 0;
391
+ entry.last = startedAt;
392
+ entry.table = tableOf(r, g);
393
+ await sync.write("games", id, { seed, startedAt });
394
+ await publish(id, entry);
395
+ if (options.onStart) {
396
+ const started = await room(id);
397
+ if (started)
398
+ safely(() => options.onStart({ id, state: entry.state, room: started }));
399
+ }
400
+ void driveBots(id);
401
+ return null;
402
+ }
403
+ /** Set the seats for good (after seating everyone from server code), and name the table. */
404
+ async function lock(id, label) {
405
+ await sync.write("rooms", id, { locked: true, ...(label ? { label: label.slice(0, 60) } : {}) });
406
+ }
407
+ /**
408
+ * Make a table one to watch: its seats are set (all computer players, seated from server code)
409
+ * and anyone may read every seat's view. Refuses a table with a person at it.
410
+ */
411
+ async function exhibit(id, label) {
412
+ const g = await game(id);
413
+ const r = await room(id);
414
+ if (!g || !r || g.holders.some(Boolean) || r.seats.some((s) => !s.bot))
415
+ throw new Error("Only a table of computer players can be watched this way.");
416
+ await sync.write("rooms", id, { locked: true, watchable: true, ...(label ? { label: label.slice(0, 60) } : {}) });
417
+ }
418
+ /**
419
+ * Close a table for good (moderation): bots stop, and every later seat, move or message is
420
+ * refused with `reason`. Pages see `closed` on the room. Resolves false when there's no such table.
421
+ */
422
+ async function closeTable(id, reason) {
423
+ if (!(await room(id)))
424
+ return false;
425
+ await sync.write("rooms", id, { closed: reason.replace(/\s+/g, " ").trim().slice(0, 200) || "This table was closed." });
426
+ const entry = live.get(id);
427
+ if (entry)
428
+ stopBot(entry);
429
+ live.delete(id);
430
+ return true;
431
+ }
432
+ /**
433
+ * Pause a game that's being played (moderation): nobody can move, no bot plays and no clock runs, until
434
+ * `resume`. Chat carries on, and pages see `paused` on the room. The game's own clock stands still, so
435
+ * a turn timer or a chess clock has the time left that it had, and `act` sees no time pass. Resolves to
436
+ * a problem, or null (also when it is paused already).
437
+ */
438
+ async function pause(id, reason = "") {
439
+ const g = await game(id);
440
+ const r = await room(id);
441
+ if (!g || !r)
442
+ return "No such table.";
443
+ if (r.closed)
444
+ return "That table is closed.";
445
+ if (!r.started)
446
+ return "The game hasn't started.";
447
+ const entry = await stateOf(id);
448
+ if (entry.state === null || def.finished?.(entry.state))
449
+ return "The game is over.";
450
+ if (entry.pausedAt !== null)
451
+ return null;
452
+ // From here to the write there is no await that matters: a move that arrives now finds the table paused.
453
+ const at = Date.now();
454
+ entry.pausedAt = at;
455
+ stopBot(entry);
456
+ disarm(entry);
457
+ const why = reason.replace(/\s+/g, " ").trim().slice(0, 200);
458
+ await sync.write("games", id, { pausedAt: at });
459
+ await sync.write("rooms", id, { paused: { at, reason: why }, deadline: null });
460
+ return null;
461
+ }
462
+ /** Let a paused game go on. Its clocks have the time they had left; the bots play again. Resolves to a problem, or null. */
463
+ async function resume(id) {
464
+ const g = await game(id);
465
+ const r = await room(id);
466
+ if (!g || !r)
467
+ return "No such table.";
468
+ if (!r.paused && g.pausedAt == null)
469
+ return "That table isn't paused.";
470
+ const entry = await stateOf(id);
471
+ if (entry.pausedAt === null)
472
+ return "That table isn't paused.";
473
+ entry.paused += Math.max(0, Date.now() - entry.pausedAt);
474
+ entry.pausedAt = null;
475
+ // One write for the game: the time paused and the end of the pause go down together.
476
+ await sync.write("games", id, { pausedMs: entry.paused, pausedAt: null });
477
+ arm(id, entry);
478
+ await sync.write("rooms", id, { paused: null, deadline: deadlineDoc(entry), ...(def.deadline ? { moved: entry.last + entry.paused } : {}) });
479
+ void driveBots(id);
480
+ return null;
481
+ }
482
+ /**
483
+ * Make a move for a seat at a paused table (moderation): as if the seat had sent it, through `act`,
484
+ * into the move log (so a restart replays it), and `onMove` is told it was the admin's. The table has
485
+ * to be paused first, so no bot or clock can move at the same time. Resolves to a problem, or null.
486
+ */
487
+ async function moveFor(id, seat, move) {
488
+ const g = await game(id);
489
+ const r = await room(id);
490
+ if (!g || !r)
491
+ return "No such table.";
492
+ if (r.closed)
493
+ return "That table is closed.";
494
+ if (!Number.isInteger(seat) || seat < 0 || seat >= r.seats.length)
495
+ return "No such seat.";
496
+ const entry = await stateOf(id);
497
+ if (entry.state === null)
498
+ return "The game hasn't started.";
499
+ if (entry.pausedAt === null)
500
+ return "Pause the table first.";
501
+ let before;
502
+ try {
503
+ before = apply(id, entry, seat, move, true);
504
+ }
505
+ catch (e) {
506
+ return e instanceof Error ? e.message : "That move isn't allowed.";
507
+ }
508
+ const over = def.finished?.(entry.state) === true;
509
+ const heldSince = entry.pausedAt;
510
+ await settle(id, entry, before, seat, move, false, true);
511
+ // A game that ended on that move isn't paused any more: there is nothing left to hold.
512
+ if (over) {
513
+ await sync.write("games", id, { pausedMs: entry.paused + Math.max(0, Date.now() - heldSince), pausedAt: null });
514
+ await sync.write("rooms", id, { paused: null });
515
+ }
516
+ return null;
517
+ }
518
+ /**
519
+ * `moveFor`, with the move the game's own computer player would make for the seat (`bot`, or `think` if
520
+ * that is what the game has). For a player who has gone, in any game that has bots, with no move to
521
+ * write by hand. Resolves to a problem, or null; the problem is "That seat has no move to make." when the
522
+ * bot has none, and "This game has no computer players." when it has no bot.
523
+ */
524
+ async function botMoveFor(id, seat) {
525
+ if (!def.bot && !def.think)
526
+ return "This game has no computer players.";
527
+ const g = await game(id);
528
+ const r = await room(id);
529
+ if (!g || !r)
530
+ return "No such table.";
531
+ if (r.closed)
532
+ return "That table is closed.";
533
+ if (!Number.isInteger(seat) || seat < 0 || seat >= r.seats.length)
534
+ return "No such seat.";
535
+ const entry = await stateOf(id);
536
+ if (entry.state === null)
537
+ return "The game hasn't started.";
538
+ if (entry.pausedAt === null)
539
+ return "Pause the table first.";
540
+ const stop = new AbortController();
541
+ const state = entry.state;
542
+ let move;
543
+ try {
544
+ move = await ask(id, state, seat, r.seats[seat]?.name ?? "", g.settings ?? def.settings?.(undefined), stop);
545
+ }
546
+ catch (e) {
547
+ console.error(`rooms: the bot in ${id} seat ${seat} couldn't think`, e);
548
+ return "The computer player couldn't find a move.";
549
+ }
550
+ if (move === null)
551
+ return "That seat has no move to make.";
552
+ if (entry.state !== state)
553
+ return "The game moved on. Try again.";
554
+ return moveFor(id, seat, move);
555
+ }
556
+ /**
557
+ * Take a person out of a seat (moderation). Before the game starts the seat is simply free again;
558
+ * once it has, a bot called `bot` plays the seat on, so the others can finish. Resolves to a
559
+ * problem, or null.
560
+ */
561
+ async function removePlayer(id, seat, bot = "Bot") {
562
+ const g = await game(id);
563
+ const r = await room(id);
564
+ if (!g || !r)
565
+ return "No such table.";
566
+ if (!Number.isInteger(seat) || seat < 0 || seat >= r.seats.length || !g.holders[seat])
567
+ return "Nobody's sitting there.";
568
+ const gone = r.started ? await replaceWithBot(id, seat, bot.trim().slice(0, 20) || "Bot") : await unseat(id, seat);
569
+ return gone ? null : "Nobody's sitting there.";
570
+ }
571
+ /** Take the words out of a chat message (moderation). `key` is the message's field in `chat/<id>`. */
572
+ async function redact(id, key) {
573
+ const message = ((await docs).get("chat", id) ?? {})[key];
574
+ if (!/^m\d+$/.test(key) || !message)
575
+ return false;
576
+ await sync.write("chat", id, { [key]: { ...message, text: REMOVED_TEXT, removed: true } });
577
+ return true;
578
+ }
579
+ /** Who holds each seat (player ids), for server code. Never send these to a page. */
580
+ async function holders(id) {
581
+ return (await game(id))?.holders ?? [];
582
+ }
583
+ /** A finished game no longer needs its state in memory: a later request replays it from the log. */
584
+ function forgetIfFinished(id, entry) {
585
+ if (entry.state === null || !def.finished?.(entry.state))
586
+ return false;
587
+ stopBot(entry);
588
+ disarm(entry);
589
+ live.delete(id);
590
+ return true;
591
+ }
592
+ /** Write every seat's view and the public room doc. */
593
+ async function publish(id, entry) {
594
+ entry.version += 1;
595
+ // The state changed, so its deadline did: arm it before anything is awaited, and publish it with the rest.
596
+ arm(id, entry);
597
+ const deadline = deadlineDoc(entry);
598
+ const writes = [];
599
+ if (entry.state !== null) {
600
+ const n = (await game(id))?.holders.length ?? 0;
601
+ const views = Array.from({ length: n }, (_, seat) => def.view(entry.state, seat));
602
+ for (const [seat, view] of views.entries())
603
+ writes.push(sync.write("views", `${id}/${seat}`, { view, version: entry.version }));
604
+ if (def.watch)
605
+ writes.push(sync.write("views", `${id}/watch`, { view: def.watch(entry.state, views), version: entry.version }));
606
+ }
607
+ writes.push(sync.write("rooms", id, {
608
+ started: entry.state !== null,
609
+ summary: entry.state !== null && def.summary ? def.summary(entry.state) : null,
610
+ ...(def.deadline ? { deadline, moved: entry.last + entry.paused } : {}),
611
+ version: entry.version,
612
+ }));
613
+ await Promise.all(writes);
614
+ }
615
+ /** Apply a move. No await between deciding and recording it, so two moves can't interleave. */
616
+ function apply(id, entry, seat, move, admin = false) {
617
+ if (entry.pausedAt !== null && !admin)
618
+ throw new RefusedMove("The table is paused.");
619
+ const before = entry.state;
620
+ const at = Math.max(gameNow(entry), entry.last); // a clock set back never makes a move take less than no time
621
+ const next = def.act(before, seat, move, { at, elapsed: at - entry.last }); // throws to refuse
622
+ entry.state = next;
623
+ entry.last = at;
624
+ // The deadline was for the state before this move: put it away now, so it can't fire on this one.
625
+ disarm(entry);
626
+ const n = entry.moves++;
627
+ void sync.write("moves", id, { [String(n)]: { seat, move, at } });
628
+ return before;
629
+ }
630
+ async function moved(id, before, after, seat, move, timeout = false, admin = false) {
631
+ if (!options.onMove)
632
+ return;
633
+ const r = await room(id);
634
+ if (r)
635
+ safely(() => options.onMove({ id, before, after, seat, move, room: r, ...(timeout ? { timeout } : {}), ...(admin ? { admin } : {}) }));
636
+ }
637
+ /** Stop the bot that's about to move, whatever it was doing: its pause ends and its answer, if one is still coming, is dropped. */
638
+ function stopBot(entry) {
639
+ if (entry.timer)
640
+ clearTimeout(entry.timer);
641
+ entry.timer = null;
642
+ entry.bot?.stop.abort();
643
+ entry.bot = null;
644
+ }
645
+ /** Ask for a bot's move: from `think` when the room has one (it may answer later), else from `bot`. */
646
+ const ask = (id, state, seat, name, settings, stop) => def.think ? def.think(state, seat, name, settings, { signal: stop.signal, table: id }) : def.bot(state, seat, name, settings);
647
+ const later = (answer) => typeof answer?.then === "function";
648
+ /**
649
+ * If it's a bot's move, make it after a pause. The think starts as the pause does, so a think
650
+ * that takes a while (see RoomDefinition.think) hides inside the pause instead of adding to it.
651
+ */
652
+ async function driveBots(id) {
653
+ const entry = await stateOf(id);
654
+ if ((!def.bot && !def.think) || entry.state === null || entry.bot)
655
+ return;
656
+ const current = await room(id);
657
+ if (current?.closed || current?.paused || entry.pausedAt !== null)
658
+ return;
659
+ const seats = current?.seats ?? [];
660
+ // A room from before it had settings plays with the defaults.
661
+ const settings = (await game(id))?.settings ?? def.settings?.(undefined);
662
+ if (entry.bot)
663
+ return; // set while this was reading
664
+ for (let seat = 0; seat < seats.length; seat++) {
665
+ if (!seats[seat]?.bot)
666
+ continue;
667
+ const name = seats[seat].name ?? "";
668
+ const stop = new AbortController();
669
+ const answer = ask(id, entry.state, seat, name, settings, stop);
670
+ if (answer === null)
671
+ continue;
672
+ const delay = fixedDelay ?? def.botDelay?.(entry.state, seat, name, settings) ?? 700;
673
+ const turn = { seat, name, settings, state: entry.state, answer, stop };
674
+ // An answer that fails is reported when the pause ends; until then it mustn't count as unhandled.
675
+ if (later(answer))
676
+ answer.catch(() => { });
677
+ entry.bot = turn;
678
+ entry.timer = setTimeout(() => {
679
+ entry.timer = null;
680
+ void play(id, entry, turn);
681
+ }, delay);
682
+ return;
683
+ }
684
+ }
685
+ /**
686
+ * A bot's pause is over: play its move, on the state it was worked out for and no other. A pause
687
+ * isn't restarted because someone else moved meanwhile (in a race, a quick person mustn't keep
688
+ * resetting the computer's clock): the move is worked out again from the table as it is now, and
689
+ * played as soon as it's known.
690
+ */
691
+ async function play(id, entry, turn) {
692
+ for (;;) {
693
+ if (entry.bot !== turn || entry.state === null)
694
+ return; // stopped: nobody wants this move any more
695
+ if (entry.state !== turn.state) {
696
+ turn.stop.abort();
697
+ turn.stop = new AbortController();
698
+ turn.state = entry.state;
699
+ try {
700
+ const answer = ask(id, turn.state, turn.seat, turn.name, turn.settings, turn.stop);
701
+ // Not this seat's move any more: see whose it is now.
702
+ if (answer === null)
703
+ return void ((entry.bot = null), live.get(id) === entry && driveBots(id));
704
+ turn.answer = answer;
705
+ }
706
+ catch (e) {
707
+ console.error(`rooms: the bot in ${id} seat ${turn.seat} couldn't think`, e);
708
+ return void (entry.bot = null);
709
+ }
710
+ }
711
+ const state = turn.state;
712
+ let move = turn.answer;
713
+ if (later(turn.answer)) {
714
+ try {
715
+ move = await turn.answer;
716
+ }
717
+ catch (e) {
718
+ if (entry.bot !== turn)
719
+ return;
720
+ console.error(`rooms: the bot in ${id} seat ${turn.seat} couldn't think`, e);
721
+ return void (entry.bot = null);
722
+ }
723
+ if (entry.bot !== turn)
724
+ return; // stopped while it was thinking: the answer is dropped
725
+ // The game moved on while it was thinking (a person moved, a deadline's move): the answer
726
+ // was for a table that's gone. Drop it and ask again.
727
+ if (entry.state !== state)
728
+ continue;
729
+ if (move === null) {
730
+ console.error(`rooms: the bot in ${id} seat ${turn.seat} had a move to make and then made none`);
731
+ return void (entry.bot = null);
732
+ }
733
+ }
734
+ entry.bot = null;
735
+ if (entry.pausedAt !== null)
736
+ return; // paused while it was thinking: nothing plays
737
+ let before;
738
+ try {
739
+ before = apply(id, entry, turn.seat, move);
740
+ }
741
+ catch (e) {
742
+ console.error(`rooms: bot in ${id} seat ${turn.seat} made a refused move`, e);
743
+ return;
744
+ }
745
+ await settle(id, entry, before, turn.seat, move);
746
+ return;
747
+ }
748
+ }
749
+ async function body(request) {
750
+ try {
751
+ const value = await request.json();
752
+ return value && typeof value === "object" ? value : {};
753
+ }
754
+ catch {
755
+ return {};
756
+ }
757
+ }
758
+ async function handleRooms(request, path) {
759
+ const parts = path.split("/").filter(Boolean);
760
+ const method = request.method;
761
+ // POST /rooms { options, settings? } → { id }
762
+ if (parts.length === 0 && method === "POST") {
763
+ const { options: given, settings } = await body(request);
764
+ const refused = await options.allow?.(given ?? {});
765
+ if (refused)
766
+ return json({ error: refused }, 403);
767
+ return json({ id: await create((given ?? {}), settings) }, 201);
768
+ }
769
+ const id = parts[0];
770
+ const action = parts[1] ?? "";
771
+ const g = await game(id);
772
+ const r = await room(id);
773
+ if (!g || !r)
774
+ return json({ error: "There's no table with that code." }, 404);
775
+ const player = playerOf(request);
776
+ const mySeat = player ? g.holders.indexOf(player) : -1;
777
+ // GET /rooms/:id → the public room and which seat (if any) this browser holds
778
+ // `now` is the server's clock, so a page can count down to a deadline by it and not its own.
779
+ if (action === "" && method === "GET")
780
+ return json({ id, ...r, seat: mySeat >= 0 ? mySeat : null, now: Date.now() });
781
+ if (method !== "POST")
782
+ return json({ error: "Not found" }, 404);
783
+ if (r.closed)
784
+ return json({ error: r.closed }, 410);
785
+ const input = await body(request);
786
+ if (action === "sit") {
787
+ if (r.locked)
788
+ return json({ error: "The seats at this table are already set." }, 409);
789
+ const seat = Number(input.seat);
790
+ const name = String(input.name ?? "").trim().slice(0, 20) || "Player";
791
+ if (!Number.isInteger(seat) || seat < 0 || seat >= r.seats.length)
792
+ return json({ error: "No such seat." }, 400);
793
+ if (r.started && mySeat !== seat)
794
+ return json({ error: "This game has started." }, 409);
795
+ const holder = g.holders[seat];
796
+ if ((holder && holder !== player) || r.seats[seat]?.bot)
797
+ return json({ error: "Someone's already sitting there." }, 409);
798
+ const me = player ?? newPlayerId();
799
+ const holders = g.holders.map((h) => (h === me ? null : h));
800
+ holders[seat] = me;
801
+ const seats = r.seats.map((s, i) => (holders[i] === null && !s.bot ? { name: null, bot: false } : s));
802
+ seats[seat] = { name, bot: false };
803
+ await sync.write("games", id, { holders });
804
+ await sync.write("rooms", id, { seats });
805
+ const entry = live.get(id);
806
+ if (entry)
807
+ entry.table = { ...entry.table, seats };
808
+ await seatsChanged(id);
809
+ return json({ seat }, 200, player ? {} : { "set-cookie": playerCookie(me, request) });
810
+ }
811
+ if (mySeat < 0)
812
+ return json({ error: "Take a seat first." }, 403);
813
+ // POST /rooms/:id/stand → give up your seat, before the game starts
814
+ if (action === "stand") {
815
+ if (r.started)
816
+ return json({ error: "This game has started." }, 409);
817
+ if (r.locked)
818
+ return json({ error: "The seats at this table are already set." }, 409);
819
+ await unseat(id, mySeat);
820
+ return json({ ok: true });
821
+ }
822
+ // POST /rooms/:id/settings { settings } → anyone seated changes the table's settings, mid-game too.
823
+ // A bot already waiting to move starts over at the new pace.
824
+ if (action === "settings") {
825
+ if (!def.settings)
826
+ return json({ error: "This table has no settings." }, 404);
827
+ const settings = def.settings(input.settings);
828
+ await sync.write("games", id, { settings });
829
+ await sync.write("rooms", id, { settings });
830
+ const entry = live.get(id);
831
+ if (entry)
832
+ stopBot(entry);
833
+ // A deadline may depend on the settings (a turn timer): work it out again. The clock isn't
834
+ // restarted, or changing a setting would be a way to stall.
835
+ if (entry && def.deadline && entry.state !== null) {
836
+ const before = deadlineDoc(entry);
837
+ entry.table = { ...entry.table, settings };
838
+ arm(id, entry, true);
839
+ const now = deadlineDoc(entry);
840
+ if (before?.at !== now?.at || before?.seat !== now?.seat)
841
+ void sync.write("rooms", id, { deadline: now });
842
+ }
843
+ void driveBots(id);
844
+ return json({ settings });
845
+ }
846
+ if (action === "bot") {
847
+ const seat = Number(input.seat);
848
+ const add = input.add !== false;
849
+ if (r.started)
850
+ return json({ error: "This game has started." }, 409);
851
+ if (r.locked)
852
+ return json({ error: "The seats at this table are already set." }, 409);
853
+ if (!Number.isInteger(seat) || seat < 0 || seat >= r.seats.length || g.holders[seat])
854
+ return json({ error: "That seat isn't free." }, 409);
855
+ const seats = [...r.seats];
856
+ seats[seat] = add ? { name: String(input.name ?? `Bot ${seat + 1}`), bot: true } : { name: null, bot: false };
857
+ await sync.write("rooms", id, { seats });
858
+ await seatsChanged(id);
859
+ return json({ ok: true });
860
+ }
861
+ if (action === "start") {
862
+ const problem = await start(id);
863
+ return problem ? json({ error: problem }, 409) : json({ ok: true });
864
+ }
865
+ // POST /rooms/:id/say { text }
866
+ if (action === "say") {
867
+ const key = `${id}/${mySeat}`;
868
+ const now = Date.now();
869
+ if (now - (lastSaid.get(key) ?? 0) < CHAT_GAP_MS)
870
+ return json({ error: "Slow down a little." }, 429);
871
+ const checked = options.beforeSay ? await options.beforeSay({ id, seat: mySeat, text: String(input.text ?? ""), room: r }) : String(input.text ?? "");
872
+ if (typeof checked !== "string")
873
+ return json({ error: checked.error }, 403);
874
+ const result = await say(id, mySeat, checked);
875
+ if (typeof result === "string")
876
+ return json({ error: result }, 400);
877
+ lastSaid.set(key, now); // only a message that was sent counts toward the pace
878
+ if (options.onSay) {
879
+ const said = await room(id);
880
+ if (said)
881
+ safely(() => options.onSay({ id, message: result, room: said }));
882
+ }
883
+ return json(result);
884
+ }
885
+ if (action === "act") {
886
+ const entry = await stateOf(id);
887
+ if (entry.state === null)
888
+ return json({ error: "The game hasn't started." }, 409);
889
+ if (entry.pausedAt !== null)
890
+ return json({ error: `The table is paused${r.paused?.reason ? `: ${r.paused.reason}` : "."}` }, 423);
891
+ let before;
892
+ try {
893
+ before = apply(id, entry, mySeat, input.move);
894
+ }
895
+ catch (e) {
896
+ return json({ error: e instanceof Error ? e.message : "That move isn't allowed." }, 400);
897
+ }
898
+ await settle(id, entry, before, mySeat, input.move);
899
+ return json({ ok: true });
900
+ }
901
+ return json({ error: "Not found" }, 404);
902
+ }
903
+ // Deadlines have to be kept even if nobody opens the table again after a restart (a day a move):
904
+ // bring back every room that had a clock running. Rooms without one wait for their next request.
905
+ const restored = def.deadline
906
+ ? docs.then(async (d) => {
907
+ for (const r of d.all("rooms"))
908
+ if (r.started && r.deadline)
909
+ await stateOf(r.key).catch((e) => console.error(`rooms: couldn't restore ${r.key}`, e));
910
+ }, (e) => console.error("rooms: couldn't read the rooms to restore their deadlines", e))
911
+ : Promise.resolve();
912
+ return {
913
+ sync,
914
+ /** Resolves once the rooms that had a deadline running before a restart have theirs again. */
915
+ restored,
916
+ create,
917
+ say,
918
+ announce,
919
+ seatPlayer,
920
+ seatBot,
921
+ unseat,
922
+ replaceWithBot,
923
+ start,
924
+ lock,
925
+ exhibit,
926
+ /** Set what the cards look like at a table (anything the app's pages understand), or null for the app's own. */
927
+ setDeck: async (id, deck) => void (await sync.write("rooms", id, { deck: deck ?? null })),
928
+ /** Get a table's computer players moving again (after a restart, nothing else would wake a table with no people). */
929
+ nudge: (id) => void driveBots(id),
930
+ holders,
931
+ closeTable,
932
+ pause,
933
+ resume,
934
+ moveFor,
935
+ botMoveFor,
936
+ removePlayer,
937
+ redact,
938
+ /** The public room doc, or undefined. */
939
+ room,
940
+ /** How many rooms have their state in memory (finished ones are dropped). */
941
+ get inMemory() {
942
+ return live.size;
943
+ },
944
+ /** Answers rooms and sync requests; null for anything else. */
945
+ async fetch(request) {
946
+ const { pathname } = new URL(request.url);
947
+ if (pathname === mount || pathname.startsWith(`${mount}/`))
948
+ return handleRooms(request, pathname.slice(mount.length));
949
+ return sync.fetch(request);
950
+ },
951
+ /** For Node's http: answers rooms and sync requests and resolves true, else false. */
952
+ async handle(req, res) {
953
+ const url = new URL(req.url ?? "/", "http://localhost");
954
+ if (url.pathname === mount || url.pathname.startsWith(`${mount}/`)) {
955
+ const chunks = [];
956
+ for await (const chunk of req)
957
+ chunks.push(chunk);
958
+ const request = new Request(url, {
959
+ method: req.method,
960
+ headers: req.headers,
961
+ body: req.method === "GET" || req.method === "HEAD" ? undefined : Buffer.concat(chunks),
962
+ });
963
+ const response = await handleRooms(request, url.pathname.slice(mount.length));
964
+ res.writeHead(response.status, Object.fromEntries(response.headers));
965
+ res.end(Buffer.from(await response.arrayBuffer()));
966
+ return true;
967
+ }
968
+ return sync.handle(req, res);
969
+ },
970
+ /** Stop bot timers and deadlines (for tests and shutdown). */
971
+ close() {
972
+ for (const entry of live.values()) {
973
+ stopBot(entry);
974
+ disarm(entry);
975
+ }
976
+ },
977
+ };
978
+ }
979
+ const same = (a, b) => {
980
+ if (a === b)
981
+ return true;
982
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
983
+ return false;
984
+ if (Array.isArray(a) !== Array.isArray(b))
985
+ return false;
986
+ const ka = Object.keys(a);
987
+ const kb = Object.keys(b);
988
+ return ka.length === kb.length && ka.every((k) => same(a[k], b[k]));
989
+ };
990
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
991
+ /** What a list of values have in common: the value where they all agree; where they don't, nothing (see sharedView). */
992
+ function common(values) {
993
+ const first = values[0];
994
+ if (values.every((v) => same(v, first)))
995
+ return first;
996
+ // Lists of the same length are compared place by place: a list of seats, a grid of cards.
997
+ if (values.every(Array.isArray)) {
998
+ const lists = values;
999
+ return lists.every((l) => l.length === lists[0].length) ? lists[0].map((_, i) => common(lists.map((l) => l[i]))) : [];
1000
+ }
1001
+ // Records with the same keys are compared key by key. Anything else that differs is simply not shown.
1002
+ if (values.every(isRecord)) {
1003
+ const records = values;
1004
+ const keys = Object.keys(records[0]);
1005
+ if (records.every((r) => Object.keys(r).length === keys.length && keys.every((k) => k in r)))
1006
+ return Object.fromEntries(keys.map((k) => [k, common(records.map((r) => r[k]))]));
1007
+ }
1008
+ return null;
1009
+ }
1010
+ /**
1011
+ * A view for someone watching, made from every seat's view: whatever all the seats see alike is
1012
+ * kept, and whatever differs between them (a hand, the moves on offer, a card only one player has
1013
+ * peeked at) becomes null, or an empty list. A watcher so learns nothing that every player at the
1014
+ * table doesn't already know, in any game, without the game saying which parts are private.
1015
+ *
1016
+ * Name a game's private parts in `blank` anyway (their values replace the seats' own before
1017
+ * comparing): two hands that happened to match in some detail would otherwise show it. `from`
1018
+ * takes the named keys from one seat's view as they are, for the parts that say where the viewer
1019
+ * sits rather than what they know.
1020
+ */
1021
+ export function sharedView(views, { blank = {}, from } = {}) {
1022
+ if (!views.length)
1023
+ throw new Error("A table has at least one seat.");
1024
+ const placed = from ? views[from.seat] ?? views[0] : null;
1025
+ const comparable = views.map((v) => {
1026
+ const copy = { ...v, ...blank };
1027
+ // Where the viewer sits differs by definition; it's set from one seat below.
1028
+ for (const key of from?.keys ?? [])
1029
+ delete copy[key];
1030
+ return copy;
1031
+ });
1032
+ const shared = common(comparable);
1033
+ for (const key of from?.keys ?? [])
1034
+ shared[key] = placed[key];
1035
+ return shared;
1036
+ }
1037
+ //# sourceMappingURL=server.js.map