@grimmdev/retrokit 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,2 +1,235 @@
1
1
  # RetroKit
2
- headless retroarch library for web
2
+
3
+ [![CI](https://github.com/Jellyfin-PG/RetroKit/actions/workflows/ci.yml/badge.svg)](https://github.com/Jellyfin-PG/RetroKit/actions/workflows/ci.yml)
4
+ [![Publish](https://github.com/Jellyfin-PG/RetroKit/actions/workflows/publish.yml/badge.svg)](https://github.com/Jellyfin-PG/RetroKit/actions/workflows/publish.yml)
5
+ [![npm version](https://img.shields.io/npm/v/@grimmdev/retrokit.svg)](https://www.npmjs.com/package/@grimmdev/retrokit)
6
+ [![npm downloads](https://img.shields.io/npm/dm/@grimmdev/retrokit.svg)](https://www.npmjs.com/package/@grimmdev/retrokit)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
8
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.7-blue.svg)](https://www.typescriptlang.org/)
9
+
10
+ Unified, headless WebAssembly emulation runtime for modern web applications. RetroKit provides an engine-agnostic API over Libretro, EmulatorJS, Play! (PS2), Lexaloffle PICO-8, LOVE (love.js), and Adobe Flash (Ruffle) without forcing any predefined UI or DOM styling.
11
+
12
+ ## Features
13
+
14
+ - Headless Architecture: Complete separation of emulation backend from user interface. Bind to any HTML5 Canvas and inject virtual input programmatically or listen to physical controllers.
15
+ - Multi-Engine Core Adapters:
16
+ - Libretro: Direct Emscripten WebAssembly libretro core bridge.
17
+ - EmulatorJS: Bundled 7z core decompression with multi-threading, WebGL2 context configuration, and runtime hooks.
18
+ - Play! (Purei): PlayStation 2 WebAssembly architecture with disc swapping and dual analog sticks.
19
+ - PICO-8: Native Lexaloffle web runtime integration with support for both `.p8.png` cartridges and `.p8` text carts.
20
+ - LOVE (love.js): Full LOVE 11.5 WebAssembly runtime with filesystem normalization and synchronous Lua-to-JavaScript bridging.
21
+ - Ruffle: Adobe Flash runtime integration with ActionScript 1/2/3 vector rendering.
22
+ - State and SRAM Persistence: Complete save state slot capturing and battery SRAM synchronization with export and import functionality.
23
+ - Input Channel Virtualization: Standard RetroPad mapping supporting physical Gamepad API, physical keyboard listeners, and programmatic button or analog stick injection for on-screen touch overlays.
24
+ - RetroAchievements: Full rcheevos protocol client with login, session token caching, unlock overlays, progress tracking, and hardcore mode enforcement.
25
+ - Video and Audio Management: Dynamic aspect ratio correction, integer scaling, fullscreen mode, Web Audio volume gain nodes, and mute control.
26
+
27
+ ## Supported Platforms
28
+
29
+ | System | Primary Core / Adapter | Engine Family | File Formats |
30
+ | :--- | :--- | :--- | :--- |
31
+ | Sony PlayStation (PSX) | `pcsx_rearmed`, `mednafen_psx_hw`, `beetle_psx` | EmulatorJS / Libretro | `.iso`, `.bin`, `.cue`, `.chd`, `.pbp` |
32
+ | Sony PlayStation 2 (PS2) | `play` | Play! | `.iso`, `.bin`, `.chd`, `.cso`, `.isz` |
33
+ | Sony PlayStation Portable (PSP) | `ppsspp` | EmulatorJS | `.iso`, `.cso`, `.pbp` |
34
+ | Nintendo 3DS | `azahar` | EmulatorJS | `.3ds`, `.3dsx`, `.cia`, `.cxi` |
35
+ | Nintendo DS | `melonds`, `desmume`, `desmume2015` | EmulatorJS | `.nds`, `.bin` |
36
+ | Nintendo 64 | `mupen64plus_next`, `parallel_n64` | EmulatorJS / Libretro | `.n64`, `.z64`, `.v64` |
37
+ | Super Nintendo (SNES) | `snes9x`, `bsnes` | Libretro / EmulatorJS | `.sfc`, `.smc` |
38
+ | Nintendo Entertainment System (NES) | `fceumm`, `nestopia` | Libretro / EmulatorJS | `.nes`, `.fds`, `.unf` |
39
+ | Game Boy / Game Boy Color | `gambatte`, `gearboy` | Libretro / EmulatorJS | `.gb`, `.gbc` |
40
+ | Game Boy Advance | `mgba`, `vba_next` | Libretro / EmulatorJS | `.gba` |
41
+ | Sega Saturn | `yabause` | EmulatorJS | `.iso`, `.cue`, `.bin`, `.chd`, `.m3u` |
42
+ | Sega Genesis / Mega Drive / 32X / CD | `genesis_plus_gx`, `picodrive` | Libretro / EmulatorJS | `.md`, `.gen`, `.smd`, `.32x`, `.iso`, `.chd` |
43
+ | Sega Master System / Game Gear | `smsplus`, `gearsystem` | Libretro / EmulatorJS | `.sms`, `.gg` |
44
+ | MS-DOS | `dosbox_pure` | EmulatorJS | `.exe`, `.com`, `.bat`, `.dos`, `.zip`, `.iso` |
45
+ | 3DO Interactive Multiplayer | `opera` | EmulatorJS | `.iso`, `.chd`, `.cue` |
46
+ | Atari Jaguar | `virtualjaguar` | EmulatorJS | `.jag`, `.j64`, `.rom`, `.bin` |
47
+ | Atari 2600 / 5200 / 7800 / Lynx | `stella2014`, `a5200`, `prosystem`, `handy` | EmulatorJS / Libretro | `.a26`, `.a52`, `.a78`, `.lnx` |
48
+ | Commodore 64 / 128 / Amiga | `vice_x64sc`, `puae` | EmulatorJS | `.d64`, `.t64`, `.tap`, `.adf`, `.lha` |
49
+ | Arcade / Capcom CPS-1 / CPS-2 | `fbneo`, `mame2003_plus` | EmulatorJS / Libretro | `.zip`, `.7z` |
50
+ | PICO-8 | `pico8` | Lexaloffle Official | `.p8`, `.p8.png` |
51
+ | LOVE (Love2D) | `love` | 2dengine love.js 11.5 | `.love`, `.zip` |
52
+ | Adobe Flash | `ruffle` | Ruffle | `.swf` |
53
+
54
+ ## Installation
55
+
56
+ ```bash
57
+ npm install @grimmdev/retrokit
58
+ ```
59
+
60
+ Or via GitHub Packages:
61
+
62
+ ```bash
63
+ npm install @jellyfin-pg/retrokit --registry=https://npm.pkg.github.com
64
+ ```
65
+
66
+ ## Quick Start
67
+
68
+ ```typescript
69
+ import { RetroKit } from '@grimmdev/retrokit';
70
+
71
+ const canvas = document.getElementById('game-canvas') as HTMLCanvasElement;
72
+
73
+ const emu = new RetroKit({
74
+ canvas,
75
+ assetBaseUrl: '/cores',
76
+ onLog: (message, level) => console.log(`[${level}] ${message}`),
77
+ onError: (err) => console.error('Emulator error:', err),
78
+ });
79
+
80
+ // Load a ROM file (accepts ArrayBuffer, Blob, File, or URL)
81
+ const response = await fetch('/roms/game.gba');
82
+ const romBuffer = await response.arrayBuffer();
83
+
84
+ await emu.load(romBuffer, {
85
+ fileName: 'game.gba',
86
+ system: 'gba', // Optional hint; auto-resolved if omitted
87
+ });
88
+
89
+ // Start playback
90
+ await emu.play();
91
+ ```
92
+
93
+ ## Canvas Integration and Existing WebGL Canvases
94
+
95
+ RetroKit can create its own canvas handling or bind directly to an existing canvas element (such as an existing WebGL canvas, a Three.js scene, or a React, Vue, or Svelte ref).
96
+
97
+ To reuse an existing canvas and prevent RetroKit from replacing the DOM node when switching cores or rebooting, set `preserveCanvas: true` or `useExistingCanvas: true`:
98
+
99
+ ```typescript
100
+ // Initialize with an existing canvas
101
+ const emu = new RetroKit({
102
+ canvas: existingCanvas,
103
+ preserveCanvas: true, // or useExistingCanvas: true
104
+ });
105
+
106
+ // Canvas is also optional at startup and can be bound later
107
+ emu.setCanvas(existingCanvas, { useExistingCanvas: true });
108
+
109
+ // Or specify per game during load
110
+ await emu.load(romBuffer, {
111
+ fileName: 'game.gba',
112
+ canvas: existingCanvas,
113
+ preserveCanvas: true,
114
+ });
115
+ ```
116
+
117
+ ## Input System
118
+
119
+ RetroKit is completely headless and provides two input channels that work simultaneously:
120
+
121
+ ### 1. Programmatic Input Injection (Virtual / On-Screen Controls)
122
+
123
+ Ideal for mobile touch controls, custom d-pads, netplay relays, or automated test harnesses:
124
+
125
+ ```typescript
126
+ // Digital button presses (Player 0 to N)
127
+ emu.input.player(0).sendButton('ACTION_DOWN', true); // Press A / Cross
128
+ emu.input.player(0).sendButton('ACTION_DOWN', false); // Release
129
+ emu.input.player(0).sendButton('DPAD_UP', true);
130
+ emu.input.player(0).sendButton('START', true);
131
+
132
+ // Analog dual-stick injection (-1.0 to 1.0)
133
+ emu.input.player(0).sendAnalogStick('LEFT', -0.75, 0.25);
134
+ emu.input.player(0).sendAxis('L_STICK_X', 0.8);
135
+
136
+ // Turbo button firing (pulses button state automatically)
137
+ emu.input.player(0).setTurbo('ACTION_RIGHT', true, 60); // 60ms interval
138
+ ```
139
+
140
+ ### 2. Physical Hardware Listeners
141
+
142
+ RetroKit monitors connected physical gamepads via the Gamepad API and maps standard keyboard keys to RetroPad buttons. You can remap buttons per player:
143
+
144
+ ```typescript
145
+ // Remap physical keyboard key for Player 1
146
+ emu.input.player(0).setKeyBinding('KeyZ', 'ACTION_DOWN');
147
+
148
+ // Remap physical gamepad button index
149
+ emu.input.player(0).setGamepadBinding(0, 'ACTION_DOWN');
150
+ ```
151
+
152
+ ## Save States and Battery SRAM
153
+
154
+ ```typescript
155
+ // Save and load state slots
156
+ if (emu.capabilities.saveStates) {
157
+ const record = await emu.state.saveState(0);
158
+ await emu.state.loadState(0);
159
+ }
160
+
161
+ // Battery SRAM export and import
162
+ if (emu.capabilities.sram) {
163
+ await emu.sram.flushSram();
164
+ const sramData = await emu.sram.getSram(); // Uint8Array or Record<string, Uint8Array>
165
+
166
+ // Restore SRAM from local file
167
+ await emu.sram.setSram(savedBuffer, { restart: true });
168
+ }
169
+ ```
170
+
171
+ ## RetroAchievements
172
+
173
+ RetroKit includes built-in RetroAchievements integration using the official rcheevos protocol:
174
+
175
+ ```typescript
176
+ // Log in
177
+ await emu.achievements.login('username', 'password_or_token');
178
+
179
+ // Hardcore mode (disables save states, cheats, and rewind)
180
+ emu.achievements.setHardcore(true);
181
+
182
+ // Listen to achievements events
183
+ emu.on('achievementUnlocked', (cheevo) => {
184
+ console.log(`Unlocked: ${cheevo.title} (${cheevo.points} points)`);
185
+ });
186
+ ```
187
+
188
+ ## Cores Directory Configuration
189
+
190
+ Frontends can configure or dynamically switch the base URL or folder path where emulator core WebAssembly binaries and runtime assets are hosted:
191
+
192
+ ```typescript
193
+ // Configure cores directory at runtime
194
+ emu.setCoresDirectory('https://cdn.example.com/cores');
195
+
196
+ // Or read current active directory
197
+ console.log('Active cores directory:', emu.coresDirectory);
198
+ ```
199
+
200
+ You can also pass `coresDirectory` per game in `load()` options:
201
+
202
+ ```typescript
203
+ await emu.load(romBuffer, {
204
+ fileName: 'game.gba',
205
+ coresDirectory: '/my-custom-cores',
206
+ });
207
+ ```
208
+
209
+ ## Complete API Documentation
210
+
211
+ For exhaustive documentation of all 14 subsystem managers, method signatures, parameters, return types, events, and configuration options, see the [Frontend API Reference](API.md).
212
+
213
+ ## Development and Build
214
+
215
+ ```bash
216
+ # Install dependencies
217
+ npm install
218
+
219
+ # Start local testbed development server
220
+ npm run dev
221
+
222
+ # Run typecheck and linting
223
+ npm run typecheck
224
+ npm run lint
225
+
226
+ # Build library bundles and TypeScript declarations
227
+ npm run build
228
+
229
+ # Run automated smoke test suite
230
+ npm test
231
+ ```
232
+
233
+ ## License
234
+
235
+ MIT License. See [LICENSE](LICENSE) for details.
package/dist/index.d.ts CHANGED
@@ -122,6 +122,8 @@ export declare abstract class BaseCoreBridge implements ICoreAdapter {
122
122
  protected isRunningInternal: boolean;
123
123
  protected isPausedInternal: boolean;
124
124
  init(context: AdapterContext): Promise<void>;
125
+ setCoresDirectory(directory: string): void;
126
+ setCanvas(canvas: HTMLCanvasElement): void;
125
127
  abstract loadGame(rom: ArrayBuffer | Blob | string | Uint8Array, options?: GameLoadOptions): Promise<void>;
126
128
  start(): void;
127
129
  pause(): void;
@@ -545,6 +547,16 @@ export declare interface GameLoadOptions {
545
547
  name: string;
546
548
  data: Uint8Array;
547
549
  }>;
550
+ /** Base URL or directory path for loading core WASM/JS binaries and data assets. Overrides RetroKitConfig. */
551
+ coresDirectory?: string;
552
+ /** Alias for coresDirectory. */
553
+ assetBaseUrl?: string;
554
+ /** Target canvas element to render into. Overrides or sets canvas for this game. */
555
+ canvas?: HTMLCanvasElement;
556
+ /** When true, preserves and reuses the existing canvas without DOM node replacement. */
557
+ preserveCanvas?: boolean;
558
+ /** Alias for preserveCanvas. */
559
+ useExistingCanvas?: boolean;
548
560
  }
549
561
 
550
562
  export declare interface GamepadDetails {
@@ -615,6 +627,8 @@ export declare interface ICoreAdapter {
615
627
  readonly name: string;
616
628
  readonly system: string;
617
629
  readonly capabilities: CoreCapabilities;
630
+ setCoresDirectory?(directory: string): void;
631
+ setCanvas?(canvas: HTMLCanvasElement): void;
618
632
  init(context: AdapterContext): Promise<void>;
619
633
  loadGame(rom: ArrayBuffer | Blob | string | Uint8Array, options?: GameLoadOptions): Promise<void>;
620
634
  start(): void;
@@ -1060,6 +1074,50 @@ export declare class RetroKit extends EventEmitter<EmuEventMap> {
1060
1074
  play(): Promise<void>;
1061
1075
  pause(): void;
1062
1076
  stop(): Promise<void>;
1077
+ /**
1078
+ * Sets the base directory or URL where emulator core binaries and runtime assets are located.
1079
+ * Updates internal configuration and the active adapter context.
1080
+ *
1081
+ * @param directory Base URL or directory path (e.g. '/cores', 'https://cdn.example.com/cores')
1082
+ */
1083
+ setCoresDirectory(directory: string): void;
1084
+ /**
1085
+ * Alias for setCoresDirectory.
1086
+ *
1087
+ * @param url Base URL or directory path
1088
+ */
1089
+ setAssetBaseUrl(url: string): void;
1090
+ /**
1091
+ * Returns the currently configured cores directory or asset base URL.
1092
+ */
1093
+ getCoresDirectory(): string;
1094
+ /**
1095
+ * Returns the currently configured cores directory or asset base URL.
1096
+ */
1097
+ get coresDirectory(): string;
1098
+ /**
1099
+ * Alias for getCoresDirectory.
1100
+ */
1101
+ getAssetBaseUrl(): string;
1102
+ /**
1103
+ * Alias for coresDirectory.
1104
+ */
1105
+ get assetBaseUrl(): string;
1106
+ /**
1107
+ * Binds or updates the rendering canvas element.
1108
+ *
1109
+ * @param canvas The target HTML5 Canvas element (can be an existing WebGL canvas).
1110
+ * @param options.preserveCanvas When true, reuses this canvas without replacing its DOM node.
1111
+ * @param options.useExistingCanvas Alias for preserveCanvas.
1112
+ */
1113
+ setCanvas(canvas: HTMLCanvasElement, options?: {
1114
+ preserveCanvas?: boolean;
1115
+ useExistingCanvas?: boolean;
1116
+ }): void;
1117
+ /**
1118
+ * Returns the currently bound canvas element, if any.
1119
+ */
1120
+ get canvas(): HTMLCanvasElement | undefined;
1063
1121
  /**
1064
1122
  * Updates the active target platform hint for subsequent game launches.
1065
1123
  */
@@ -1084,6 +1142,8 @@ export declare class RetroKit extends EventEmitter<EmuEventMap> {
1084
1142
  /**
1085
1143
  * Replaces the canvas DOM element with a clean canvas surface to prevent
1086
1144
  * WebGL, WebGL2, or 2D context collisions when switching emulator cores.
1145
+ * If preserveCanvas or useExistingCanvas is enabled, preserves the existing
1146
+ * canvas element and clears its frame buffer instead of replacing the DOM node.
1087
1147
  */
1088
1148
  private _resetCanvas;
1089
1149
  private _createAdapter;
@@ -1093,8 +1153,16 @@ export declare class RetroKit extends EventEmitter<EmuEventMap> {
1093
1153
  * Initialization configuration for RetroKit.
1094
1154
  */
1095
1155
  export declare interface RetroKitConfig {
1096
- /** Target canvas element for rendering. */
1097
- canvas: HTMLCanvasElement;
1156
+ /** Target canvas element for rendering. Optional if provided during load() or setCanvas(). */
1157
+ canvas?: HTMLCanvasElement;
1158
+ /**
1159
+ * When true, preserves and reuses the existing canvas element instead of replacing
1160
+ * the DOM node when switching cores or resetting. Ideal for frameworks (React/Vue/Svelte)
1161
+ * or when using a pre-created WebGL canvas.
1162
+ */
1163
+ preserveCanvas?: boolean;
1164
+ /** Alias for preserveCanvas. */
1165
+ useExistingCanvas?: boolean;
1098
1166
  /** Core ID or 'auto' to detect by ROM file extension. */
1099
1167
  core?: string;
1100
1168
  /** Target platform/system identifier (e.g. 'ps1', 'psx', 'ps2', 'snes', 'genesis'). */