c64-ready 2.5.0 → 3.1.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 (100) hide show
  1. package/README.md +32 -0
  2. package/bin/admin.mjs +7 -1
  3. package/bin/headless.mjs +1 -1
  4. package/dist/assets/BeachHead-CuSwFD4k.js +1 -0
  5. package/dist/assets/ChuckieEgg-CPqBnAOF.js +1 -0
  6. package/dist/assets/ForbiddenForest-DsQ9jsc8.js +1 -0
  7. package/dist/assets/Galaga-Cutc3p9s.js +1 -0
  8. package/dist/assets/Gribbly-DdZ_hHFt.js +1 -0
  9. package/dist/assets/Hercules-vZYKm7GG.js +1 -0
  10. package/dist/assets/LegendOfWilf-CxSMOjsj.js +1 -0
  11. package/dist/assets/MariosCementFactory-z0IZ0q30.js +1 -0
  12. package/dist/assets/MoleAttack-buC6ChYy.js +1 -0
  13. package/dist/assets/MunchyWorm-D2Zv7i0Q.js +1 -0
  14. package/dist/assets/ParkPatrol-CVj7hyoB.js +1 -0
  15. package/dist/assets/PottyPigeon-0SYpIUBa.js +1 -0
  16. package/dist/assets/RainbowIslands-BjfmJB8z.js +1 -0
  17. package/dist/assets/Stix-BU-qUCeC.js +1 -0
  18. package/dist/assets/Tilt-C5KtKisF.js +1 -0
  19. package/dist/assets/UpNDown-CATRO7Mz.js +1 -0
  20. package/dist/assets/Uridium-DanS2KoH.js +1 -0
  21. package/dist/assets/VegetablesDeluxe-C41ViimS.js +1 -0
  22. package/dist/assets/index-B8DSjPqI.js +243 -0
  23. package/dist/assets/src-DX0rJQsE.js +1 -0
  24. package/dist/assets/src-_trgwTvp.js +2 -0
  25. package/dist/assets/string-utils-CMVABfx0.js +1 -0
  26. package/dist/index.html +1 -1
  27. package/dist-ts/emulator/c64-emulator.d.ts +2 -2
  28. package/dist-ts/emulator/c64-emulator.js +2 -2
  29. package/dist-ts/emulator/c64-keys.d.ts +69 -0
  30. package/dist-ts/emulator/c64-keys.d.ts.map +1 -0
  31. package/dist-ts/emulator/c64-keys.js +69 -0
  32. package/dist-ts/emulator/c64-keys.js.map +1 -0
  33. package/dist-ts/emulator/c64-wasm.d.ts +1 -1
  34. package/dist-ts/emulator/gamepad-mapping.d.ts +64 -0
  35. package/dist-ts/emulator/gamepad-mapping.d.ts.map +1 -0
  36. package/dist-ts/emulator/gamepad-mapping.js +154 -0
  37. package/dist-ts/emulator/gamepad-mapping.js.map +1 -0
  38. package/dist-ts/emulator/input.d.ts +27 -78
  39. package/dist-ts/emulator/input.d.ts.map +1 -1
  40. package/dist-ts/emulator/input.js +94 -215
  41. package/dist-ts/emulator/input.js.map +1 -1
  42. package/dist-ts/headless/audio-capture.d.ts +1 -1
  43. package/dist-ts/headless/c64-headless.d.ts +2 -2
  44. package/dist-ts/headless/c64-headless.js +4 -4
  45. package/dist-ts/headless/frame-capture.d.ts +1 -1
  46. package/dist-ts/headless/input-bridge.d.ts +1 -1
  47. package/dist-ts/player/c64-player.d.ts +21 -5
  48. package/dist-ts/player/c64-player.d.ts.map +1 -1
  49. package/dist-ts/player/c64-player.js +32 -5
  50. package/dist-ts/player/c64-player.js.map +1 -1
  51. package/dist-ts/player/canvas-renderer.d.ts +2 -2
  52. package/dist-ts/player/cheevos-dev.d.ts +65 -0
  53. package/dist-ts/player/cheevos-dev.d.ts.map +1 -0
  54. package/dist-ts/player/cheevos-dev.js +237 -0
  55. package/dist-ts/player/cheevos-dev.js.map +1 -0
  56. package/dist-ts/player/cheevos-tracker-panel.d.ts +21 -0
  57. package/dist-ts/player/cheevos-tracker-panel.d.ts.map +1 -0
  58. package/dist-ts/player/cheevos-tracker-panel.js +242 -0
  59. package/dist-ts/player/cheevos-tracker-panel.js.map +1 -0
  60. package/dist-ts/player/index.d.ts +10 -7
  61. package/dist-ts/player/index.d.ts.map +1 -1
  62. package/dist-ts/player/index.js +6 -4
  63. package/dist-ts/player/index.js.map +1 -1
  64. package/dist-ts/player/input-handler.d.ts +7 -3
  65. package/dist-ts/player/input-handler.d.ts.map +1 -1
  66. package/dist-ts/player/input-handler.js +24 -1
  67. package/dist-ts/player/input-handler.js.map +1 -1
  68. package/dist-ts/player/load-formats.d.ts +1 -1
  69. package/dist-ts/player/local-rom-store.d.ts +23 -0
  70. package/dist-ts/player/local-rom-store.d.ts.map +1 -0
  71. package/dist-ts/player/local-rom-store.js +87 -0
  72. package/dist-ts/player/local-rom-store.js.map +1 -0
  73. package/dist-ts/player/startup-params.d.ts +7 -0
  74. package/dist-ts/player/startup-params.d.ts.map +1 -0
  75. package/dist-ts/player/startup-params.js +47 -0
  76. package/dist-ts/player/startup-params.js.map +1 -0
  77. package/dist-ts/player/ui-controller.d.ts +23 -1
  78. package/dist-ts/player/ui-controller.d.ts.map +1 -1
  79. package/dist-ts/player/ui-controller.js +665 -1
  80. package/dist-ts/player/ui-controller.js.map +1 -1
  81. package/package.json +2 -1
  82. package/src/emulator/c64-keys.ts +68 -0
  83. package/src/emulator/gamepad-mapping.ts +212 -0
  84. package/src/emulator/input.ts +106 -209
  85. package/src/headless/headless-cli.mjs +10 -4
  86. package/src/headless/input-server.mjs +92 -17
  87. package/src/headless/webrtc-server.mjs +344 -22
  88. package/src/main.ts +177 -12
  89. package/src/player/c64-player.ts +36 -0
  90. package/src/player/cheevos-dev.ts +340 -0
  91. package/src/player/cheevos-tracker-panel.ts +309 -0
  92. package/src/player/index.ts +19 -0
  93. package/src/player/input-handler.ts +32 -0
  94. package/src/player/local-rom-store.ts +126 -0
  95. package/src/player/startup-params.ts +40 -0
  96. package/src/player/ui-controller.ts +740 -0
  97. package/src/types/c64-cheevos.d.ts +6 -0
  98. package/dist/assets/index-BAsZcXuS.js +0 -178
  99. /package/dist/assets/{marked.esm--kBm026b.js → marked.esm-fTuuvbcB.js} +0 -0
  100. /package/dist/assets/{purify.es-BcoGFDcJ.js → purify.es-CRM-GE0Y.js} +0 -0
package/src/main.ts CHANGED
@@ -1,24 +1,29 @@
1
1
  import { C64Player } from './player/c64-player';
2
2
  import CanvasRenderer from './player/canvas-renderer';
3
3
  import UIController from './player/ui-controller';
4
+ import CheevosDevController, { parseCheevosSetJson } from './player/cheevos-dev';
5
+ import type { CheevosDevSet } from './player/cheevos-dev';
6
+ import CheevosTrackerPanel from './player/cheevos-tracker-panel';
4
7
  import { inferLoadTypeFromFilename, isSupportedLoadType } from './player/load-formats';
8
+ import {
9
+ getCheevosRomPath,
10
+ getCheevosRomType,
11
+ getStoredCheevosRom,
12
+ } from './player/local-rom-store';
13
+ import {
14
+ resolveGameFromParam,
15
+ resolveUrlFromParam,
16
+ shouldDisableDefaultGameForCheevos,
17
+ } from './player/startup-params';
5
18
 
6
19
  const status = document.getElementById('status')!;
7
20
  const renderer = new CanvasRenderer('c64-screen');
8
21
  const base = import.meta.env.BASE_URL;
9
22
  const params = new URLSearchParams(window.location.search);
10
23
 
11
- function resolveGameFromParam(raw: string | null, baseUrl: string): string {
12
- if (!raw) return `${baseUrl}games/cartridges/legend-of-wilf.crt`;
13
- const value = raw.trim();
14
- if (!value) return `${baseUrl}games/cartridges/legend-of-wilf.crt`;
15
- if (value.toLowerCase() === 'null') return '';
16
- if (/^https?:\/\//i.test(value)) return value;
17
- if (value.startsWith('/')) return value;
18
- return `${baseUrl}${value.replace(/^\/+/, '')}`;
19
- }
20
-
21
- const gameUrl = resolveGameFromParam(params.get('game'), base);
24
+ const gameUrl = resolveGameFromParam(params.get('game'), base, {
25
+ disableDefault: shouldDisableDefaultGameForCheevos(params),
26
+ });
22
27
  const gameType = inferLoadTypeFromFilename(gameUrl || '') ?? 'crt';
23
28
 
24
29
  // Create player and keep in outer scope so UI can trigger file loads
@@ -30,18 +35,22 @@ const player = new C64Player({
30
35
  audio: { assetBaseUrl: base },
31
36
  onProgress: (pct, label) => renderer.setProgress(pct, label),
32
37
  });
38
+ const cheevosDev = new CheevosDevController(player);
39
+ const cheevosTrackerPanel = new CheevosTrackerPanel();
40
+ cheevosTrackerPanel.init();
33
41
 
34
42
  // Initialise UI with reference to the player (for audio controls)
35
43
  new UIController({ assetBaseUrl: base }).init(player);
36
44
 
37
45
  player
38
46
  .start()
39
- .then(() => {
47
+ .then(async () => {
40
48
  if (!gameUrl) {
41
49
  status.textContent = 'Autoload disabled (?game=null)';
42
50
  status.style.color = '#9ecbff';
43
51
  }
44
52
  renderer.hideLoader();
53
+ await enableCheevosFromParams();
45
54
  })
46
55
  .catch((err) => {
47
56
  console.error(err);
@@ -122,6 +131,61 @@ window.addEventListener('c64-load-tool', async (e: Event) => {
122
131
  }
123
132
  });
124
133
 
134
+ window.addEventListener('c64-cheevos-enable', async (e: Event) => {
135
+ const detail = (e as CustomEvent<{ detectorId?: string; jsonText?: string }>).detail;
136
+ const detectorId = detail?.detectorId?.trim() ?? '';
137
+ if (!detectorId) return;
138
+ try {
139
+ if (detail?.jsonText?.trim()) {
140
+ const cheevosSet = parseCheevosSetJson(detail.jsonText);
141
+ await cheevosDev.enable(detectorId, cheevosSet);
142
+ await loadCheevosRomFromSet(cheevosSet);
143
+ } else {
144
+ await cheevosDev.enable(detectorId);
145
+ }
146
+ } catch (err) {
147
+ const msg = normalizeErrorMessage(String((err as Error)?.message ?? err));
148
+ window.dispatchEvent(
149
+ new CustomEvent('c64-cheevos-error', { detail: { detectorId, error: msg } }),
150
+ );
151
+ }
152
+ });
153
+
154
+ window.addEventListener('c64-cheevos-rom-file', async (e: Event) => {
155
+ const detail = (e as CustomEvent<{ file?: File; type?: string; romPath?: string }>).detail;
156
+ const file = detail?.file;
157
+ if (!file) return;
158
+ const loadType = isSupportedLoadType(detail?.type) ? detail.type : undefined;
159
+ try {
160
+ status.textContent = `Loading cheevos ROM: ${detail?.romPath ?? file.name}`;
161
+ status.style.color = '#9ecbff';
162
+ renderer.showLoader();
163
+ await player.loadFile(file, loadType);
164
+ renderer.hideLoader();
165
+ } catch (err) {
166
+ console.error(err);
167
+ renderer.setError('LOAD ERROR');
168
+ status.textContent = `Cheevos ROM load error: ${normalizeErrorMessage(String(err))}`;
169
+ status.style.color = '#f44';
170
+ }
171
+ });
172
+
173
+ window.addEventListener('c64-cheevos-disable', () => {
174
+ cheevosDev.disable();
175
+ status.textContent = 'Cheevos dev tracking disabled';
176
+ status.style.color = '#9ecbff';
177
+ });
178
+
179
+ window.addEventListener('c64-cheevos-clear-popped', (e: Event) => {
180
+ const detail = (e as CustomEvent<{ detectorId?: string }>).detail;
181
+ cheevosDev.clearPopped(detail?.detectorId);
182
+ });
183
+
184
+ window.addEventListener('c64-cheevos-clear-scores', (e: Event) => {
185
+ const detail = (e as CustomEvent<{ detectorId?: string }>).detail;
186
+ cheevosDev.clearScores(detail?.detectorId);
187
+ });
188
+
125
189
  // Global listener for load errors dispatched by C64Player
126
190
  window.addEventListener('c64-load-error', (e: Event) => {
127
191
  const detail = (e as CustomEvent).detail as
@@ -144,6 +208,45 @@ window.addEventListener('c64-load-info', (e: Event) => {
144
208
  console.info('C64 load info event:', detail);
145
209
  });
146
210
 
211
+ window.addEventListener('c64-cheevos-status', (e: Event) => {
212
+ const detail = (e as CustomEvent<{ detectorId?: string; status?: string; cheevosCount?: number }>)
213
+ .detail;
214
+ if (detail?.status !== 'enabled') return;
215
+ status.textContent = `Cheevos tracking enabled: ${detail.detectorId ?? 'unknown'} (${detail.cheevosCount ?? 0} achievements)`;
216
+ status.style.color = '#9ecbff';
217
+ });
218
+
219
+ window.addEventListener('c64-cheevos-error', (e: Event) => {
220
+ const detail = (e as CustomEvent<{ detectorId?: string; error?: string }>).detail;
221
+ status.textContent = `Cheevos error${detail?.detectorId ? ` (${detail.detectorId})` : ''}: ${detail?.error ?? 'Unknown error'}`;
222
+ status.style.color = '#f44';
223
+ });
224
+
225
+ window.addEventListener('c64-cheevos-score', (e: Event) => {
226
+ const detail = (e as CustomEvent<{ detectorId?: string; score?: { score?: number } }>).detail;
227
+ status.textContent = `Cheevos score captured${detail?.detectorId ? ` for ${detail.detectorId}` : ''}: ${detail?.score?.score ?? 0}`;
228
+ status.style.color = '#9ecbff';
229
+ });
230
+
231
+ window.addEventListener('c64-cheevos-event', (e: Event) => {
232
+ const detail = (
233
+ e as CustomEvent<{
234
+ detectorId?: string;
235
+ type?: string;
236
+ payload?: { title?: string; message?: string; score?: number };
237
+ }>
238
+ ).detail;
239
+ if (!detail?.type) return;
240
+ if (detail.type === 'cheevo') {
241
+ status.textContent = `${detail.payload?.title ?? 'Achievement'}: ${detail.payload?.message ?? 'Unlocked'}`;
242
+ } else if (detail.type === 'gameOver') {
243
+ status.textContent = `Game over${detail.detectorId ? ` (${detail.detectorId})` : ''}: ${detail.payload?.score ?? 0}`;
244
+ } else {
245
+ return;
246
+ }
247
+ status.style.color = '#9ecbff';
248
+ });
249
+
147
250
  window.addEventListener('c64-reboot', () => {
148
251
  status.textContent = 'Emulator rebooted. Load a cartridge to continue.';
149
252
  status.style.color = '#9ecbff';
@@ -157,3 +260,65 @@ function normalizeErrorMessage(msg: string): string {
157
260
  }
158
261
  return out || 'Unknown load error';
159
262
  }
263
+
264
+ async function enableCheevosFromParams(): Promise<void> {
265
+ const detectorId = params.get('cheevos')?.trim();
266
+ if (!detectorId) return;
267
+
268
+ const cheevosSetUrl = resolveUrlFromParam(params.get('cheevosSet'), base);
269
+ try {
270
+ if (cheevosSetUrl) {
271
+ const res = await fetch(cheevosSetUrl, { cache: 'no-store' });
272
+ if (!res.ok) throw new Error(`Failed to fetch cheevos set: ${res.status}`);
273
+ const jsonText = await res.text();
274
+ window.dispatchEvent(
275
+ new CustomEvent('c64-cheevos-json-loaded', {
276
+ detail: { jsonText, source: cheevosSetUrl },
277
+ }),
278
+ );
279
+ const cheevosSet = parseCheevosSetJson(jsonText);
280
+ await cheevosDev.enable(detectorId, cheevosSet);
281
+ await loadCheevosRomFromSet(cheevosSet);
282
+ return;
283
+ }
284
+ await cheevosDev.enable(detectorId);
285
+ } catch (err) {
286
+ const msg = normalizeErrorMessage(String((err as Error)?.message ?? err));
287
+ window.dispatchEvent(
288
+ new CustomEvent('c64-cheevos-error', { detail: { detectorId, error: msg } }),
289
+ );
290
+ }
291
+ }
292
+
293
+ async function loadCheevosRomFromSet(cheevosSet: CheevosDevSet): Promise<void> {
294
+ const romPath = getCheevosRomPath(cheevosSet);
295
+ if (!romPath) return;
296
+
297
+ const type = getCheevosRomType(cheevosSet);
298
+ try {
299
+ const rom = await getStoredCheevosRom(romPath, type);
300
+ if (!rom) {
301
+ requestCheevosRomFile(romPath, type, 'Choose local ROM file');
302
+ return;
303
+ }
304
+ status.textContent = `Loading cheevos ROM: ${romPath}`;
305
+ status.style.color = '#9ecbff';
306
+ renderer.showLoader();
307
+ await player.loadFile(rom.file, rom.type);
308
+ renderer.hideLoader();
309
+ } catch (err) {
310
+ requestCheevosRomFile(
311
+ romPath,
312
+ type,
313
+ `Unable to auto-load ROM (${normalizeErrorMessage(String((err as Error)?.message ?? err))})`,
314
+ );
315
+ }
316
+ }
317
+
318
+ function requestCheevosRomFile(romPath: string, type: string | undefined, reason: string): void {
319
+ window.dispatchEvent(
320
+ new CustomEvent('c64-cheevos-rom-needed', { detail: { romPath, type, reason } }),
321
+ );
322
+ status.textContent = `${reason}: ${romPath}`;
323
+ status.style.color = '#f9c74f';
324
+ }
@@ -3,6 +3,12 @@ import { getUnsupportedCrtReason, parseCrtInfo } from '../emulator/crt-info';
3
3
  import type { GameLoadOptions } from '../types';
4
4
  import type { JoystickPort } from '../emulator/constants';
5
5
  import type { InputMode, KeyboardJoystickMap } from '../emulator/input';
6
+ import {
7
+ resolveGamepadMapping,
8
+ type GamepadMapping,
9
+ type GamepadState,
10
+ type ResolvedGamepadMapping,
11
+ } from '../emulator/gamepad-mapping';
6
12
  import type CanvasRenderer from './canvas-renderer';
7
13
  import { AudioEngine, type AudioEngineOptions } from './audio-engine';
8
14
  import InputHandler from './input-handler';
@@ -35,6 +41,8 @@ export interface C64PlayerOptions {
35
41
  export class C64Player {
36
42
  private emulator: C64Emulator | null = null;
37
43
  private inputHandler: InputHandler | null = null;
44
+ // Kept here so a mapping set before start() (or across restarts) still applies
45
+ private gamepadMapping: GamepadMapping | null = null;
38
46
  private disableCrtPreloadChecks: boolean = false;
39
47
  private destroyed: boolean = false;
40
48
  private diskSessionActive: boolean = false;
@@ -341,6 +349,29 @@ export class C64Player {
341
349
  return this.inputHandler?.getActiveGamepadIndex() ?? -1;
342
350
  }
343
351
 
352
+ /**
353
+ * Remaps the gamepad for the current game: the stick mode ('8way' | '4way' | '2way') and the
354
+ * joystick input or C64 key (C64_KEY) for each direction and for A, B, X, Y, LB, RB, LT, RT.
355
+ * Unlisted controls keep their defaults; null restores all defaults. Start stays RUN/STOP.
356
+ * Can be called before start().
357
+ */
358
+ setGamepadMapping(mapping: GamepadMapping | null): void {
359
+ this.gamepadMapping = mapping;
360
+ this.inputHandler?.setGamepadMapping(mapping);
361
+ }
362
+
363
+ getGamepadMapping(): ResolvedGamepadMapping {
364
+ return this.inputHandler?.getGamepadMapping() ?? resolveGamepadMapping(this.gamepadMapping);
365
+ }
366
+
367
+ /**
368
+ * Feeds a virtual gamepad, such as on-screen touch controls: the controls held on it go through
369
+ * the same mapping as a physical gamepad.
370
+ */
371
+ setVirtualGamepadState(state: GamepadState): void {
372
+ this.inputHandler?.setVirtualGamepadState(state);
373
+ }
374
+
344
375
  getSnapshot(): Uint8Array<ArrayBufferLike> {
345
376
  if (!this.emulator) {
346
377
  throw new Error('Emulator not initialised');
@@ -360,6 +391,10 @@ export class C64Player {
360
391
  return this.emulator?.cpuReadNS(addr) ?? 0;
361
392
  }
362
393
 
394
+ cpuWrite(addr: number, v: number): void {
395
+ this.emulator?.cpuWrite(addr, v);
396
+ }
397
+
363
398
  setVoiceEnabled(voice: number, enabled: boolean): void {
364
399
  this.emulator?.setVoiceEnabled(voice, enabled);
365
400
  }
@@ -511,6 +546,7 @@ export class C64Player {
511
546
  onFastForwardReset: () => this.resetFastForwardSpeed(),
512
547
  });
513
548
  this.inputHandler.attach();
549
+ this.inputHandler.setGamepadMapping(this.gamepadMapping);
514
550
  renderer.attachTo(emulator);
515
551
  }
516
552
 
@@ -0,0 +1,340 @@
1
+ import type { C64Player } from './c64-player';
2
+
3
+ const STORAGE_PREFIX = 'c64-cheevos-dev';
4
+
5
+ export type CheevosDevAchievement = {
6
+ _id: string;
7
+ title: string;
8
+ description?: string;
9
+ };
10
+
11
+ export type CheevosDevSet = {
12
+ _id?: string;
13
+ romPath?: string;
14
+ rom?: {
15
+ path?: string;
16
+ type?: string;
17
+ };
18
+ cheevos?: CheevosDevAchievement[];
19
+ trackerFields?: CheevosDevTrackerField[];
20
+ };
21
+
22
+ export type CheevosDevTrackerField = {
23
+ key: string;
24
+ label?: string;
25
+ source?: 'field';
26
+ field?: string;
27
+ display?: 'text' | 'bar';
28
+ max?: number;
29
+ };
30
+
31
+ export type CheevosDevScore = {
32
+ gameId: string;
33
+ score: number;
34
+ userId: string;
35
+ username: string;
36
+ variant?: string;
37
+ at: string;
38
+ };
39
+
40
+ export type CheevosDevState = {
41
+ enabled: boolean;
42
+ detectorId: string;
43
+ cheevosSet: CheevosDevSet;
44
+ };
45
+
46
+ type CheevosInstance = {
47
+ execute?: () => void;
48
+ cpuReadNS?: (addr: number) => number;
49
+ cpuRead?: (addr: number) => number;
50
+ ramRead?: (addr: number) => number;
51
+ watcher?: {
52
+ on?: (name: string, callback: (payload: unknown) => void) => void;
53
+ };
54
+ [key: string]: unknown;
55
+ };
56
+
57
+ type CheevosEventPayload = {
58
+ detectorId: string;
59
+ type: string;
60
+ payload?: unknown;
61
+ };
62
+
63
+ export class CheevosDevController {
64
+ private player: C64Player | null;
65
+ private enabled = false;
66
+ private detectorId = '';
67
+ private cheevosSet: CheevosDevSet = { cheevos: [] };
68
+ private instance: CheevosInstance | null = null;
69
+ private rafId = 0;
70
+ private lastSnapshotKey = '';
71
+
72
+ constructor(player: C64Player) {
73
+ this.player = player;
74
+ }
75
+
76
+ getState(): CheevosDevState {
77
+ return {
78
+ enabled: this.enabled,
79
+ detectorId: this.detectorId,
80
+ cheevosSet: this.cheevosSet,
81
+ };
82
+ }
83
+
84
+ async enable(detectorId: string, cheevosSet: CheevosDevSet = { cheevos: [] }): Promise<void> {
85
+ const normalisedDetectorId = detectorId.trim().toLowerCase();
86
+ if (!normalisedDetectorId) throw new Error('Cheevos detector ID is required');
87
+
88
+ this.disable();
89
+ this.detectorId = normalisedDetectorId;
90
+ this.cheevosSet = normaliseCheevosSet(cheevosSet, normalisedDetectorId);
91
+
92
+ const { createCheevos } = await import('c64-cheevos');
93
+ const poppedCheevos = this.getPoppedCheevos(normalisedDetectorId);
94
+ const cheevos = (await createCheevos(normalisedDetectorId, {
95
+ gameId: normalisedDetectorId,
96
+ user: { id: 'dev-user', username: 'Developer' },
97
+ cheevosSet: this.cheevosSet,
98
+ poppedCheevos,
99
+ postScore: this.postScore,
100
+ popCheevo: this.popCheevo,
101
+ })) as CheevosInstance;
102
+
103
+ cheevos.cpuReadNS = (addr) => this.player?.cpuReadNS(addr) ?? 0;
104
+ cheevos.cpuRead = (addr) => this.player?.cpuRead(addr) ?? 0;
105
+ cheevos.ramRead = (addr) => this.player?.ramRead(addr) ?? 0;
106
+
107
+ this.attachWatcher(cheevos);
108
+ this.instance = cheevos;
109
+ this.enabled = true;
110
+ this.dispatchStatus('enabled', {
111
+ cheevosCount: this.cheevosSet.cheevos?.length ?? 0,
112
+ cheevosSet: this.cheevosSet,
113
+ poppedCheevos,
114
+ });
115
+ this.tick();
116
+ }
117
+
118
+ async enableFromJson(detectorId: string, rawJson: string): Promise<void> {
119
+ await this.enable(detectorId, parseCheevosSetJson(rawJson));
120
+ }
121
+
122
+ disable(): void {
123
+ if (this.rafId) {
124
+ cancelAnimationFrame(this.rafId);
125
+ this.rafId = 0;
126
+ }
127
+ this.enabled = false;
128
+ this.instance = null;
129
+ this.lastSnapshotKey = '';
130
+ }
131
+
132
+ destroy(): void {
133
+ this.disable();
134
+ this.player = null;
135
+ }
136
+
137
+ clearPopped(detectorId: string = this.detectorId): void {
138
+ const id = detectorId.trim().toLowerCase();
139
+ if (!id) return;
140
+ localStorage.removeItem(getPoppedStorageKey(id));
141
+ this.dispatchStatus('popped-cleared', { poppedCheevos: [] });
142
+ }
143
+
144
+ clearScores(detectorId: string = this.detectorId): void {
145
+ const id = detectorId.trim().toLowerCase();
146
+ if (!id) return;
147
+ localStorage.removeItem(getScoresStorageKey(id));
148
+ this.dispatchStatus('scores-cleared');
149
+ }
150
+
151
+ private tick = (): void => {
152
+ if (!this.enabled) return;
153
+ try {
154
+ this.instance?.execute?.();
155
+ this.dispatchSnapshot();
156
+ } catch (err) {
157
+ this.disable();
158
+ window.dispatchEvent(
159
+ new CustomEvent('c64-cheevos-error', {
160
+ detail: { detectorId: this.detectorId, error: normaliseError(err) },
161
+ }),
162
+ );
163
+ return;
164
+ }
165
+ this.rafId = requestAnimationFrame(this.tick);
166
+ };
167
+
168
+ private readonly postScore = async (
169
+ gameId: string,
170
+ score: number,
171
+ userId: string,
172
+ username: string,
173
+ variant?: string,
174
+ ): Promise<{ ok: true }> => {
175
+ const entry: CheevosDevScore = {
176
+ gameId,
177
+ score,
178
+ userId,
179
+ username,
180
+ variant,
181
+ at: new Date().toISOString(),
182
+ };
183
+ const scores = readJson<CheevosDevScore[]>(getScoresStorageKey(this.detectorId), []);
184
+ scores.push(entry);
185
+ localStorage.setItem(getScoresStorageKey(this.detectorId), JSON.stringify(scores));
186
+ window.dispatchEvent(
187
+ new CustomEvent('c64-cheevos-score', {
188
+ detail: { detectorId: this.detectorId, score: entry },
189
+ }),
190
+ );
191
+ return { ok: true };
192
+ };
193
+
194
+ private readonly popCheevo = async (
195
+ _cheevosSetId: string,
196
+ _userId: string,
197
+ cheevoId: string,
198
+ ): Promise<{ achievement: CheevosDevAchievement }> => {
199
+ const achievement = this.findAchievement(cheevoId) ?? {
200
+ _id: cheevoId,
201
+ title: cheevoId,
202
+ description: 'Unlocked in c64-ready dev mode',
203
+ };
204
+ const popped = this.getPoppedCheevos(this.detectorId);
205
+ if (!popped.some((item) => item.achievement._id === cheevoId)) {
206
+ popped.push({ achievement });
207
+ localStorage.setItem(getPoppedStorageKey(this.detectorId), JSON.stringify(popped));
208
+ }
209
+ window.dispatchEvent(
210
+ new CustomEvent('c64-cheevos-popped', {
211
+ detail: { detectorId: this.detectorId, achievement, poppedCheevos: popped },
212
+ }),
213
+ );
214
+ return { achievement };
215
+ };
216
+
217
+ private dispatchSnapshot(): void {
218
+ const instance = this.instance;
219
+ if (!instance) return;
220
+
221
+ const fields = Object.fromEntries(
222
+ (this.cheevosSet.trackerFields ?? []).map((field) => {
223
+ const sourceField = field.field ?? field.key;
224
+ return [field.key, normaliseTrackerValue(instance[sourceField])];
225
+ }),
226
+ );
227
+ const detail = {
228
+ detectorId: this.detectorId,
229
+ score: normaliseTrackerValue(instance.score),
230
+ lives: normaliseTrackerValue(instance.lives),
231
+ isGameOver: typeof instance.isGameOver === 'boolean' ? instance.isGameOver : undefined,
232
+ fields,
233
+ };
234
+ const snapshotKey = JSON.stringify(detail);
235
+ if (snapshotKey === this.lastSnapshotKey) return;
236
+ this.lastSnapshotKey = snapshotKey;
237
+ window.dispatchEvent(new CustomEvent('c64-cheevos-snapshot', { detail }));
238
+ }
239
+
240
+ private attachWatcher(cheevos: CheevosInstance): void {
241
+ const watcher = cheevos.watcher;
242
+ if (typeof watcher?.on !== 'function') return;
243
+ for (const type of ['cheevo', 'gameOver', 'livesChange', 'newGame']) {
244
+ watcher.on(type, (payload) => {
245
+ const detail: CheevosEventPayload = { detectorId: this.detectorId, type, payload };
246
+ window.dispatchEvent(new CustomEvent('c64-cheevos-event', { detail }));
247
+ });
248
+ }
249
+ }
250
+
251
+ private findAchievement(cheevoId: string): CheevosDevAchievement | undefined {
252
+ return this.cheevosSet.cheevos?.find((achievement) => achievement._id === cheevoId);
253
+ }
254
+
255
+ private getPoppedCheevos(detectorId: string): Array<{ achievement: CheevosDevAchievement }> {
256
+ return readJson<Array<{ achievement: CheevosDevAchievement }>>(
257
+ getPoppedStorageKey(detectorId),
258
+ [],
259
+ );
260
+ }
261
+
262
+ private dispatchStatus(status: string, extra: Record<string, unknown> = {}): void {
263
+ window.dispatchEvent(
264
+ new CustomEvent('c64-cheevos-status', {
265
+ detail: { detectorId: this.detectorId, status, ...extra },
266
+ }),
267
+ );
268
+ }
269
+ }
270
+
271
+ export function parseCheevosSetJson(rawJson: string): CheevosDevSet {
272
+ const parsed = JSON.parse(rawJson) as unknown;
273
+ if (!parsed || typeof parsed !== 'object') {
274
+ throw new Error('Cheevos JSON must be an object');
275
+ }
276
+ return normaliseCheevosSet(parsed as CheevosDevSet);
277
+ }
278
+
279
+ function normaliseCheevosSet(set: CheevosDevSet, detectorId = 'dev'): CheevosDevSet {
280
+ const cheevos = Array.isArray(set.cheevos) ? set.cheevos : [];
281
+ const trackerFields = Array.isArray(set.trackerFields) ? set.trackerFields : [];
282
+ const romPath = normaliseOptionalString(set.romPath ?? set.rom?.path);
283
+ const romType = normaliseOptionalString(set.rom?.type);
284
+ return {
285
+ _id: set._id ?? `${detectorId}-dev-set`,
286
+ ...(romPath ? { romPath } : {}),
287
+ ...(romPath || romType
288
+ ? { rom: { ...(romPath ? { path: romPath } : {}), ...(romType ? { type: romType } : {}) } }
289
+ : {}),
290
+ trackerFields: trackerFields.map((field, index) => ({
291
+ key: String(field.key ?? field.field ?? `field-${index + 1}`),
292
+ label: field.label ? String(field.label) : undefined,
293
+ source: 'field',
294
+ field: field.field ? String(field.field) : undefined,
295
+ display: field.display === 'bar' ? 'bar' : 'text',
296
+ max: typeof field.max === 'number' && Number.isFinite(field.max) ? field.max : undefined,
297
+ })),
298
+ cheevos: cheevos.map((achievement, index) => ({
299
+ _id: String(achievement._id ?? `dev-${index + 1}`),
300
+ title: String(achievement.title ?? achievement._id ?? `Achievement ${index + 1}`),
301
+ description: achievement.description ? String(achievement.description) : '',
302
+ })),
303
+ };
304
+ }
305
+
306
+ function normaliseOptionalString(value: unknown): string | undefined {
307
+ if (typeof value !== 'string') return undefined;
308
+ const trimmed = value.trim();
309
+ return trimmed || undefined;
310
+ }
311
+
312
+ function readJson<T>(key: string, fallback: T): T {
313
+ try {
314
+ const raw = localStorage.getItem(key);
315
+ return raw ? (JSON.parse(raw) as T) : fallback;
316
+ } catch {
317
+ return fallback;
318
+ }
319
+ }
320
+
321
+ function getScoresStorageKey(detectorId: string): string {
322
+ return `${STORAGE_PREFIX}:${detectorId}:scores`;
323
+ }
324
+
325
+ function getPoppedStorageKey(detectorId: string): string {
326
+ return `${STORAGE_PREFIX}:${detectorId}:popped`;
327
+ }
328
+
329
+ function normaliseError(err: unknown): string {
330
+ return err instanceof Error ? err.message : String(err);
331
+ }
332
+
333
+ function normaliseTrackerValue(value: unknown): string | number | boolean | undefined {
334
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
335
+ return value;
336
+ }
337
+ return undefined;
338
+ }
339
+
340
+ export default CheevosDevController;