c64-ready 3.1.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.
@@ -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;
@@ -127,6 +127,69 @@ function buildIceServers({
127
127
  return iceServers;
128
128
  }
129
129
 
130
+ export const DEFAULT_ICE_PORT_RANGE = '50000-50100';
131
+ const ROUTE_SNAPSHOT_RETRIES = 5;
132
+ const FALLBACK_STUN_URL = 'stun:stun.l.google.com:19302';
133
+
134
+ /**
135
+ * Whether the server's own peer connections may allocate TURN relay candidates.
136
+ *
137
+ * A host with a public IP and a published ICE port range never needs a relay
138
+ * itself, but offering one lets ICE settle on server-relayed pairs — on a remote
139
+ * TURN service that adds a detour to every packet. Browsers still receive the
140
+ * TURN config via /ice-config, so clients behind strict NATs can relay.
141
+ *
142
+ * @param {string} [raw] "0"/"false"/"off"/"no" disables; anything else enables
143
+ * @returns {boolean}
144
+ */
145
+ export function parseServerUseTurn(raw = process.env.ICE_SERVER_USE_TURN) {
146
+ const value = String(raw ?? '').trim().toLowerCase();
147
+ return !['0', 'false', 'off', 'no'].includes(value);
148
+ }
149
+
150
+ /**
151
+ * Strip turn:/turns: URLs from an iceServers list, keeping at least one STUN
152
+ * server so the host still gathers its server-reflexive (public) candidate.
153
+ *
154
+ * @param {RTCIceServer[]} iceServers
155
+ * @returns {RTCIceServer[]}
156
+ */
157
+ export function withoutTurnServers(iceServers) {
158
+ const stunOnly = (iceServers ?? [])
159
+ .map((server) => ({
160
+ urls: [].concat(server?.urls ?? []).filter((url) => !/^turns?:/i.test(String(url))),
161
+ }))
162
+ .filter((server) => server.urls.length > 0);
163
+ return stunOnly.length > 0 ? stunOnly : [{ urls: [FALLBACK_STUN_URL] }];
164
+ }
165
+
166
+ /**
167
+ * Parse the UDP/TCP port range libwebrtc may bind ICE candidates to.
168
+ *
169
+ * Without a range libwebrtc picks random ephemeral ports. Inside Docker only the
170
+ * published range (`-p 50000-50100:50000-50100/udp`) is reachable from outside,
171
+ * so direct (host/srflx) candidates fail and every peer falls back to a TURN
172
+ * relay — adding the relay's round trip to every input and frame.
173
+ *
174
+ * @param {string} [raw] "min-max", or "off" to let libwebrtc choose freely
175
+ * @returns {{ min: number, max: number } | null}
176
+ */
177
+ export function parseIcePortRange(raw = process.env.ICE_PORT_RANGE) {
178
+ const value = String(raw ?? '').trim().toLowerCase() || DEFAULT_ICE_PORT_RANGE;
179
+ if (value === 'off' || value === '0') return null;
180
+
181
+ const match = /^(\d+)\s*-\s*(\d+)$/.exec(value);
182
+ const min = match ? Number(match[1]) : NaN;
183
+ const max = match ? Number(match[2]) : NaN;
184
+ if (!(min >= 1024 && max <= 65535 && min <= max)) {
185
+ console.error(
186
+ `[webrtc] invalid ICE_PORT_RANGE "${raw}" — expected "min-max" within 1024-65535; using ${DEFAULT_ICE_PORT_RANGE}`,
187
+ );
188
+ return parseIcePortRange(DEFAULT_ICE_PORT_RANGE);
189
+ }
190
+ return { min, max };
191
+ }
192
+
130
193
  /**
131
194
  * @param {object} opts
132
195
  * @param {number} [opts.port=9002] HTTP + WS listen port
@@ -147,6 +210,10 @@ function buildIceServers({
147
210
  * @param {string} [opts.iceTurnUsernameLabel] Optional TURN username suffix for timed creds
148
211
  * @param {string} [opts.iceTurnUsername] Optional TURN username
149
212
  * @param {string} [opts.iceTurnPassword] Optional TURN credential/password
213
+ * @param {string} [opts.icePortRange] ICE port range "min-max" or "off"
214
+ * (default ICE_PORT_RANGE env, else 50000-50100)
215
+ * @param {string|boolean} [opts.iceServerUseTurn] Let server peers use TURN (default
216
+ * ICE_SERVER_USE_TURN env, else enabled)
150
217
  * @param {(pc: RTCPeerConnection) => void} opts.onOffer
151
218
  * Called synchronously when an SDP offer arrives, BEFORE createAnswer().
152
219
  * Attach tracks here: pc.addTrack(videoTrack, stream)
@@ -171,6 +238,8 @@ export function createWebRTCServer({
171
238
  iceTurnUsernameLabel,
172
239
  iceTurnUsername,
173
240
  iceTurnPassword,
241
+ icePortRange,
242
+ iceServerUseTurn,
174
243
  onOffer,
175
244
  onPeerConnected,
176
245
  onDataChannelInput,
@@ -188,6 +257,26 @@ export function createWebRTCServer({
188
257
  });
189
258
 
190
259
  const iceServers = buildRuntimeIceServers();
260
+ const portRange = parseIcePortRange(icePortRange);
261
+ if (verbose) {
262
+ console.error(
263
+ `[webrtc] ICE port range ${portRange ? `${portRange.min}-${portRange.max}` : 'unrestricted'}`,
264
+ );
265
+ }
266
+ const serverUseTurn =
267
+ typeof iceServerUseTurn === 'boolean' ? iceServerUseTurn : parseServerUseTurn(iceServerUseTurn);
268
+ if (!serverUseTurn) {
269
+ console.error(
270
+ '[webrtc] server-side TURN disabled (ICE_SERVER_USE_TURN=0); browsers still get TURN via /ice-config',
271
+ );
272
+ }
273
+ const buildPeerConnectionConfig = () => {
274
+ const runtimeIceServers = buildRuntimeIceServers();
275
+ return {
276
+ iceServers: serverUseTurn ? runtimeIceServers : withoutTurnServers(runtimeIceServers),
277
+ ...(portRange ? { portRange } : {}),
278
+ };
279
+ };
191
280
 
192
281
  /** Emit a structured [event] line — same format as input-server.mjs. */
193
282
  function logEv(tag, fields = {}) {
@@ -244,31 +333,44 @@ export function createWebRTCServer({
244
333
  );
245
334
  }
246
335
 
247
- async function logRouteSnapshot(pc, remoteAddr) {
336
+ async function logRouteSnapshot(pc, remoteAddr, attempt = 0) {
248
337
  try {
249
338
  const report = await pc.getStats();
250
- let selected = null;
339
+ let nominated = null;
340
+ const selectedPairIds = new Set();
341
+ const pairsById = new Map();
251
342
  const localById = new Map();
252
343
  const remoteById = new Map();
253
344
  for (const stat of report.values()) {
254
- if (
255
- stat.type === 'candidate-pair' &&
256
- stat.nominated &&
257
- (stat.state === 'succeeded' || stat.selected)
258
- )
259
- selected = stat;
345
+ if (stat.type === 'transport' && stat.selectedCandidatePairId) {
346
+ selectedPairIds.add(stat.selectedCandidatePairId);
347
+ }
348
+ if (stat.type === 'candidate-pair') {
349
+ pairsById.set(stat.id, stat);
350
+ if (stat.nominated && (stat.state === 'succeeded' || stat.selected)) nominated = stat;
351
+ }
260
352
  if (stat.type === 'local-candidate') localById.set(stat.id, stat);
261
353
  if (stat.type === 'remote-candidate') remoteById.set(stat.id, stat);
262
354
  }
263
- if (!selected) return;
355
+ // Prefer the transport's selected pair: libwebrtc's nominated/state flags on
356
+ // candidate-pair stats can lag ICE 'connected', which left this log empty.
357
+ const selected =
358
+ [...selectedPairIds].map((id) => pairsById.get(id)).find(Boolean) ?? nominated;
359
+ if (!selected) {
360
+ if (attempt < ROUTE_SNAPSHOT_RETRIES && pc.connectionState !== 'closed') {
361
+ setTimeout(() => logRouteSnapshot(pc, remoteAddr, attempt + 1), 1000);
362
+ }
363
+ return;
364
+ }
264
365
  const local = localById.get(selected.localCandidateId);
265
366
  const remote = remoteById.get(selected.remoteCandidateId);
367
+ const protocol = selected.protocol ?? local?.protocol ?? '-';
266
368
  const rttMs = Number.isFinite(selected.currentRoundTripTime)
267
369
  ? Math.round(selected.currentRoundTripTime * 1000)
268
370
  : null;
269
371
  logEv('webrtc-route', {
270
372
  addr: remoteAddr,
271
- protocol: selected.protocol ?? '-',
373
+ protocol,
272
374
  localType: local?.candidateType ?? '-',
273
375
  remoteType: remote?.candidateType ?? '-',
274
376
  networkType: local?.networkType ?? '-',
@@ -276,7 +378,7 @@ export function createWebRTCServer({
276
378
  });
277
379
  if (verbose) {
278
380
  console.error(
279
- `[webrtc-route] addr=${remoteAddr} protocol=${selected.protocol ?? '-'} local=${local?.candidateType ?? '-'} remote=${remote?.candidateType ?? '-'} net=${local?.networkType ?? '-'} rtt=${rttMs ?? '-'}ms`,
381
+ `[webrtc-route] addr=${remoteAddr} protocol=${protocol} local=${local?.candidateType ?? '-'} remote=${remote?.candidateType ?? '-'} net=${local?.networkType ?? '-'} rtt=${rttMs ?? '-'}ms`,
280
382
  );
281
383
  }
282
384
  } catch (_) {
@@ -632,7 +734,7 @@ export function createWebRTCServer({
632
734
  const remoteAddr = req.socket.remoteAddress;
633
735
  const sessionId = crypto.randomUUID();
634
736
  pendingPeers++;
635
- const pc = new RTCPeerConnection({ iceServers: buildRuntimeIceServers() });
737
+ const pc = new RTCPeerConnection(buildPeerConnectionConfig());
636
738
  const controller = {
637
739
  pc,
638
740
  ws: null,
@@ -860,7 +962,7 @@ export function createWebRTCServer({
860
962
  logEv('webrtc-peer-connected', { addr: remoteAddr });
861
963
  logLoadSnapshot('webrtc-load-change', { reason: 'peer-connected' });
862
964
 
863
- const pc = new RTCPeerConnection({ iceServers: buildRuntimeIceServers() });
965
+ const pc = new RTCPeerConnection(buildPeerConnectionConfig());
864
966
  const controller = {
865
967
  pc,
866
968
  ws,
package/src/main.ts CHANGED
@@ -193,16 +193,36 @@ window.addEventListener('c64-load-error', (e: Event) => {
193
193
  | undefined;
194
194
  const msg = normalizeErrorMessage(detail?.error ?? 'Unknown load error');
195
195
  console.error('C64 load error event:', detail);
196
+ loadWarningShown = false;
196
197
  renderer.setError('LOAD ERROR');
197
198
  status.textContent = `Load error: ${msg}`;
198
199
  status.style.color = '#f44';
199
200
  });
200
201
 
202
+ // Set while a load-time warning is on screen so the success message doesn't hide it
203
+ let loadWarningShown = false;
204
+
205
+ window.addEventListener('c64-load-success', (e: Event) => {
206
+ const detail = (e as CustomEvent<{ name?: string }>).detail;
207
+ if (loadWarningShown) {
208
+ loadWarningShown = false;
209
+ return;
210
+ }
211
+ status.textContent = `Loaded: ${detail?.name ?? 'game'}`;
212
+ status.style.color = '#9ecbff';
213
+ });
214
+
215
+ window.addEventListener('c64-detach', () => {
216
+ status.textContent = 'Cartridge detached (no game loaded)';
217
+ status.style.color = '#9ecbff';
218
+ });
219
+
201
220
  window.addEventListener('c64-load-info', (e: Event) => {
202
221
  const detail = (e as CustomEvent).detail as
203
222
  | { mode?: string; source?: string; message?: string }
204
223
  | undefined;
205
224
  if (!detail?.message) return;
225
+ loadWarningShown = detail.mode === 'warning';
206
226
  status.textContent = detail.message;
207
227
  status.style.color = detail.mode === 'warning' ? '#f9c74f' : '#9ecbff';
208
228
  console.info('C64 load info event:', detail);
@@ -38,6 +38,12 @@ export interface C64PlayerOptions {
38
38
  audio?: AudioEngineOptions;
39
39
  }
40
40
 
41
+ export interface LoadedGame {
42
+ name: string;
43
+ type: GameLoadOptions['type'];
44
+ data: Uint8Array<ArrayBufferLike>;
45
+ }
46
+
41
47
  export class C64Player {
42
48
  private emulator: C64Emulator | null = null;
43
49
  private inputHandler: InputHandler | null = null;
@@ -49,6 +55,7 @@ export class C64Player {
49
55
  private startupLoadInProgress: boolean = false;
50
56
  private startupDiskAutoloadPending: boolean = false;
51
57
  private debugSpeed: number = NORMAL_DEBUG_SPEED;
58
+ private currentGame: LoadedGame | null = null;
52
59
  readonly audio: AudioEngine;
53
60
  private readonly options: Required<Pick<C64PlayerOptions, 'wasmUrl' | 'gameUrl' | 'gameType'>> &
54
61
  C64PlayerOptions;
@@ -227,6 +234,11 @@ export class C64Player {
227
234
  await this.loadGame(url, resolvedType, onProgress);
228
235
  }
229
236
 
237
+ /** The most recently loaded game, or null after a detach/reboot. */
238
+ getCurrentGame(): LoadedGame | null {
239
+ return this.currentGame;
240
+ }
241
+
230
242
  // Expose cartridge / reset controls for UI
231
243
  detachCartridge(): void {
232
244
  if (!this.emulator) return;
@@ -234,6 +246,7 @@ export class C64Player {
234
246
  this.emulator.removeCartridge();
235
247
  this.diskSessionActive = false;
236
248
  this.startupDiskAutoloadPending = false;
249
+ this.currentGame = null;
237
250
  window.dispatchEvent(new CustomEvent('c64-detach', { detail: {} }));
238
251
  window.dispatchEvent(new CustomEvent('c64-close-menu'));
239
252
  } catch (e) {
@@ -262,6 +275,7 @@ export class C64Player {
262
275
  this.emulator.start();
263
276
  this.diskSessionActive = false;
264
277
  this.startupDiskAutoloadPending = false;
278
+ this.currentGame = null;
265
279
  this.emulator.setSampleRate(this.audio.sampleRate);
266
280
  this.applyDebugSpeed();
267
281
  this.audio.setSidBufferReader(() => this.emulator?.getSidBuffer() ?? null);
@@ -488,9 +502,11 @@ export class C64Player {
488
502
  } else {
489
503
  this.diskSessionActive = false;
490
504
  }
505
+ const name = getSourceName(source);
506
+ this.currentGame = { name, type, data };
491
507
  onProgress?.(100, 'READY!');
492
508
  window.dispatchEvent(
493
- new CustomEvent('c64-load-success', { detail: { ...eventDetail, type } }),
509
+ new CustomEvent('c64-load-success', { detail: { ...eventDetail, name, type } }),
494
510
  );
495
511
  } catch (err) {
496
512
  onProgress?.(0, 'FAILED');
@@ -694,3 +710,8 @@ function hasViceSnapshotMagic(data: Uint8Array<ArrayBufferLike>): boolean {
694
710
  }
695
711
  return true;
696
712
  }
713
+
714
+ function getSourceName(source: string): string {
715
+ const path = source.split(/[?#]/)[0];
716
+ return path.split('/').filter(Boolean).pop() || source;
717
+ }
@@ -10,6 +10,7 @@ const css = `
10
10
  .c64-dragarea{border:1px dashed #555;border-radius:6px;background:#111827;color:#aaa;padding:18px;margin:0 0 12px;text-align:center}.c64-dragarea.dragover{border-color:#7b71d5;background:#1f1b38;color:#fff}.c64-cart-preview,.c64-tools-section{background:#151527;border:1px solid #2a2a3e;border-radius:6px;padding:12px;margin:12px 0}.c64-section-hint{color:#888;font-size:12px;line-height:1.4;margin:4px 0 12px}.c64-checkbox-row{display:flex;align-items:center;gap:8px;color:#ccc;font-size:13px;margin:14px 0 4px}
11
11
  .c64-text-input,.c64-textarea{background:#111827;border:1px solid #444;border-radius:3px;color:#ddd;font:inherit;font-size:13px;padding:5px 8px}.c64-text-input{min-width:180px}.c64-textarea{box-sizing:border-box;width:100%;min-height:120px;resize:vertical}.c64-cheevos-json-file{display:none}.c64-inline-status{color:#888;font-size:12px}
12
12
  .c64-cheat-list{display:grid;gap:12px;margin:0 0 12px}.c64-cheat-card{background:#151527;border:1px solid #2a2a3e;border-radius:6px;padding:12px}.c64-cheat-card-header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:0 0 10px;color:#ddd;font-size:13px}.c64-cheat-remove{background:none;border:0;color:#ff9a9a;cursor:pointer;font:inherit;font-size:12px}.c64-cheat-grid{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:8px 10px;align-items:center}.c64-cheat-input{background:#111827;border:1px solid #444;border-radius:3px;color:#ddd;font:inherit;font-size:13px;min-width:0;padding:5px 8px}.c64-cheat-error{color:#ff9a9a;font-size:12px;margin:8px 0 0}.c64-cheat-status{color:#aaa;font-size:12px;line-height:1.4;margin:8px 0 0}.c64-cheat-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}@media (max-width:600px){.c64-cheat-grid{grid-template-columns:1fr}.c64-cheat-grid label{margin-top:4px}}
13
+ .c64-cheat-status[data-mode=ok]{color:#8fd694}.c64-cheat-status[data-mode=error]{color:#f77}#c64-ultimate-device[data-connected]{color:#8fd694}.c64-settings-section .c64-section-hint a{color:#a8a8ff;text-decoration:none}
13
14
  `;
14
15
 
15
16
  export interface UIControllerOptions {
@@ -53,6 +54,7 @@ import type { C64Player } from './c64-player';
53
54
  import type { JoystickPort } from '../emulator/constants';
54
55
  import { chooseAndStoreCheevosRom, storeCheevosRomFile } from './local-rom-store';
55
56
  import { toViteFsUrl } from './startup-params';
57
+ import UltimatePanel from './ultimate-panel';
56
58
  import {
57
59
  LOAD_FORMAT_OPTIONS,
58
60
  getAcceptForLoadTypeSelection,
@@ -834,6 +836,7 @@ export default class UIController {
834
836
  { id: 'audio', label: 'Audio' },
835
837
  { id: 'cheevos', label: 'Cheevos' },
836
838
  { id: 'cheats', label: 'Cheats' },
839
+ { id: 'ultimate', label: 'Ultimate' },
837
840
  { id: 'system', label: 'System' },
838
841
  ] as const;
839
842
 
@@ -977,6 +980,10 @@ export default class UIController {
977
980
  </div>
978
981
  </section>
979
982
 
983
+ <section class="c64-settings-section" data-settings-section="ultimate" hidden>
984
+ <div id="c64-ultimate-section-anchor"></div>
985
+ </section>
986
+
980
987
  <section class="c64-settings-section" data-settings-section="system" hidden>
981
988
  <label class="c64-section-label">System Actions</label>
982
989
  <div class="c64-system-actions">
@@ -1433,6 +1440,10 @@ export default class UIController {
1433
1440
  const audioContainer = panel.querySelector('#c64-audio-section-anchor') as HTMLElement;
1434
1441
  this.createAudioSection(audioContainer);
1435
1442
 
1443
+ // ── Ultimate section ──────────────────────────────────────────────────
1444
+ const ultimateContainer = panel.querySelector('#c64-ultimate-section-anchor') as HTMLElement;
1445
+ new UltimatePanel(ultimateContainer, () => this.player).init();
1446
+
1436
1447
  // ── Input section wiring ───────────────────────────────────────────────
1437
1448
  const joyRadios = panel.querySelectorAll(
1438
1449
  'input[name="c64-joy-port"]',
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Client for the `@c64cade/ultimate-bridge` npm bridge. Browsers can't call an Ultimate's
3
+ * REST API directly, so requests go to the bridge running on the user's machine, which
4
+ * forwards them to the device. The protocol matches C64Cade's own client.
5
+ */
6
+
7
+ export const DEFAULT_BRIDGE_URL = 'http://localhost:6464';
8
+ export const ULTIMATE_BRIDGE_PACKAGE_URL = 'https://www.npmjs.com/package/@c64cade/ultimate-bridge';
9
+ export const ULTIMATE_FILE_TYPES = ['prg', 'crt', 'd64'] as const;
10
+ export const DEFAULT_D64_AUTOLOAD_COMMAND = 'LOAD"*",8,1\nRUN';
11
+
12
+ const BRIDGE_URL_STORAGE_KEY = 'c64-ultimate-bridge-url';
13
+ const IP_STORAGE_KEY = 'c64-ultimate-ip';
14
+ const PASSWORD_STORAGE_KEY = 'c64-ultimate-password';
15
+
16
+ export type UltimateFileType = (typeof ULTIMATE_FILE_TYPES)[number];
17
+
18
+ export interface UltimateSettings {
19
+ bridgeUrl: string;
20
+ ip: string;
21
+ password: string;
22
+ }
23
+
24
+ export interface UltimateDeviceInfo {
25
+ product?: string;
26
+ firmware_version?: string;
27
+ fpga_version?: string;
28
+ core_version?: string;
29
+ hostname?: string;
30
+ unique_id?: string;
31
+ [key: string]: unknown;
32
+ }
33
+
34
+ export interface UltimateLaunchOptions {
35
+ fileType: UltimateFileType;
36
+ filename: string;
37
+ data: Uint8Array<ArrayBufferLike>;
38
+ joyPort?: number;
39
+ autoLoadCommand?: string;
40
+ }
41
+
42
+ export function getSavedUltimateSettings(): UltimateSettings {
43
+ return {
44
+ bridgeUrl: readStorage(BRIDGE_URL_STORAGE_KEY) || DEFAULT_BRIDGE_URL,
45
+ ip: readStorage(IP_STORAGE_KEY),
46
+ password: readStorage(PASSWORD_STORAGE_KEY),
47
+ };
48
+ }
49
+
50
+ export function saveUltimateSettings(settings: Partial<UltimateSettings>): void {
51
+ if (settings.bridgeUrl !== undefined)
52
+ writeStorage(BRIDGE_URL_STORAGE_KEY, settings.bridgeUrl || DEFAULT_BRIDGE_URL);
53
+ if (settings.ip !== undefined) writeStorage(IP_STORAGE_KEY, settings.ip);
54
+ if (settings.password !== undefined) writeStorage(PASSWORD_STORAGE_KEY, settings.password);
55
+ }
56
+
57
+ export function isUltimateFileType(value: unknown): value is UltimateFileType {
58
+ return typeof value === 'string' && (ULTIMATE_FILE_TYPES as readonly string[]).includes(value);
59
+ }
60
+
61
+ export function isValidUltimateIp(ip: string): boolean {
62
+ const value = ip.trim();
63
+ return (
64
+ /^(?:\d{1,3}\.){3}\d{1,3}$/.test(value) &&
65
+ value.split('.').every((octet) => Number(octet) <= 255)
66
+ );
67
+ }
68
+
69
+ export async function getUltimateInfo(settings: UltimateSettings): Promise<UltimateDeviceInfo> {
70
+ const { bridgeUrl, ip, password } = settings;
71
+ return (await postToBridge(bridgeUrl, '/ultimate/info', { ip, password })) as UltimateDeviceInfo;
72
+ }
73
+
74
+ export async function launchOnUltimate(
75
+ settings: UltimateSettings,
76
+ options: UltimateLaunchOptions,
77
+ ): Promise<void> {
78
+ const { bridgeUrl, ip, password } = settings;
79
+ await postToBridge(bridgeUrl, '/ultimate/launch', {
80
+ ip,
81
+ password,
82
+ fileType: options.fileType,
83
+ filename: options.filename,
84
+ fileBase64: bytesToBase64(options.data),
85
+ autoLoadCommand: options.autoLoadCommand ?? DEFAULT_D64_AUTOLOAD_COMMAND,
86
+ joyPort: options.joyPort ?? 2,
87
+ });
88
+ }
89
+
90
+ export async function rebootUltimate(settings: UltimateSettings): Promise<void> {
91
+ const { bridgeUrl, ip, password } = settings;
92
+ await postToBridge(bridgeUrl, '/ultimate/reboot', { ip, password });
93
+ }
94
+
95
+ export async function powerOffUltimate(settings: UltimateSettings): Promise<void> {
96
+ const { bridgeUrl, ip, password } = settings;
97
+ await postToBridge(bridgeUrl, '/ultimate/poweroff', { ip, password, timeoutMs: 1500 }, 2500);
98
+ }
99
+
100
+ export function bytesToBase64(bytes: Uint8Array<ArrayBufferLike>): string {
101
+ let binary = '';
102
+ const chunkSize = 0x8000;
103
+ for (let index = 0; index < bytes.length; index += chunkSize) {
104
+ binary += String.fromCharCode(...bytes.subarray(index, index + chunkSize));
105
+ }
106
+ return btoa(binary);
107
+ }
108
+
109
+ async function postToBridge(
110
+ bridgeUrl: string,
111
+ path: string,
112
+ body: Record<string, unknown>,
113
+ timeoutMs?: number,
114
+ ): Promise<unknown> {
115
+ const baseUrl = (bridgeUrl || DEFAULT_BRIDGE_URL).replace(/\/$/, '');
116
+ const controller = timeoutMs ? new AbortController() : null;
117
+ const timer = controller ? window.setTimeout(() => controller.abort(), timeoutMs) : null;
118
+
119
+ let response: Response;
120
+ try {
121
+ response = await fetch(`${baseUrl}${path}`, {
122
+ method: 'POST',
123
+ headers: { 'Content-Type': 'application/json' },
124
+ body: JSON.stringify(body),
125
+ signal: controller?.signal,
126
+ });
127
+ } catch (err) {
128
+ // fetch only rejects when the bridge itself can't be reached; Ultimate errors come back as JSON.
129
+ if ((err as Error)?.name === 'AbortError')
130
+ throw new Error(`The Ultimate bridge at ${baseUrl} did not respond in time.`, {
131
+ cause: err,
132
+ });
133
+ throw new Error(
134
+ `Could not reach the Ultimate bridge at ${baseUrl}. Start it with: npx @c64cade/ultimate-bridge`,
135
+ { cause: err },
136
+ );
137
+ } finally {
138
+ if (timer !== null) window.clearTimeout(timer);
139
+ }
140
+
141
+ const data = (await response.json().catch(() => null)) as { error?: string } | null;
142
+ if (!response.ok) throw new Error(data?.error || `Bridge request failed: ${response.status}`);
143
+ return data;
144
+ }
145
+
146
+ function readStorage(key: string): string {
147
+ try {
148
+ return window.localStorage.getItem(key) ?? '';
149
+ } catch {
150
+ return '';
151
+ }
152
+ }
153
+
154
+ function writeStorage(key: string, value: string): void {
155
+ try {
156
+ if (value) window.localStorage.setItem(key, value);
157
+ else window.localStorage.removeItem(key);
158
+ } catch {
159
+ // storage unavailable (private mode etc.)
160
+ }
161
+ }