c64-ready 2.5.0 → 3.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.
Files changed (105) hide show
  1. package/README.md +52 -1
  2. package/bin/admin.mjs +7 -1
  3. package/bin/agent.mjs +18 -0
  4. package/bin/headless.mjs +1 -1
  5. package/dist/assets/BeachHead-CuSwFD4k.js +1 -0
  6. package/dist/assets/ChuckieEgg-CPqBnAOF.js +1 -0
  7. package/dist/assets/ForbiddenForest-DsQ9jsc8.js +1 -0
  8. package/dist/assets/Galaga-Cutc3p9s.js +1 -0
  9. package/dist/assets/Gribbly-DdZ_hHFt.js +1 -0
  10. package/dist/assets/Hercules-vZYKm7GG.js +1 -0
  11. package/dist/assets/LegendOfWilf-CxSMOjsj.js +1 -0
  12. package/dist/assets/MariosCementFactory-z0IZ0q30.js +1 -0
  13. package/dist/assets/MoleAttack-buC6ChYy.js +1 -0
  14. package/dist/assets/MunchyWorm-D2Zv7i0Q.js +1 -0
  15. package/dist/assets/ParkPatrol-CVj7hyoB.js +1 -0
  16. package/dist/assets/PottyPigeon-0SYpIUBa.js +1 -0
  17. package/dist/assets/RainbowIslands-BjfmJB8z.js +1 -0
  18. package/dist/assets/Stix-BU-qUCeC.js +1 -0
  19. package/dist/assets/Tilt-C5KtKisF.js +1 -0
  20. package/dist/assets/UpNDown-CATRO7Mz.js +1 -0
  21. package/dist/assets/Uridium-DanS2KoH.js +1 -0
  22. package/dist/assets/VegetablesDeluxe-C41ViimS.js +1 -0
  23. package/dist/assets/index-B8DSjPqI.js +243 -0
  24. package/dist/assets/src-DX0rJQsE.js +1 -0
  25. package/dist/assets/src-_trgwTvp.js +2 -0
  26. package/dist/assets/string-utils-CMVABfx0.js +1 -0
  27. package/dist/index.html +1 -1
  28. package/dist-ts/emulator/c64-emulator.d.ts +2 -2
  29. package/dist-ts/emulator/c64-emulator.js +2 -2
  30. package/dist-ts/emulator/c64-keys.d.ts +69 -0
  31. package/dist-ts/emulator/c64-keys.d.ts.map +1 -0
  32. package/dist-ts/emulator/c64-keys.js +69 -0
  33. package/dist-ts/emulator/c64-keys.js.map +1 -0
  34. package/dist-ts/emulator/c64-wasm.d.ts +1 -1
  35. package/dist-ts/emulator/gamepad-mapping.d.ts +64 -0
  36. package/dist-ts/emulator/gamepad-mapping.d.ts.map +1 -0
  37. package/dist-ts/emulator/gamepad-mapping.js +154 -0
  38. package/dist-ts/emulator/gamepad-mapping.js.map +1 -0
  39. package/dist-ts/emulator/input.d.ts +27 -78
  40. package/dist-ts/emulator/input.d.ts.map +1 -1
  41. package/dist-ts/emulator/input.js +94 -215
  42. package/dist-ts/emulator/input.js.map +1 -1
  43. package/dist-ts/headless/audio-capture.d.ts +1 -1
  44. package/dist-ts/headless/c64-headless.d.ts +2 -2
  45. package/dist-ts/headless/c64-headless.js +4 -4
  46. package/dist-ts/headless/frame-capture.d.ts +1 -1
  47. package/dist-ts/headless/input-bridge.d.ts +1 -1
  48. package/dist-ts/player/c64-player.d.ts +21 -5
  49. package/dist-ts/player/c64-player.d.ts.map +1 -1
  50. package/dist-ts/player/c64-player.js +32 -5
  51. package/dist-ts/player/c64-player.js.map +1 -1
  52. package/dist-ts/player/canvas-renderer.d.ts +2 -2
  53. package/dist-ts/player/cheevos-dev.d.ts +65 -0
  54. package/dist-ts/player/cheevos-dev.d.ts.map +1 -0
  55. package/dist-ts/player/cheevos-dev.js +237 -0
  56. package/dist-ts/player/cheevos-dev.js.map +1 -0
  57. package/dist-ts/player/cheevos-tracker-panel.d.ts +21 -0
  58. package/dist-ts/player/cheevos-tracker-panel.d.ts.map +1 -0
  59. package/dist-ts/player/cheevos-tracker-panel.js +242 -0
  60. package/dist-ts/player/cheevos-tracker-panel.js.map +1 -0
  61. package/dist-ts/player/index.d.ts +10 -7
  62. package/dist-ts/player/index.d.ts.map +1 -1
  63. package/dist-ts/player/index.js +6 -4
  64. package/dist-ts/player/index.js.map +1 -1
  65. package/dist-ts/player/input-handler.d.ts +7 -3
  66. package/dist-ts/player/input-handler.d.ts.map +1 -1
  67. package/dist-ts/player/input-handler.js +24 -1
  68. package/dist-ts/player/input-handler.js.map +1 -1
  69. package/dist-ts/player/load-formats.d.ts +1 -1
  70. package/dist-ts/player/local-rom-store.d.ts +23 -0
  71. package/dist-ts/player/local-rom-store.d.ts.map +1 -0
  72. package/dist-ts/player/local-rom-store.js +87 -0
  73. package/dist-ts/player/local-rom-store.js.map +1 -0
  74. package/dist-ts/player/startup-params.d.ts +7 -0
  75. package/dist-ts/player/startup-params.d.ts.map +1 -0
  76. package/dist-ts/player/startup-params.js +47 -0
  77. package/dist-ts/player/startup-params.js.map +1 -0
  78. package/dist-ts/player/ui-controller.d.ts +23 -1
  79. package/dist-ts/player/ui-controller.d.ts.map +1 -1
  80. package/dist-ts/player/ui-controller.js +665 -1
  81. package/dist-ts/player/ui-controller.js.map +1 -1
  82. package/package.json +11 -4
  83. package/src/emulator/c64-keys.ts +68 -0
  84. package/src/emulator/gamepad-mapping.ts +212 -0
  85. package/src/emulator/input.ts +106 -209
  86. package/src/headless/agent-cli.mjs +825 -0
  87. package/src/headless/headless-cli.mjs +10 -4
  88. package/src/headless/input-server.mjs +92 -17
  89. package/src/headless/png.mjs +72 -0
  90. package/src/headless/webrtc-server.mjs +458 -34
  91. package/src/main.ts +197 -12
  92. package/src/player/c64-player.ts +58 -1
  93. package/src/player/cheevos-dev.ts +340 -0
  94. package/src/player/cheevos-tracker-panel.ts +309 -0
  95. package/src/player/index.ts +19 -0
  96. package/src/player/input-handler.ts +32 -0
  97. package/src/player/local-rom-store.ts +126 -0
  98. package/src/player/startup-params.ts +40 -0
  99. package/src/player/ui-controller.ts +751 -0
  100. package/src/player/ultimate-bridge.ts +161 -0
  101. package/src/player/ultimate-panel.ts +315 -0
  102. package/src/types/c64-cheevos.d.ts +6 -0
  103. package/dist/assets/index-BAsZcXuS.js +0 -178
  104. /package/dist/assets/{marked.esm--kBm026b.js → marked.esm-fTuuvbcB.js} +0 -0
  105. /package/dist/assets/{purify.es-BcoGFDcJ.js → purify.es-CRM-GE0Y.js} +0 -0
@@ -3,6 +3,7 @@ import { readFileSync, mkdirSync, createWriteStream, readdirSync, statSync, unli
3
3
  import path from 'path';
4
4
  import { fileURLToPath } from 'url';
5
5
  import { execSync } from 'child_process';
6
+ import { timingSafeEqual } from 'crypto';
6
7
  import FFmpegRunner from './ffmpeg-runner.mjs';
7
8
  import { domKeyToC64Actions } from './c64-key-map.mjs';
8
9
 
@@ -382,6 +383,12 @@ export async function runHeadless(options = {}) {
382
383
  }
383
384
  if (!Number.isFinite(hostTimeoutMs) || hostTimeoutMs <= 0) hostTimeoutMs = undefined;
384
385
  const adminTokenSafe = String(adminToken ?? '').trim();
386
+ const validateAdminToken = (token) => {
387
+ if (!adminTokenSafe) return false;
388
+ const expected = Buffer.from(adminTokenSafe);
389
+ const received = Buffer.from(String(token ?? ''));
390
+ return received.length === expected.length && timingSafeEqual(received, expected);
391
+ };
385
392
 
386
393
  const webrtcMinBitrateKbpsSafe =
387
394
  Number.isFinite(webrtcMinBitrateKbps) && webrtcMinBitrateKbps > 0
@@ -765,10 +772,9 @@ export async function runHeadless(options = {}) {
765
772
  logEvents,
766
773
  hostTimeoutMs,
767
774
  validateKickToken,
768
- validateAdminToken: (token) => {
769
- if (!adminTokenSafe) return false;
770
- return token === adminTokenSafe;
771
- },
775
+ hostAuthRequired: true,
776
+ validateHostToken: validateAdminToken,
777
+ validateAdminToken,
772
778
  initialCartFilename: gamePath ? path.basename(gamePath) : null,
773
779
  serverVersion: _serverVersion,
774
780
  serverGitHash: _serverGitHash,
@@ -22,6 +22,8 @@ import { randomBytes } from 'crypto';
22
22
  * @param {number} [opts.hostTimeoutMs=300000]
23
23
  * @param {Function} [opts.validateKickToken]
24
24
  * @param {Function} [opts.validateAdminToken]
25
+ * @param {boolean} [opts.hostAuthRequired=false]
26
+ * @param {Function} [opts.validateHostToken]
25
27
  * @param {number} [opts.hostReconnectGraceMs=8000]
26
28
  * @param {number} [opts.p2ReconnectGraceMs=5000]
27
29
  * @param {Function} [opts.getRuntimeStats]
@@ -47,6 +49,8 @@ export function createInputServer(opts = {}) {
47
49
  const HOST_TIMEOUT = opts.hostTimeoutMs ?? 10 * 60 * 1000;
48
50
  const validateKickToken = opts.validateKickToken ?? (() => null);
49
51
  const validateAdminToken = opts.validateAdminToken ?? (() => false);
52
+ const hostAuthRequired = opts.hostAuthRequired ?? false;
53
+ const validateHostToken = opts.validateHostToken ?? (() => false);
50
54
  const serverVersion = opts.serverVersion ?? null;
51
55
  const serverGitHash = opts.serverGitHash ?? null;
52
56
  const getRuntimeStats = opts.getRuntimeStats ?? (() => null);
@@ -177,6 +181,8 @@ export function createInputServer(opts = {}) {
177
181
  let attractPlaylist = null;
178
182
  let attractCursor = null;
179
183
  let attractGeneration = 0;
184
+ let attractAutoStartEnabled = true;
185
+ let attractSelectedPlaylistOnce = false;
180
186
 
181
187
  function clearAttractTimer() {
182
188
  if (attractTimer) clearTimeout(attractTimer);
@@ -294,6 +300,7 @@ export function createInputServer(opts = {}) {
294
300
  csdbUrl: item.url ?? null,
295
301
  rating: item.rating ?? null,
296
302
  playlistPath: attractPlaylist._playlistPath ?? null,
303
+ playlistIndex: attractPlaylist._playlistIndex ?? null,
297
304
  itemIndex,
298
305
  fileIndex,
299
306
  filename,
@@ -311,6 +318,7 @@ export function createInputServer(opts = {}) {
311
318
  attractStatus = { active: false, reason, updatedAt: Date.now() };
312
319
  attractPlaylist = null;
313
320
  attractCursor = null;
321
+ attractSelectedPlaylistOnce = false;
314
322
  if (broadcast && wasActive) broadcastAttractMode();
315
323
  return wasActive;
316
324
  }
@@ -619,7 +627,7 @@ export function createInputServer(opts = {}) {
619
627
  if (typeof attractTimer.unref === 'function') attractTimer.unref();
620
628
  }
621
629
 
622
- async function loadAttractEntry(itemIndex, fileIndex, { mountOnly = false, rebootBeforeLoad = false } = {}) {
630
+ async function loadAttractEntry(itemIndex, fileIndex, { mountOnly = false, rebootBeforeLoad = false, afterStatus = null } = {}) {
623
631
  const generation = attractGeneration;
624
632
  const item = getAttractItem(itemIndex);
625
633
  const file = getAttractFile(item, fileIndex);
@@ -659,6 +667,7 @@ export function createInputServer(opts = {}) {
659
667
  if (generation !== attractGeneration) return;
660
668
  setAttractStatus({ item, file, itemIndex, fileIndex, filename });
661
669
  broadcastAttractMode();
670
+ if (typeof afterStatus === 'function') afterStatus();
662
671
  await runLoadFileCommand({
663
672
  filename,
664
673
  fileType,
@@ -670,20 +679,32 @@ export function createInputServer(opts = {}) {
670
679
  scheduleAttractAdvance();
671
680
  }
672
681
 
673
- async function startAttractMode(demoIndex = 0) {
682
+ async function startAttractMode(
683
+ demoIndex = 0,
684
+ playlistIndex = undefined,
685
+ { afterStatus = null, resumeAutoStart = false } = {},
686
+ ) {
674
687
  if (!attractEnabled) throw new Error('Attract Mode is not configured');
675
688
  attractGeneration += 1;
689
+ const generation = attractGeneration;
676
690
  clearAttractTimer();
691
+ if (resumeAutoStart) attractAutoStartEnabled = true;
677
692
  const manifest = await fetchAttractJson(resolveAttractUrl(attractManifest));
693
+ if (generation !== attractGeneration) return;
678
694
  logEv('attract-manifest-loaded', { count: Array.isArray(manifest) ? manifest.length : '-' });
679
695
  if (!Array.isArray(manifest) || manifest.length === 0) {
680
696
  throw new Error('No Attract Mode playlists configured');
681
697
  }
682
- const playlistEntry = chooseRandom(manifest);
698
+ if (playlistIndex != null && (!Number.isInteger(playlistIndex) || playlistIndex < 0 || playlistIndex >= manifest.length)) {
699
+ throw new Error(`Playlist index ${playlistIndex} is out of bounds (manifest has ${manifest.length} playlists)`);
700
+ }
701
+ const resolvedPlaylistIndex = playlistIndex ?? manifest.indexOf(chooseRandom(manifest));
702
+ const playlistEntry = manifest[resolvedPlaylistIndex];
683
703
  const playlistPath = typeof playlistEntry === 'string' ? playlistEntry : playlistEntry?.filename;
684
704
  if (!playlistPath) throw new Error('Invalid Attract Mode playlist entry');
685
- logEv('attract-playlist-selected', { playlistPath });
705
+ logEv('attract-playlist-selected', { playlistPath, playlistIndex: resolvedPlaylistIndex });
686
706
  const playlist = await fetchAttractJson(resolveAttractUrl(playlistPath));
707
+ if (generation !== attractGeneration) return;
687
708
  if (!playlist?.name) throw new Error('Attract Mode playlist is missing a name');
688
709
  if (!Array.isArray(playlist.items) || playlist.items.length === 0) {
689
710
  throw new Error('Attract Mode playlist has no demos');
@@ -691,15 +712,17 @@ export function createInputServer(opts = {}) {
691
712
  if (demoIndex < 0 || demoIndex >= playlist.items.length) {
692
713
  throw new Error(`Demo index ${demoIndex} is out of bounds (playlist has ${playlist.items.length} demos)`);
693
714
  }
694
- attractPlaylist = { ...playlist, _playlistPath: playlistPath };
695
- await loadAttractEntry(demoIndex, 0, { rebootBeforeLoad: true });
715
+ attractSelectedPlaylistOnce = playlistIndex != null;
716
+ attractPlaylist = { ...playlist, _playlistPath: playlistPath, _playlistIndex: resolvedPlaylistIndex };
717
+ await loadAttractEntry(demoIndex, 0, { rebootBeforeLoad: true, afterStatus });
696
718
  }
697
719
 
698
720
  function startAttractModeIfRoomEmpty(reason = 'empty-room') {
699
- if (!attractEnabled || attractStatus.active || hostClient || p2Client) {
721
+ if (!attractEnabled || !attractAutoStartEnabled || attractStatus.active || hostClient || p2Client) {
700
722
  logEv('attract-empty-room-start-skipped', {
701
723
  reason,
702
724
  attractEnabled,
725
+ autoStartEnabled: attractAutoStartEnabled,
703
726
  active: !!attractStatus.active,
704
727
  hasHost: !!hostClient,
705
728
  hasP2: !!p2Client,
@@ -716,10 +739,11 @@ export function createInputServer(opts = {}) {
716
739
 
717
740
  function scheduleAttractModeIfRoomEmpty(reason = 'empty-room') {
718
741
  clearEmptyRoomAttractTimer();
719
- if (!attractEnabled || attractStatus.active || hostClient || p2Client) {
742
+ if (!attractEnabled || !attractAutoStartEnabled || attractStatus.active || hostClient || p2Client) {
720
743
  logEv('attract-empty-room-schedule-skipped', {
721
744
  reason,
722
745
  attractEnabled,
746
+ autoStartEnabled: attractAutoStartEnabled,
723
747
  active: !!attractStatus.active,
724
748
  hasHost: !!hostClient,
725
749
  hasP2: !!p2Client,
@@ -746,6 +770,11 @@ export function createInputServer(opts = {}) {
746
770
  }
747
771
  const nextItemIndex = (attractCursor.itemIndex + 1) % attractPlaylist.items.length;
748
772
  if (generation !== attractGeneration) return;
773
+ if (nextItemIndex === 0 && attractSelectedPlaylistOnce) {
774
+ attractSelectedPlaylistOnce = false;
775
+ await startAttractMode(0);
776
+ return;
777
+ }
749
778
  await loadAttractEntry(nextItemIndex, 0, { rebootBeforeLoad: true });
750
779
  }
751
780
 
@@ -996,6 +1025,7 @@ export function createInputServer(opts = {}) {
996
1025
  ? {
997
1026
  connected: hostClient.readyState === hostClient.OPEN,
998
1027
  username: hostUsername,
1028
+ joystickPort: hostPort(),
999
1029
  addr: hostMeta?.addr ?? null,
1000
1030
  webrtcPeers: hostWebrtcPeers,
1001
1031
  }
@@ -1004,6 +1034,7 @@ export function createInputServer(opts = {}) {
1004
1034
  ? {
1005
1035
  connected: p2Client.readyState === p2Client.OPEN,
1006
1036
  username: p2Username,
1037
+ joystickPort: p2Port(),
1007
1038
  addr: p2Meta?.addr ?? null,
1008
1039
  webrtcPeers: p2WebrtcPeers,
1009
1040
  }
@@ -1020,6 +1051,10 @@ export function createInputServer(opts = {}) {
1020
1051
  webrtc: webrtcSnapshot,
1021
1052
  runtime: getRuntimeStats?.() ?? null,
1022
1053
  attractMode: attractStatusPayload(),
1054
+ gameState: {
1055
+ cartFilename: currentCartFilename,
1056
+ filename: currentCartFilename,
1057
+ },
1023
1058
  sampledAt: Date.now(),
1024
1059
  };
1025
1060
  }
@@ -1072,6 +1107,14 @@ export function createInputServer(opts = {}) {
1072
1107
 
1073
1108
  // ── Host claim ────────────────────────────────────────────────────────
1074
1109
  if (msg.type === 'host') {
1110
+ if (hostAuthRequired && !validateHostToken(msg.token ?? '')) {
1111
+ ws.send(JSON.stringify({ type: 'host-auth-failed', reason: 'invalid-token' }));
1112
+ logEv('host-claim-rejected', {
1113
+ reason: 'invalid-token',
1114
+ username: msg.username ?? 'player',
1115
+ });
1116
+ return;
1117
+ }
1075
1118
  if (hostClient && hostClient.readyState === hostClient.OPEN) {
1076
1119
  // force:true lets a new connection take over from a stale/ghost host
1077
1120
  // (e.g. page reload, WebRTC reconnect, or lost tab). Without this
@@ -1519,10 +1562,28 @@ export function createInputServer(opts = {}) {
1519
1562
  }
1520
1563
  setWsIdentity(ws, 'admin', null);
1521
1564
  const action = String(msg.action ?? '').toLowerCase();
1522
- const demoIndex = msg.demoIndex != null ? Number(msg.demoIndex) : undefined;
1523
- if (action === 'on') {
1524
- startAttractMode(demoIndex)
1525
- .then(() => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ type: 'admin-attract-mode-ok', action, attractMode: attractStatusPayload() })))
1565
+ const rawDemoIndex = msg.demoIndex != null ? Number(msg.demoIndex) : undefined;
1566
+ const rawIndex = msg.index != null ? Number(msg.index) : undefined;
1567
+ const demoIndex = action === 'playlist' ? 0 : rawDemoIndex;
1568
+ const playlistIndex = msg.playlistIndex != null
1569
+ ? Number(msg.playlistIndex)
1570
+ : action === 'playlist'
1571
+ ? rawDemoIndex ?? rawIndex
1572
+ : undefined;
1573
+ let sentAttractAdminOk = false;
1574
+ const sendAttractAdminOk = () => {
1575
+ if (sentAttractAdminOk) return;
1576
+ sentAttractAdminOk = true;
1577
+ if (ws.readyState === ws.OPEN) {
1578
+ ws.send(JSON.stringify({ type: 'admin-attract-mode-ok', action, attractMode: attractStatusPayload() }));
1579
+ }
1580
+ };
1581
+ if (action === 'on' || action === 'playlist') {
1582
+ startAttractMode(demoIndex, playlistIndex, {
1583
+ afterStatus: sendAttractAdminOk,
1584
+ resumeAutoStart: true,
1585
+ })
1586
+ .then(sendAttractAdminOk)
1526
1587
  .catch((e) => {
1527
1588
  stopAttractMode({ reason: 'error' });
1528
1589
  if (ws.readyState === ws.OPEN) {
@@ -1532,8 +1593,13 @@ export function createInputServer(opts = {}) {
1532
1593
  return;
1533
1594
  }
1534
1595
  if (action === 'off') {
1596
+ attractAutoStartEnabled = false;
1535
1597
  stopAttractMode({ reason: 'admin' });
1536
- ws.send(JSON.stringify({ type: 'admin-attract-mode-ok', action, attractMode: attractStatusPayload() }));
1598
+ sendAttractAdminOk();
1599
+ return;
1600
+ }
1601
+ if (ws.readyState === ws.OPEN) {
1602
+ ws.send(JSON.stringify({ type: 'admin-error', command: 'attract-mode', reason: 'invalid-action' }));
1537
1603
  }
1538
1604
  return;
1539
1605
  }
@@ -1614,10 +1680,17 @@ export function createInputServer(opts = {}) {
1614
1680
  return;
1615
1681
  }
1616
1682
  const action = String(msg.action ?? '').toLowerCase();
1617
- const demoIndex = msg.demoIndex != null ? Number(msg.demoIndex) : undefined;
1618
- logEv('cmd-attract-mode', { action, host: hostUsername ?? '-', demoIndex: demoIndex ?? '-' });
1619
- if (action === 'on') {
1620
- startAttractMode(demoIndex)
1683
+ const rawDemoIndex = msg.demoIndex != null ? Number(msg.demoIndex) : undefined;
1684
+ const rawIndex = msg.index != null ? Number(msg.index) : undefined;
1685
+ const demoIndex = action === 'playlist' ? 0 : rawDemoIndex;
1686
+ const playlistIndex = msg.playlistIndex != null
1687
+ ? Number(msg.playlistIndex)
1688
+ : action === 'playlist'
1689
+ ? rawDemoIndex ?? rawIndex
1690
+ : undefined;
1691
+ logEv('cmd-attract-mode', { action, host: hostUsername ?? '-', demoIndex: demoIndex ?? '-', playlistIndex: playlistIndex ?? '-' });
1692
+ if (action === 'on' || action === 'playlist') {
1693
+ startAttractMode(demoIndex, playlistIndex, { resumeAutoStart: true })
1621
1694
  .then(() => {
1622
1695
  if (ws.readyState === ws.OPEN) {
1623
1696
  ws.send(JSON.stringify({ type: 'attract-mode-ok', action, attractMode: attractStatusPayload() }));
@@ -1634,6 +1707,7 @@ export function createInputServer(opts = {}) {
1634
1707
  return;
1635
1708
  }
1636
1709
  if (action === 'off') {
1710
+ attractAutoStartEnabled = false;
1637
1711
  stopAttractMode({ reason: 'manual' });
1638
1712
  if (ws.readyState === ws.OPEN) {
1639
1713
  ws.send(JSON.stringify({ type: 'attract-mode-ok', action, attractMode: attractStatusPayload() }));
@@ -1824,6 +1898,7 @@ export function createInputServer(opts = {}) {
1824
1898
  type: 'hello',
1825
1899
  protocol: 'c64-input',
1826
1900
  version: 1,
1901
+ hostAuthRequired,
1827
1902
  serverTime, // Unix ms for client clock sync
1828
1903
  // During grace period: treat slot as free so the original host can reclaim it.
1829
1904
  // hostPendingRejoin tells P2 (and spectators) to hold off.
@@ -0,0 +1,72 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 hayesmaker
3
+ // See LICENSE in the project root for full license information.
4
+ /**
5
+ * png.mjs — dependency-free PNG encoder for raw RGBA frame buffers.
6
+ *
7
+ * Used by the agent CLI (`c64-agent --screenshot`) to write emulator frames
8
+ * to disk. Relies only on node:zlib (deflateSync + crc32).
9
+ */
10
+
11
+ import { deflateSync, crc32 } from 'node:zlib';
12
+
13
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
14
+
15
+ function chunk(type, data) {
16
+ const len = Buffer.alloc(4);
17
+ len.writeUInt32BE(data.length, 0);
18
+ const typeAndData = Buffer.concat([Buffer.from(type, 'ascii'), data]);
19
+ const crc = Buffer.alloc(4);
20
+ crc.writeUInt32BE(crc32(typeAndData) >>> 0, 0);
21
+ return Buffer.concat([len, typeAndData, crc]);
22
+ }
23
+
24
+ /**
25
+ * Encode an RGBA buffer as an 8-bit truecolour PNG (alpha dropped — C64 frames are opaque).
26
+ *
27
+ * @param {Uint8Array} rgba width*height*4 bytes
28
+ * @param {number} width
29
+ * @param {number} height
30
+ * @param {{ scale?: number }} [opts] integer nearest-neighbour upscale (default 1)
31
+ * @returns {Buffer}
32
+ */
33
+ export function encodePng(rgba, width, height, opts = {}) {
34
+ const scale = Math.max(1, Math.floor(opts.scale ?? 1));
35
+ if (rgba.length < width * height * 4) {
36
+ throw new Error(`encodePng: buffer too small (${rgba.length} < ${width * height * 4})`);
37
+ }
38
+ const outW = width * scale;
39
+ const outH = height * scale;
40
+ const stride = outW * 3 + 1;
41
+ const raw = Buffer.alloc(stride * outH);
42
+
43
+ for (let y = 0; y < outH; y++) {
44
+ const srcRow = Math.floor(y / scale) * width * 4;
45
+ let o = y * stride;
46
+ raw[o++] = 0; // filter: none
47
+ for (let x = 0; x < outW; x++) {
48
+ const s = srcRow + Math.floor(x / scale) * 4;
49
+ raw[o++] = rgba[s];
50
+ raw[o++] = rgba[s + 1];
51
+ raw[o++] = rgba[s + 2];
52
+ }
53
+ }
54
+
55
+ const ihdr = Buffer.alloc(13);
56
+ ihdr.writeUInt32BE(outW, 0);
57
+ ihdr.writeUInt32BE(outH, 4);
58
+ ihdr[8] = 8; // bit depth
59
+ ihdr[9] = 2; // colour type: truecolour RGB
60
+ ihdr[10] = 0; // compression
61
+ ihdr[11] = 0; // filter
62
+ ihdr[12] = 0; // interlace
63
+
64
+ return Buffer.concat([
65
+ PNG_SIGNATURE,
66
+ chunk('IHDR', ihdr),
67
+ chunk('IDAT', deflateSync(raw, { level: 6 })),
68
+ chunk('IEND', Buffer.alloc(0)),
69
+ ]);
70
+ }
71
+
72
+ export default encodePng;