c64-ready 1.0.0 → 1.0.1

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 (34) hide show
  1. package/dist/assets/CHANGELOG-B12WeYEc.js +116 -0
  2. package/dist/assets/index-fUdEY2R7.js +610 -0
  3. package/dist/index.html +1 -1
  4. package/dist-ts/emulator/c64-emulator.d.ts +3 -0
  5. package/dist-ts/emulator/c64-emulator.d.ts.map +1 -1
  6. package/dist-ts/emulator/c64-emulator.js +36 -4
  7. package/dist-ts/emulator/c64-emulator.js.map +1 -1
  8. package/dist-ts/emulator/crt-info.d.ts +61 -0
  9. package/dist-ts/emulator/crt-info.d.ts.map +1 -0
  10. package/dist-ts/emulator/crt-info.js +190 -0
  11. package/dist-ts/emulator/crt-info.js.map +1 -0
  12. package/dist-ts/emulator/input.d.ts +96 -0
  13. package/dist-ts/emulator/input.d.ts.map +1 -1
  14. package/dist-ts/emulator/input.js +549 -4
  15. package/dist-ts/emulator/input.js.map +1 -1
  16. package/dist-ts/headless/c64-headless.d.ts +1 -0
  17. package/dist-ts/headless/c64-headless.d.ts.map +1 -1
  18. package/dist-ts/headless/c64-headless.js +5 -0
  19. package/dist-ts/headless/c64-headless.js.map +1 -1
  20. package/dist-ts/types/emulator.d.ts +2 -1
  21. package/dist-ts/types/emulator.d.ts.map +1 -1
  22. package/package.json +1 -1
  23. package/src/emulator/c64-emulator.ts +34 -2
  24. package/src/emulator/crt-info.ts +35 -23
  25. package/src/headless/c64-headless.ts +5 -0
  26. package/src/headless/headless-cli.mjs +406 -229
  27. package/src/headless/input-server.mjs +397 -200
  28. package/src/headless/webrtc-server.mjs +168 -67
  29. package/src/main.ts +18 -4
  30. package/src/player/c64-player.ts +102 -36
  31. package/src/player/styles/ui-controller.css +90 -21
  32. package/src/player/ui-controller.ts +58 -11
  33. package/dist/assets/CHANGELOG-CPlXKLCV.js +0 -279
  34. package/dist/assets/index-Ckbi7gQo.js +0 -535
@@ -17,11 +17,13 @@ import { randomBytes } from 'crypto';
17
17
  * @param {number} [opts.port=9001]
18
18
  * @param {Function} opts.onInput
19
19
  * @param {Function} [opts.onCommand] Called with emulator commands from the host:
20
- * { type: 'load-crt'|'detach-crt'|'hard-reset', ... }
20
+ * { type: 'load-crt'|'detach-crt'|'hard-reset'|'reboot', ... }
21
21
  * @param {boolean} [opts.verbose]
22
22
  * @param {number} [opts.hostTimeoutMs=300000]
23
23
  * @param {Function} [opts.validateKickToken]
24
24
  * @param {Function} [opts.validateAdminToken]
25
+ * @param {number} [opts.hostReconnectGraceMs=8000]
26
+ * @param {number} [opts.p2ReconnectGraceMs=5000]
25
27
  * @param {Function} [opts.getRuntimeStats]
26
28
  * @param {Function} [opts.getWebrtcPeerSnapshot]
27
29
  * @param {Function} [opts.disconnectWebrtcPeersByAddr]
@@ -31,17 +33,17 @@ import { randomBytes } from 'crypto';
31
33
  * @returns {{ wss: WebSocketServer, close: () => Promise<void> }}
32
34
  */
33
35
  export function createInputServer(opts = {}) {
34
- const port = opts.port ?? 9001;
35
- const onInput = opts.onInput;
36
- const onCommand = opts.onCommand ?? (() => {});
37
- const verbose = opts.verbose ?? false;
38
- const logEvents = opts.logEvents ?? false;
39
- const HOST_TIMEOUT = opts.hostTimeoutMs ?? 10 * 60 * 1000;
36
+ const port = opts.port ?? 9001;
37
+ const onInput = opts.onInput;
38
+ const onCommand = opts.onCommand ?? (() => {});
39
+ const verbose = opts.verbose ?? false;
40
+ const logEvents = opts.logEvents ?? false;
41
+ const HOST_TIMEOUT = opts.hostTimeoutMs ?? 10 * 60 * 1000;
40
42
  const validateKickToken = opts.validateKickToken ?? (() => null);
41
43
  const validateAdminToken = opts.validateAdminToken ?? (() => false);
42
- const serverVersion = opts.serverVersion ?? null;
43
- const serverGitHash = opts.serverGitHash ?? null;
44
- const getRuntimeStats = opts.getRuntimeStats ?? (() => null);
44
+ const serverVersion = opts.serverVersion ?? null;
45
+ const serverGitHash = opts.serverGitHash ?? null;
46
+ const getRuntimeStats = opts.getRuntimeStats ?? (() => null);
45
47
  const getWebrtcPeerSnapshot = opts.getWebrtcPeerSnapshot ?? (() => null);
46
48
  const disconnectWebrtcPeersByAddr = opts.disconnectWebrtcPeersByAddr ?? (() => 0);
47
49
  const disconnectAllWebrtcPeers = opts.disconnectAllWebrtcPeers ?? (() => 0);
@@ -49,7 +51,7 @@ export function createInputServer(opts = {}) {
49
51
  // ── Input flood instrumentation ───────────────────────────────────────────────
50
52
  const _inputStats = {
51
53
  host: { joystick: 0, key: 0, lastMsgTime: 0 },
52
- p2: { joystick: 0, key: 0, lastMsgTime: 0 },
54
+ p2: { joystick: 0, key: 0, lastMsgTime: 0 },
53
55
  };
54
56
  // ── Input latency tracking ─────────────────────────────────────────────────
55
57
  const LATENCY_SPIKE_MS = 200;
@@ -60,7 +62,7 @@ export function createInputServer(opts = {}) {
60
62
  let _networkStatsTimer = null;
61
63
  const _networkStats = {
62
64
  host: { avgLatency: null, lastLatency: null, lastSpikeLatency: null, lastSpikeAt: null },
63
- p2: { avgLatency: null, lastLatency: null, lastSpikeLatency: null, lastSpikeAt: null },
65
+ p2: { avgLatency: null, lastLatency: null, lastSpikeLatency: null, lastSpikeAt: null },
64
66
  };
65
67
 
66
68
  function broadcastNetworkStats() {
@@ -70,14 +72,18 @@ export function createInputServer(opts = {}) {
70
72
  type: 'network-stats',
71
73
  serverTime: Date.now(),
72
74
  host: { ..._networkStats.host },
73
- p2: { ..._networkStats.p2 },
75
+ p2: { ..._networkStats.p2 },
74
76
  ...(runtime ? { server: runtime } : {}),
75
77
  });
76
78
  if (hostClient && hostClient.readyState === hostClient.OPEN) {
77
- try { hostClient.send(payload); } catch (_) {}
79
+ try {
80
+ hostClient.send(payload);
81
+ } catch (_) {}
78
82
  }
79
83
  if (p2Client && p2Client.readyState === p2Client.OPEN) {
80
- try { p2Client.send(payload); } catch (_) {}
84
+ try {
85
+ p2Client.send(payload);
86
+ } catch (_) {}
81
87
  }
82
88
  }
83
89
  const INPUT_LOG_INTERVAL_MS = 5000; // every 5 seconds
@@ -87,10 +93,12 @@ export function createInputServer(opts = {}) {
87
93
  _inputLogTimer = setInterval(() => {
88
94
  const now = Date.now();
89
95
  // Only log if there's been recent activity (within last 10s)
90
- const h = _inputStats.host.lastMsgTime && (now - _inputStats.host.lastMsgTime < 10000);
91
- const p = _inputStats.p2.lastMsgTime && (now - _inputStats.p2.lastMsgTime < 10000);
96
+ const h = _inputStats.host.lastMsgTime && now - _inputStats.host.lastMsgTime < 10000;
97
+ const p = _inputStats.p2.lastMsgTime && now - _inputStats.p2.lastMsgTime < 10000;
92
98
  if ((h || p) && (logEvents || verbose)) {
93
- console.error(`[event] input-flood host-joystick=${_inputStats.host.joystick} host-key=${_inputStats.host.key} p2-joystick=${_inputStats.p2.joystick} p2-key=${_inputStats.p2.key}`);
99
+ console.error(
100
+ `[event] input-flood host-joystick=${_inputStats.host.joystick} host-key=${_inputStats.host.key} p2-joystick=${_inputStats.p2.joystick} p2-key=${_inputStats.p2.key}`,
101
+ );
94
102
  }
95
103
  // Reset counters after reporting
96
104
  _inputStats.host.joystick = 0;
@@ -113,7 +121,9 @@ export function createInputServer(opts = {}) {
113
121
  function logEv(tag, fields = {}) {
114
122
  if (!logEvents) return;
115
123
  const ts = new Date().toISOString();
116
- const pairs = Object.entries(fields).map(([k, v]) => `${k}=${v}`).join(' ');
124
+ const pairs = Object.entries(fields)
125
+ .map(([k, v]) => `${k}=${v}`)
126
+ .join(' ');
117
127
  console.error(`[event] ${ts} ${tag}${pairs ? ' ' + pairs : ''}`);
118
128
  }
119
129
 
@@ -122,15 +132,15 @@ export function createInputServer(opts = {}) {
122
132
  const P2_RECONNECT_GRACE = opts.p2ReconnectGraceMs ?? HOST_RECONNECT_GRACE;
123
133
 
124
134
  // ── Room state ────────────────────────────────────────────────────────────
125
- let hostClient = null;
126
- let hostUsername = null;
135
+ let hostClient = null;
136
+ let hostUsername = null;
127
137
 
128
- let p2Client = null;
129
- let p2Username = null;
130
- let inviteToken = null;
138
+ let p2Client = null;
139
+ let p2Username = null;
140
+ let inviteToken = null;
131
141
 
132
142
  // Joystick port swap — when true, host uses port 1, P2 uses port 2
133
- let portsSwapped = false;
143
+ let portsSwapped = false;
134
144
  // Optional host-defined override for independent per-role joystick ports.
135
145
  let portOverrideEnabled = false;
136
146
  let overrideHostPort = 2;
@@ -139,19 +149,19 @@ export function createInputServer(opts = {}) {
139
149
  // ── Host reconnect grace period ───────────────────────────────────────────
140
150
  // When the host disconnects we hold off on promoting P2 for up to
141
151
  // HOST_RECONNECT_GRACE ms, giving the host a chance to refresh and reclaim.
142
- let graceTimer = null;
143
- let pendingHostUsername = null; // username of the disconnected host
144
- let p2GraceTimer = null;
145
- let pendingP2Username = null;
152
+ let graceTimer = null;
153
+ let pendingHostUsername = null; // username of the disconnected host
154
+ let p2GraceTimer = null;
155
+ let pendingP2Username = null;
146
156
  // Currently loaded cartridge filename (for hello message to late joiners).
147
157
  // Seeded from opts.initialCartFilename when a default game is pre-loaded.
148
158
  let currentCartFilename = opts.initialCartFilename ?? null;
149
159
 
150
160
  function hostPort() {
151
- return portOverrideEnabled ? overrideHostPort : (portsSwapped ? 1 : 2);
161
+ return portOverrideEnabled ? overrideHostPort : portsSwapped ? 1 : 2;
152
162
  }
153
163
  function p2Port() {
154
- return portOverrideEnabled ? overrideP2Port : (portsSwapped ? 2 : 1);
164
+ return portOverrideEnabled ? overrideP2Port : portsSwapped ? 2 : 1;
155
165
  }
156
166
 
157
167
  // ── Host inactivity timeout ───────────────────────────────────────────────
@@ -164,7 +174,10 @@ export function createInputServer(opts = {}) {
164
174
  }
165
175
 
166
176
  function clearHostTimeout() {
167
- if (hostTimeoutTimer) { clearTimeout(hostTimeoutTimer); hostTimeoutTimer = null; }
177
+ if (hostTimeoutTimer) {
178
+ clearTimeout(hostTimeoutTimer);
179
+ hostTimeoutTimer = null;
180
+ }
168
181
  }
169
182
 
170
183
  // ── P2 inactivity timeout ─────────────────────────────────────────────────
@@ -177,7 +190,10 @@ export function createInputServer(opts = {}) {
177
190
  }
178
191
 
179
192
  function clearP2Timeout() {
180
- if (p2TimeoutTimer) { clearTimeout(p2TimeoutTimer); p2TimeoutTimer = null; }
193
+ if (p2TimeoutTimer) {
194
+ clearTimeout(p2TimeoutTimer);
195
+ p2TimeoutTimer = null;
196
+ }
181
197
  }
182
198
 
183
199
  function kickP2ForInactivity() {
@@ -189,8 +205,8 @@ export function createInputServer(opts = {}) {
189
205
  }
190
206
  const leaving = p2Username;
191
207
  setWsIdentity(p2Client, 'spectator', null);
192
- p2Client = null;
193
- p2Username = null;
208
+ p2Client = null;
209
+ p2Username = null;
194
210
  clearP2Grace();
195
211
  clearP2Timeout();
196
212
  broadcastAll({ type: 'player2-left', username: leaving, reason: 'timeout' });
@@ -199,19 +215,25 @@ export function createInputServer(opts = {}) {
199
215
 
200
216
  // ── Host reconnect grace period helpers ───────────────────────────────────
201
217
  function clearGrace() {
202
- if (graceTimer) { clearTimeout(graceTimer); graceTimer = null; }
218
+ if (graceTimer) {
219
+ clearTimeout(graceTimer);
220
+ graceTimer = null;
221
+ }
203
222
  pendingHostUsername = null;
204
223
  }
205
224
 
206
225
  function clearP2Grace() {
207
- if (p2GraceTimer) { clearTimeout(p2GraceTimer); p2GraceTimer = null; }
226
+ if (p2GraceTimer) {
227
+ clearTimeout(p2GraceTimer);
228
+ p2GraceTimer = null;
229
+ }
208
230
  pendingP2Username = null;
209
231
  }
210
232
 
211
233
  // Called when grace expires without the host reconnecting.
212
234
  function expireGrace() {
213
- graceTimer = null;
214
- const leaving = pendingHostUsername;
235
+ graceTimer = null;
236
+ const leaving = pendingHostUsername;
215
237
  pendingHostUsername = null;
216
238
  if (verbose) console.error(`[input-server] host grace expired for ${leaving}`);
217
239
  logEv('host-grace-expired', { username: leaving });
@@ -223,7 +245,10 @@ export function createInputServer(opts = {}) {
223
245
  function onHostDisconnect(leaving) {
224
246
  clearGrace();
225
247
  pendingHostUsername = leaving;
226
- if (verbose) console.error(`[input-server] host ${leaving} disconnected — grace ${HOST_RECONNECT_GRACE}ms`);
248
+ if (verbose)
249
+ console.error(
250
+ `[input-server] host ${leaving} disconnected — grace ${HOST_RECONNECT_GRACE}ms`,
251
+ );
227
252
  logEv('host-disconnected', { username: leaving, graceMs: HOST_RECONNECT_GRACE });
228
253
  // Tell everyone the host is temporarily gone; P2 should wait before acting.
229
254
  broadcastAll({ type: 'host-disconnected', username: leaving, graceMs: HOST_RECONNECT_GRACE });
@@ -231,8 +256,8 @@ export function createInputServer(opts = {}) {
231
256
  }
232
257
 
233
258
  function expireP2Grace() {
234
- p2GraceTimer = null;
235
- const leaving = pendingP2Username;
259
+ p2GraceTimer = null;
260
+ const leaving = pendingP2Username;
236
261
  pendingP2Username = null;
237
262
  if (verbose) console.error(`[input-server] p2 grace expired for ${leaving}`);
238
263
  logEv('p2-grace-expired', { username: leaving });
@@ -243,7 +268,10 @@ export function createInputServer(opts = {}) {
243
268
  function onP2Disconnect(leaving) {
244
269
  clearP2Grace();
245
270
  pendingP2Username = leaving;
246
- if (verbose) console.error(`[input-server] player2 ${leaving} disconnected — grace ${P2_RECONNECT_GRACE}ms`);
271
+ if (verbose)
272
+ console.error(
273
+ `[input-server] player2 ${leaving} disconnected — grace ${P2_RECONNECT_GRACE}ms`,
274
+ );
247
275
  logEv('p2-disconnected', { username: leaving, graceMs: P2_RECONNECT_GRACE });
248
276
  p2GraceTimer = setTimeout(expireP2Grace, P2_RECONNECT_GRACE);
249
277
  }
@@ -258,9 +286,9 @@ export function createInputServer(opts = {}) {
258
286
  }
259
287
  const leaving = hostUsername;
260
288
  setWsIdentity(hostClient, 'spectator', null);
261
- hostClient = null;
262
- hostUsername = null;
263
- inviteToken = null;
289
+ hostClient = null;
290
+ hostUsername = null;
291
+ inviteToken = null;
264
292
  portOverrideEnabled = false;
265
293
  overrideHostPort = 2;
266
294
  overrideP2Port = 1;
@@ -280,7 +308,9 @@ export function createInputServer(opts = {}) {
280
308
  clearHostTimeout();
281
309
  clearGrace();
282
310
  if (targetWs.readyState === targetWs.OPEN) {
283
- try { targetWs.send(JSON.stringify({ type: 'host-kicked', reason })); } catch (_) {}
311
+ try {
312
+ targetWs.send(JSON.stringify({ type: 'host-kicked', reason }));
313
+ } catch (_) {}
284
314
  }
285
315
  hostClient = null;
286
316
  hostUsername = null;
@@ -303,7 +333,9 @@ export function createInputServer(opts = {}) {
303
333
  const addr = targetMeta?.addr ?? null;
304
334
  const leaving = p2Username;
305
335
  if (targetWs.readyState === targetWs.OPEN) {
306
- try { targetWs.send(JSON.stringify({ type: 'kicked', reason })); } catch (_) {}
336
+ try {
337
+ targetWs.send(JSON.stringify({ type: 'kicked', reason }));
338
+ } catch (_) {}
307
339
  }
308
340
  clearP2Timeout();
309
341
  clearP2Grace();
@@ -316,7 +348,6 @@ export function createInputServer(opts = {}) {
316
348
  return { kicked: true, username: leaving, addr };
317
349
  }
318
350
 
319
-
320
351
  function broadcastExcept(excludeWs, msg) {
321
352
  const raw = JSON.stringify(msg);
322
353
  wss.clients.forEach((c) => {
@@ -326,14 +357,18 @@ export function createInputServer(opts = {}) {
326
357
 
327
358
  function broadcastAll(msg) {
328
359
  const raw = JSON.stringify(msg);
329
- wss.clients.forEach((c) => { if (c.readyState === c.OPEN) c.send(raw); });
360
+ wss.clients.forEach((c) => {
361
+ if (c.readyState === c.OPEN) c.send(raw);
362
+ });
330
363
  }
331
364
 
332
365
  // True when the P2 slot is available for open joining
333
366
  function isP2SlotOpen() {
334
- return !!(hostClient && hostClient.readyState === hostClient.OPEN)
335
- && !(p2Client && p2Client.readyState === p2Client.OPEN)
336
- && !p2GraceTimer;
367
+ return (
368
+ !!(hostClient && hostClient.readyState === hostClient.OPEN) &&
369
+ !(p2Client && p2Client.readyState === p2Client.OPEN) &&
370
+ !p2GraceTimer
371
+ );
337
372
  }
338
373
 
339
374
  let clientCount = 0;
@@ -392,18 +427,22 @@ export function createInputServer(opts = {}) {
392
427
  const anonymousWebrtcPeers = Math.max(0, webrtcTotal - mappedWebrtcPeers);
393
428
 
394
429
  return {
395
- host: hostClient ? {
396
- connected: hostClient.readyState === hostClient.OPEN,
397
- username: hostUsername,
398
- addr: hostMeta?.addr ?? null,
399
- webrtcPeers: hostMeta?.addr ? (webrtcByAddr.get(hostMeta.addr) ?? 0) : 0,
400
- } : null,
401
- p2: p2Client ? {
402
- connected: p2Client.readyState === p2Client.OPEN,
403
- username: p2Username,
404
- addr: p2Meta?.addr ?? null,
405
- webrtcPeers: p2Meta?.addr ? (webrtcByAddr.get(p2Meta.addr) ?? 0) : 0,
406
- } : null,
430
+ host: hostClient
431
+ ? {
432
+ connected: hostClient.readyState === hostClient.OPEN,
433
+ username: hostUsername,
434
+ addr: hostMeta?.addr ?? null,
435
+ webrtcPeers: hostMeta?.addr ? (webrtcByAddr.get(hostMeta.addr) ?? 0) : 0,
436
+ }
437
+ : null,
438
+ p2: p2Client
439
+ ? {
440
+ connected: p2Client.readyState === p2Client.OPEN,
441
+ username: p2Username,
442
+ addr: p2Meta?.addr ?? null,
443
+ webrtcPeers: p2Meta?.addr ? (webrtcByAddr.get(p2Meta.addr) ?? 0) : 0,
444
+ }
445
+ : null,
407
446
  spectators,
408
447
  counts: {
409
448
  inputClients: clientCount,
@@ -431,7 +470,8 @@ export function createInputServer(opts = {}) {
431
470
  clientCount++;
432
471
  const addr = req.socket.remoteAddress;
433
472
  clientMeta.set(ws, { addr: normalizeAddr(addr), role: 'spectator', username: null });
434
- if (verbose) console.error(`[input-server] client connected from ${addr} (${clientCount} total)`);
473
+ if (verbose)
474
+ console.error(`[input-server] client connected from ${addr} (${clientCount} total)`);
435
475
  logEv('client-connected', { addr, total: clientCount });
436
476
 
437
477
  ws.on('message', (data) => {
@@ -448,7 +488,9 @@ export function createInputServer(opts = {}) {
448
488
  // main thread causes a noticeable pause proportional to file size.
449
489
  if (verbose) {
450
490
  if (msg.type === 'load-crt') {
451
- console.error(`[input-server] rx: load-crt filename=${msg.filename ?? '?'} dataLen=${(msg.data ?? '').length}`);
491
+ console.error(
492
+ `[input-server] rx: load-crt filename=${msg.filename ?? '?'} dataLen=${(msg.data ?? '').length}`,
493
+ );
452
494
  } else {
453
495
  console.error(`[input-server] rx:`, JSON.stringify(msg));
454
496
  }
@@ -462,7 +504,10 @@ export function createInputServer(opts = {}) {
462
504
  // the new browser tab gets host-taken and detach/reset silently fail.
463
505
  if (!msg.force) {
464
506
  ws.send(JSON.stringify({ type: 'host-taken' }));
465
- logEv('host-claim-rejected', { reason: 'slot-taken', username: msg.username ?? 'player' });
507
+ logEv('host-claim-rejected', {
508
+ reason: 'slot-taken',
509
+ username: msg.username ?? 'player',
510
+ });
466
511
  return;
467
512
  }
468
513
  // Forcibly evict the existing host before granting the new claim.
@@ -470,29 +515,49 @@ export function createInputServer(opts = {}) {
470
515
  logEv('host-force-evicted', { evicted: hostUsername, by: msg.username ?? 'player' });
471
516
  clearHostTimeout();
472
517
  clearGrace();
473
- try { hostClient.send(JSON.stringify({ type: 'host-evicted', reason: 'force-claim' })); } catch (_) {}
474
- try { hostClient.close(); } catch (_) {}
518
+ try {
519
+ hostClient.send(JSON.stringify({ type: 'host-evicted', reason: 'force-claim' }));
520
+ } catch (_) {}
521
+ try {
522
+ hostClient.close();
523
+ } catch (_) {}
475
524
  setWsIdentity(hostClient, 'spectator', null);
476
- hostClient = null;
525
+ hostClient = null;
477
526
  hostUsername = null;
478
- inviteToken = null;
527
+ inviteToken = null;
479
528
  }
480
529
  const isRejoin = graceTimer && pendingHostUsername === (msg.username ?? 'player');
481
530
  if (graceTimer) clearGrace(); // cancel grace regardless of who's claiming
482
- hostClient = ws;
531
+ hostClient = ws;
483
532
  hostUsername = msg.username ?? 'player';
484
533
  setWsIdentity(ws, 'host', hostUsername);
485
- ws.send(JSON.stringify({
486
- type: 'host-confirmed', username: hostUsername, joystickPort: hostPort(),
487
- player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
488
- }));
534
+ ws.send(
535
+ JSON.stringify({
536
+ type: 'host-confirmed',
537
+ username: hostUsername,
538
+ joystickPort: hostPort(),
539
+ player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
540
+ }),
541
+ );
489
542
  if (isRejoin) {
490
- broadcastExcept(ws, { type: 'host-rejoined', username: hostUsername, joystickPort: hostPort() });
543
+ broadcastExcept(ws, {
544
+ type: 'host-rejoined',
545
+ username: hostUsername,
546
+ joystickPort: hostPort(),
547
+ });
491
548
  } else {
492
- broadcastExcept(ws, { type: 'host-joined', username: hostUsername, joystickPort: hostPort() });
549
+ broadcastExcept(ws, {
550
+ type: 'host-joined',
551
+ username: hostUsername,
552
+ joystickPort: hostPort(),
553
+ });
493
554
  }
494
- if (verbose) console.error(`[input-server] host ${isRejoin ? 're' : ''}claimed by ${hostUsername}`);
495
- logEv(isRejoin ? 'host-rejoined' : 'host-joined', { username: hostUsername, joystickPort: hostPort() });
555
+ if (verbose)
556
+ console.error(`[input-server] host ${isRejoin ? 're' : ''}claimed by ${hostUsername}`);
557
+ logEv(isRejoin ? 'host-rejoined' : 'host-joined', {
558
+ username: hostUsername,
559
+ joystickPort: hostPort(),
560
+ });
496
561
  resetHostTimeout();
497
562
  // P2 slot just opened (host present, no P2)
498
563
  broadcastExcept(ws, { type: 'p2-slot-status', open: isP2SlotOpen() });
@@ -503,13 +568,14 @@ export function createInputServer(opts = {}) {
503
568
  if (msg.type === 'swap-ports') {
504
569
  if (ws !== hostClient) return;
505
570
  portsSwapped = !portsSwapped;
506
- if (verbose) console.error(`[input-server] ports swapped: host=${hostPort()} p2=${p2Port()}`);
571
+ if (verbose)
572
+ console.error(`[input-server] ports swapped: host=${hostPort()} p2=${p2Port()}`);
507
573
  logEv('ports-swapped', { hostPort: hostPort(), p2Port: p2Port() });
508
574
  broadcastAll({
509
- type: 'ports-swapped',
510
- swapped: portsSwapped,
511
- hostPort: hostPort(),
512
- p2Port: p2Port(),
575
+ type: 'ports-swapped',
576
+ swapped: portsSwapped,
577
+ hostPort: hostPort(),
578
+ p2Port: p2Port(),
513
579
  });
514
580
  return;
515
581
  }
@@ -520,9 +586,18 @@ export function createInputServer(opts = {}) {
520
586
  const enabled = !!msg.enabled;
521
587
  const hp = Number(msg.hostPort);
522
588
  const pp = Number(msg.p2Port);
523
- if (!Number.isFinite(hp) || !Number.isFinite(pp) || (hp !== 1 && hp !== 2) || (pp !== 1 && pp !== 2)) {
589
+ if (
590
+ !Number.isFinite(hp) ||
591
+ !Number.isFinite(pp) ||
592
+ (hp !== 1 && hp !== 2) ||
593
+ (pp !== 1 && pp !== 2)
594
+ ) {
524
595
  if (verbose) console.error('[input-server] invalid set-port-override payload');
525
- logEv('error', { kind: 'set-port-override-invalid', hostPort: msg.hostPort, p2Port: msg.p2Port });
596
+ logEv('error', {
597
+ kind: 'set-port-override-invalid',
598
+ hostPort: msg.hostPort,
599
+ p2Port: msg.p2Port,
600
+ });
526
601
  return;
527
602
  }
528
603
  portOverrideEnabled = enabled;
@@ -549,9 +624,9 @@ export function createInputServer(opts = {}) {
549
624
  if (msg.type === 'p2-leave') {
550
625
  if (ws === p2Client) {
551
626
  clearP2Timeout();
552
- p2Client = null;
553
- const leaving = p2Username;
554
- p2Username = null;
627
+ p2Client = null;
628
+ const leaving = p2Username;
629
+ p2Username = null;
555
630
  setWsIdentity(ws, 'spectator', null);
556
631
  if (verbose) console.error(`[input-server] player2 ${leaving} voluntarily left`);
557
632
  logEv('p2-left', { username: leaving, reason: 'voluntary' });
@@ -567,11 +642,11 @@ export function createInputServer(opts = {}) {
567
642
  if (ws === hostClient) {
568
643
  clearHostTimeout();
569
644
  clearGrace();
570
- hostClient = null;
571
- const leaving = hostUsername;
572
- hostUsername = null;
573
- inviteToken = null;
574
- portsSwapped = false;
645
+ hostClient = null;
646
+ const leaving = hostUsername;
647
+ hostUsername = null;
648
+ inviteToken = null;
649
+ portsSwapped = false;
575
650
  portOverrideEnabled = false;
576
651
  overrideHostPort = 2;
577
652
  overrideP2Port = 1;
@@ -628,18 +703,28 @@ export function createInputServer(opts = {}) {
628
703
  ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'already-host' }));
629
704
  return;
630
705
  }
631
- p2Client = ws;
632
- p2Username = requestedUsername;
706
+ p2Client = ws;
707
+ p2Username = requestedUsername;
633
708
  inviteToken = null;
634
709
  setWsIdentity(ws, 'p2', p2Username);
635
- ws.send(JSON.stringify({
636
- type: 'join-p2-confirmed', username: p2Username, joystickPort: p2Port(),
637
- }));
638
- broadcastExcept(ws, { type: 'player2-joined', username: p2Username, joystickPort: p2Port() });
710
+ ws.send(
711
+ JSON.stringify({
712
+ type: 'join-p2-confirmed',
713
+ username: p2Username,
714
+ joystickPort: p2Port(),
715
+ }),
716
+ );
717
+ broadcastExcept(ws, {
718
+ type: 'player2-joined',
719
+ username: p2Username,
720
+ joystickPort: p2Port(),
721
+ });
639
722
  // Notify all clients that the slot is now taken
640
723
  broadcastAll({ type: 'p2-slot-status', open: false });
641
724
  if (verbose) {
642
- console.error(`[input-server] player2 ${isRejoin ? 're' : ''}joined (open): ${p2Username}`);
725
+ console.error(
726
+ `[input-server] player2 ${isRejoin ? 're' : ''}joined (open): ${p2Username}`,
727
+ );
643
728
  }
644
729
  logEv(isRejoin ? 'p2-rejoined' : 'p2-joined', {
645
730
  username: p2Username,
@@ -654,7 +739,10 @@ export function createInputServer(opts = {}) {
654
739
  if (msg.type === 'join-p2') {
655
740
  if (!inviteToken || msg.token !== inviteToken) {
656
741
  ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'invalid-token' }));
657
- logEv('p2-join-rejected', { reason: 'invalid-token', username: msg.username ?? 'player2' });
742
+ logEv('p2-join-rejected', {
743
+ reason: 'invalid-token',
744
+ username: msg.username ?? 'player2',
745
+ });
658
746
  return;
659
747
  }
660
748
  if (p2Client && p2Client.readyState === p2Client.OPEN) {
@@ -673,17 +761,27 @@ export function createInputServer(opts = {}) {
673
761
  return;
674
762
  }
675
763
  if (isRejoin) clearP2Grace();
676
- p2Client = ws;
677
- p2Username = requestedUsername;
764
+ p2Client = ws;
765
+ p2Username = requestedUsername;
678
766
  inviteToken = null;
679
767
  setWsIdentity(ws, 'p2', p2Username);
680
- ws.send(JSON.stringify({
681
- type: 'join-p2-confirmed', username: p2Username, joystickPort: p2Port(),
682
- }));
683
- broadcastExcept(ws, { type: 'player2-joined', username: p2Username, joystickPort: p2Port() });
768
+ ws.send(
769
+ JSON.stringify({
770
+ type: 'join-p2-confirmed',
771
+ username: p2Username,
772
+ joystickPort: p2Port(),
773
+ }),
774
+ );
775
+ broadcastExcept(ws, {
776
+ type: 'player2-joined',
777
+ username: p2Username,
778
+ joystickPort: p2Port(),
779
+ });
684
780
  broadcastAll({ type: 'p2-slot-status', open: false });
685
781
  if (verbose) {
686
- console.error(`[input-server] player2 ${isRejoin ? 're' : ''}joined (token): ${p2Username}`);
782
+ console.error(
783
+ `[input-server] player2 ${isRejoin ? 're' : ''}joined (token): ${p2Username}`,
784
+ );
687
785
  }
688
786
  logEv(isRejoin ? 'p2-rejoined' : 'p2-joined', {
689
787
  username: p2Username,
@@ -705,11 +803,15 @@ export function createInputServer(opts = {}) {
705
803
  const pendingLeaving = pendingP2Username;
706
804
  clearP2Timeout();
707
805
  clearP2Grace();
708
- p2Client = null;
709
- p2Username = null;
806
+ p2Client = null;
807
+ p2Username = null;
710
808
  setWsIdentity(ws, 'spectator', null);
711
809
  if (leaving || pendingLeaving) {
712
- broadcastAll({ type: 'player2-left', username: leaving ?? pendingLeaving, reason: 'revoked' });
810
+ broadcastAll({
811
+ type: 'player2-left',
812
+ username: leaving ?? pendingLeaving,
813
+ reason: 'revoked',
814
+ });
713
815
  }
714
816
  broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
715
817
  if (verbose) console.error(`[input-server] p2 revoked by host`);
@@ -721,51 +823,80 @@ export function createInputServer(opts = {}) {
721
823
  if (msg.type === 'admin-status') {
722
824
  const valid = validateAdminToken(msg.token ?? '');
723
825
  if (!valid) {
724
- ws.send(JSON.stringify({ type: 'admin-error', command: 'status', reason: 'invalid-token' }));
826
+ ws.send(
827
+ JSON.stringify({ type: 'admin-error', command: 'status', reason: 'invalid-token' }),
828
+ );
725
829
  return;
726
830
  }
727
831
  setWsIdentity(ws, 'admin', null);
728
- ws.send(JSON.stringify({
729
- type: 'admin-status-ok',
730
- status: buildAdminStatus(),
731
- }));
832
+ ws.send(
833
+ JSON.stringify({
834
+ type: 'admin-status-ok',
835
+ status: buildAdminStatus(),
836
+ }),
837
+ );
732
838
  return;
733
839
  }
734
840
 
735
841
  if (msg.type === 'admin-kick-player') {
736
842
  const valid = validateAdminToken(msg.token ?? '');
737
843
  if (!valid) {
738
- ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-player', reason: 'invalid-token' }));
844
+ ws.send(
845
+ JSON.stringify({
846
+ type: 'admin-error',
847
+ command: 'kick-player',
848
+ reason: 'invalid-token',
849
+ }),
850
+ );
739
851
  return;
740
852
  }
741
853
  setWsIdentity(ws, 'admin', null);
742
- const target = msg.target === 'p2' ? 'p2' : (msg.target === 'host' ? 'host' : null);
854
+ const target = msg.target === 'p2' ? 'p2' : msg.target === 'host' ? 'host' : null;
743
855
  if (!target) {
744
- ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-player', reason: 'invalid-target' }));
856
+ ws.send(
857
+ JSON.stringify({
858
+ type: 'admin-error',
859
+ command: 'kick-player',
860
+ reason: 'invalid-target',
861
+ }),
862
+ );
745
863
  return;
746
864
  }
747
- const result = target === 'host'
748
- ? kickHostByReason('admin-kick')
749
- : kickP2ByReason('admin-kick');
865
+ const result =
866
+ target === 'host' ? kickHostByReason('admin-kick') : kickP2ByReason('admin-kick');
750
867
  if (!result.kicked) {
751
- ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-player', reason: 'target-not-present', target }));
868
+ ws.send(
869
+ JSON.stringify({
870
+ type: 'admin-error',
871
+ command: 'kick-player',
872
+ reason: 'target-not-present',
873
+ target,
874
+ }),
875
+ );
752
876
  return;
753
877
  }
754
- logEv(target === 'host' ? 'host-kicked' : 'p2-kicked', { username: result.username ?? '-', by: 'admin-cli' });
755
- ws.send(JSON.stringify({
756
- type: 'admin-kick-player-ok',
757
- target,
758
- username: result.username,
759
- addr: result.addr,
760
- status: buildAdminStatus(),
761
- }));
878
+ logEv(target === 'host' ? 'host-kicked' : 'p2-kicked', {
879
+ username: result.username ?? '-',
880
+ by: 'admin-cli',
881
+ });
882
+ ws.send(
883
+ JSON.stringify({
884
+ type: 'admin-kick-player-ok',
885
+ target,
886
+ username: result.username,
887
+ addr: result.addr,
888
+ status: buildAdminStatus(),
889
+ }),
890
+ );
762
891
  return;
763
892
  }
764
893
 
765
894
  if (msg.type === 'admin-kick-all') {
766
895
  const valid = validateAdminToken(msg.token ?? '');
767
896
  if (!valid) {
768
- ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-all', reason: 'invalid-token' }));
897
+ ws.send(
898
+ JSON.stringify({ type: 'admin-error', command: 'kick-all', reason: 'invalid-token' }),
899
+ );
769
900
  return;
770
901
  }
771
902
  setWsIdentity(ws, 'admin', null);
@@ -783,18 +914,21 @@ export function createInputServer(opts = {}) {
783
914
  const meta = clientMeta.get(c);
784
915
  if (meta?.role === 'admin') continue;
785
916
  try {
786
- if (c.readyState === c.OPEN) c.send(JSON.stringify({ type: 'kicked', reason: 'admin-kick-all' }));
917
+ if (c.readyState === c.OPEN)
918
+ c.send(JSON.stringify({ type: 'kicked', reason: 'admin-kick-all' }));
787
919
  c.close();
788
920
  kicked.spectators++;
789
921
  } catch (_) {}
790
922
  }
791
923
  kicked.webrtcPeers = disconnectAllWebrtcPeers('admin-kick-all');
792
924
  logEv('admin-kick-all', { spectators: kicked.spectators, webrtcPeers: kicked.webrtcPeers });
793
- ws.send(JSON.stringify({
794
- type: 'admin-kick-all-ok',
795
- kicked,
796
- status: buildAdminStatus(),
797
- }));
925
+ ws.send(
926
+ JSON.stringify({
927
+ type: 'admin-kick-all-ok',
928
+ kicked,
929
+ status: buildAdminStatus(),
930
+ }),
931
+ );
798
932
  return;
799
933
  }
800
934
 
@@ -828,7 +962,8 @@ export function createInputServer(opts = {}) {
828
962
  if (ws !== hostClient) return;
829
963
  const loadFilename = msg.filename ?? '';
830
964
  const fileType = msg.fileType ?? 'crt';
831
- if (verbose) console.error(`[input-server] load-file: ${loadFilename || '?'} (${fileType})`);
965
+ if (verbose)
966
+ console.error(`[input-server] load-file: ${loadFilename || '?'} (${fileType})`);
832
967
  logEv('cmd-load-file', {
833
968
  filename: loadFilename || '?',
834
969
  fileType,
@@ -836,7 +971,14 @@ export function createInputServer(opts = {}) {
836
971
  });
837
972
  broadcastAll({ type: 'cart-loading', filename: loadFilename });
838
973
  Promise.resolve()
839
- .then(() => onCommand({ type: 'load-file', filename: loadFilename, fileType, data: msg.data ?? '' }))
974
+ .then(() =>
975
+ onCommand({
976
+ type: 'load-file',
977
+ filename: loadFilename,
978
+ fileType,
979
+ data: msg.data ?? '',
980
+ }),
981
+ )
840
982
  .then(() => {
841
983
  currentCartFilename = loadFilename || null;
842
984
  broadcastAll({ type: 'cart-loaded', filename: loadFilename });
@@ -861,7 +1003,14 @@ export function createInputServer(opts = {}) {
861
1003
  const loadFilename = msg.filename ?? '';
862
1004
  broadcastAll({ type: 'cart-loading', filename: loadFilename });
863
1005
  Promise.resolve()
864
- .then(() => onCommand({ type: 'load-file', filename: loadFilename, fileType: 'crt', data: msg.data ?? '' }))
1006
+ .then(() =>
1007
+ onCommand({
1008
+ type: 'load-file',
1009
+ filename: loadFilename,
1010
+ fileType: 'crt',
1011
+ data: msg.data ?? '',
1012
+ }),
1013
+ )
865
1014
  .then(() => {
866
1015
  currentCartFilename = loadFilename || null;
867
1016
  broadcastAll({ type: 'cart-loaded', filename: loadFilename });
@@ -869,7 +1018,11 @@ export function createInputServer(opts = {}) {
869
1018
  .catch((e) => {
870
1019
  broadcastAll({ type: 'cart-load-error', reason: String(e?.message ?? e) });
871
1020
  if (verbose) console.error('[input-server] load-crt error:', e);
872
- logEv('error', { kind: 'load-crt-failed', filename: loadFilename, err: String(e?.message ?? e) });
1021
+ logEv('error', {
1022
+ kind: 'load-crt-failed',
1023
+ filename: loadFilename,
1024
+ err: String(e?.message ?? e),
1025
+ });
873
1026
  });
874
1027
  return;
875
1028
  }
@@ -907,11 +1060,28 @@ export function createInputServer(opts = {}) {
907
1060
  return;
908
1061
  }
909
1062
 
1063
+ if (msg.type === 'reboot') {
1064
+ if (ws !== hostClient) return;
1065
+ if (verbose) console.error('[input-server] reboot');
1066
+ logEv('cmd-reboot', { host: hostUsername });
1067
+ Promise.resolve()
1068
+ .then(() => onCommand({ type: 'reboot' }))
1069
+ .then(() => {
1070
+ currentCartFilename = null;
1071
+ broadcastAll({ type: 'machine-rebooted' });
1072
+ })
1073
+ .catch((e) => {
1074
+ if (verbose) console.error('[input-server] reboot error:', e);
1075
+ logEv('error', { kind: 'reboot-failed', err: String(e?.message ?? e) });
1076
+ });
1077
+ return;
1078
+ }
1079
+
910
1080
  // ── Input events ─────────────────────────────────────────────────────
911
1081
  if (msg.type === 'joystick' || msg.type === 'key') {
912
1082
  if (ws !== hostClient && ws !== p2Client) return;
913
1083
  if (ws === hostClient) resetHostTimeout();
914
- if (ws === p2Client) resetP2Timeout();
1084
+ if (ws === p2Client) resetP2Timeout();
915
1085
  // Track input counts for flood investigation
916
1086
  const role = ws === hostClient ? 'host' : 'p2';
917
1087
  const stats = role === 'host' ? _inputStats.host : _inputStats.p2;
@@ -931,37 +1101,44 @@ export function createInputServer(opts = {}) {
931
1101
  if (!_latencyLogTimer) {
932
1102
  _latencyLogTimer = setInterval(() => {
933
1103
  const hostActive = _latencyCount.host > 0;
934
- const p2Active = _latencyCount.p2 > 0;
1104
+ const p2Active = _latencyCount.p2 > 0;
935
1105
  if (hostActive || p2Active) {
936
1106
  const hostAvg = hostActive ? Number(_avgLatency.host.toFixed(0)) : null;
937
- const p2Avg = p2Active ? Number(_avgLatency.p2.toFixed(0)) : null;
1107
+ const p2Avg = p2Active ? Number(_avgLatency.p2.toFixed(0)) : null;
938
1108
  const hostLabel = hostAvg != null ? `${hostAvg}` : '--';
939
- const p2Label = p2Avg != null ? `${p2Avg}` : '--';
1109
+ const p2Label = p2Avg != null ? `${p2Avg}` : '--';
940
1110
  if (logEvents || verbose) {
941
- console.error(`[event] input-latency host-avg=${hostLabel}ms p2-avg=${p2Label}ms`);
1111
+ console.error(
1112
+ `[event] input-latency host-avg=${hostLabel}ms p2-avg=${p2Label}ms`,
1113
+ );
942
1114
  }
943
1115
  _networkStats.host.avgLatency = hostAvg;
944
- _networkStats.p2.avgLatency = p2Avg;
1116
+ _networkStats.p2.avgLatency = p2Avg;
945
1117
  broadcastNetworkStats();
946
1118
  }
947
1119
  // Reset averages
948
- _avgLatency.host = 0; _avgLatency.p2 = 0;
949
- _latencyCount.host = 0; _latencyCount.p2 = 0;
1120
+ _avgLatency.host = 0;
1121
+ _avgLatency.p2 = 0;
1122
+ _latencyCount.host = 0;
1123
+ _latencyCount.p2 = 0;
950
1124
  }, 5000);
951
1125
  }
952
1126
  // Accumulate for averaging
953
1127
  _latencyCount[role]++;
954
- _avgLatency[role] = ((_avgLatency[role] * (_latencyCount[role] - 1)) + latency) / _latencyCount[role];
1128
+ _avgLatency[role] =
1129
+ (_avgLatency[role] * (_latencyCount[role] - 1) + latency) / _latencyCount[role];
955
1130
  if (latency > LATENCY_SPIKE_MS) {
956
1131
  if (bucket) {
957
1132
  bucket.lastSpikeLatency = latency;
958
1133
  bucket.lastSpikeAt = now;
959
1134
  }
960
1135
  if (logEvents || verbose) {
961
- console.error(`[event] input-latency-spike role=${role} latency=${latency}ms type=${msg.type} action=${msg.action ?? '-'} ` +
962
- `dir=${msg.direction ?? '-'} fire=${msg.fire ? 1 : 0}`);
963
- }
1136
+ console.error(
1137
+ `[event] input-latency-spike role=${role} latency=${latency}ms type=${msg.type} action=${msg.action ?? '-'} ` +
1138
+ `dir=${msg.direction ?? '-'} fire=${msg.fire ? 1 : 0}`,
1139
+ );
964
1140
  }
1141
+ }
965
1142
  }
966
1143
 
967
1144
  // Tag with role so onInput can include it in logEvents output
@@ -980,7 +1157,7 @@ export function createInputServer(opts = {}) {
980
1157
  }
981
1158
 
982
1159
  if (msg.type === 'ping') {
983
- const role = ws === hostClient ? 'host' : (ws === p2Client ? 'p2' : 'spectator');
1160
+ const role = ws === hostClient ? 'host' : ws === p2Client ? 'p2' : 'spectator';
984
1161
  const now = Date.now();
985
1162
  const payload = {
986
1163
  type: 'pong',
@@ -988,7 +1165,9 @@ export function createInputServer(opts = {}) {
988
1165
  serverTime: now,
989
1166
  clientTime: msg.clientTime ?? null,
990
1167
  };
991
- try { ws.send(JSON.stringify(payload)); } catch (_) {}
1168
+ try {
1169
+ ws.send(JSON.stringify(payload));
1170
+ } catch (_) {}
992
1171
  if (verbose) console.error(`[ping] role=${role} pong pingId=${msg.pingId ?? '-'} `);
993
1172
  return;
994
1173
  }
@@ -1001,11 +1180,11 @@ export function createInputServer(opts = {}) {
1001
1180
 
1002
1181
  if (ws === hostClient) {
1003
1182
  clearHostTimeout();
1004
- hostClient = null;
1183
+ hostClient = null;
1005
1184
  const leaving = hostUsername;
1006
- hostUsername = null;
1007
- inviteToken = null;
1008
- portsSwapped = false;
1185
+ hostUsername = null;
1186
+ inviteToken = null;
1187
+ portsSwapped = false;
1009
1188
  portOverrideEnabled = false;
1010
1189
  overrideHostPort = 2;
1011
1190
  overrideP2Port = 1;
@@ -1014,9 +1193,9 @@ export function createInputServer(opts = {}) {
1014
1193
 
1015
1194
  if (ws === p2Client) {
1016
1195
  clearP2Timeout();
1017
- p2Client = null;
1196
+ p2Client = null;
1018
1197
  const leaving = p2Username;
1019
- p2Username = null;
1198
+ p2Username = null;
1020
1199
  onP2Disconnect(leaving);
1021
1200
  }
1022
1201
  clientMeta.delete(ws);
@@ -1030,31 +1209,39 @@ export function createInputServer(opts = {}) {
1030
1209
  // ── Hello handshake ───────────────────────────────────────────────────
1031
1210
  const hostActive = !!(hostClient && hostClient.readyState === hostClient.OPEN);
1032
1211
  const serverTime = Date.now();
1033
- ws.send(JSON.stringify({
1034
- type: 'hello',
1035
- protocol: 'c64-input',
1036
- version: 1,
1037
- serverTime, // Unix ms for client clock sync
1038
- // During grace period: treat slot as free so the original host can reclaim it.
1039
- // hostPendingRejoin tells P2 (and spectators) to hold off.
1040
- hostTaken: hostActive,
1041
- hostPendingRejoin: !hostActive && !!graceTimer ? { username: pendingHostUsername, graceMs: HOST_RECONNECT_GRACE } : null,
1042
- host: hostActive ? { username: hostUsername, joystickPort: hostPort() } : null,
1043
- p2PendingRejoin: !p2Client && !!p2GraceTimer ? { username: pendingP2Username, graceMs: P2_RECONNECT_GRACE } : null,
1044
- player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
1045
- p2SlotOpen: isP2SlotOpen(),
1046
- portOverride: {
1047
- enabled: portOverrideEnabled,
1048
- hostPort: overrideHostPort,
1049
- p2Port: overrideP2Port,
1050
- effectiveHostPort: hostPort(),
1051
- effectiveP2Port: p2Port(),
1052
- },
1053
- ...(currentCartFilename ? { cartFilename: currentCartFilename } : {}),
1054
- joystickBitmask: { up: 0x1, down: 0x2, left: 0x4, right: 0x8, fire: 0x10 },
1055
- ...(serverVersion ? { serverVersion } : {}),
1056
- ...(serverGitHash ? { serverGitHash } : {}),
1057
- }));
1212
+ ws.send(
1213
+ JSON.stringify({
1214
+ type: 'hello',
1215
+ protocol: 'c64-input',
1216
+ version: 1,
1217
+ serverTime, // Unix ms for client clock sync
1218
+ // During grace period: treat slot as free so the original host can reclaim it.
1219
+ // hostPendingRejoin tells P2 (and spectators) to hold off.
1220
+ hostTaken: hostActive,
1221
+ hostPendingRejoin:
1222
+ !hostActive && !!graceTimer
1223
+ ? { username: pendingHostUsername, graceMs: HOST_RECONNECT_GRACE }
1224
+ : null,
1225
+ host: hostActive ? { username: hostUsername, joystickPort: hostPort() } : null,
1226
+ p2PendingRejoin:
1227
+ !p2Client && !!p2GraceTimer
1228
+ ? { username: pendingP2Username, graceMs: P2_RECONNECT_GRACE }
1229
+ : null,
1230
+ player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
1231
+ p2SlotOpen: isP2SlotOpen(),
1232
+ portOverride: {
1233
+ enabled: portOverrideEnabled,
1234
+ hostPort: overrideHostPort,
1235
+ p2Port: overrideP2Port,
1236
+ effectiveHostPort: hostPort(),
1237
+ effectiveP2Port: p2Port(),
1238
+ },
1239
+ ...(currentCartFilename ? { cartFilename: currentCartFilename } : {}),
1240
+ joystickBitmask: { up: 0x1, down: 0x2, left: 0x4, right: 0x8, fire: 0x10 },
1241
+ ...(serverVersion ? { serverVersion } : {}),
1242
+ ...(serverGitHash ? { serverGitHash } : {}),
1243
+ }),
1244
+ );
1058
1245
  });
1059
1246
 
1060
1247
  wss.on('error', (err) => {
@@ -1062,16 +1249,26 @@ export function createInputServer(opts = {}) {
1062
1249
  logEv('error', { kind: 'server-error', err: err.message });
1063
1250
  });
1064
1251
 
1065
- const close = () => new Promise((resolve) => {
1066
- clearHostTimeout();
1067
- clearP2Timeout();
1068
- clearGrace();
1069
- clearP2Grace();
1070
- if (_inputLogTimer) { clearInterval(_inputLogTimer); _inputLogTimer = null; }
1071
- if (_latencyLogTimer) { clearInterval(_latencyLogTimer); _latencyLogTimer = null; }
1072
- if (_networkStatsTimer) { clearInterval(_networkStatsTimer); _networkStatsTimer = null; }
1073
- wss.close(() => resolve());
1074
- });
1252
+ const close = () =>
1253
+ new Promise((resolve) => {
1254
+ clearHostTimeout();
1255
+ clearP2Timeout();
1256
+ clearGrace();
1257
+ clearP2Grace();
1258
+ if (_inputLogTimer) {
1259
+ clearInterval(_inputLogTimer);
1260
+ _inputLogTimer = null;
1261
+ }
1262
+ if (_latencyLogTimer) {
1263
+ clearInterval(_latencyLogTimer);
1264
+ _latencyLogTimer = null;
1265
+ }
1266
+ if (_networkStatsTimer) {
1267
+ clearInterval(_networkStatsTimer);
1268
+ _networkStatsTimer = null;
1269
+ }
1270
+ wss.close(() => resolve());
1271
+ });
1075
1272
 
1076
1273
  return { wss, close };
1077
1274
  }