@wasm-gaming/rsdkv3-wasm 0.1.2 → 0.1.5

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,89 +1,82 @@
1
1
  # @wasm-gaming/rsdkv3-wasm
2
2
 
3
- RSDKv3 (Retro Software Development Kit v3, Sonic CD 2011 decompilation) compiled
4
- to WebAssembly, wrapped in a JS SDK conforming to the
5
- [wasm-gaming engine contract](https://github.com/wasm-gaming/engine-specs).
3
+ RSDKv3 (Retro Software Development Kit v3, the Sonic CD 2011 decompilation) compiled to
4
+ WebAssembly, wrapped in a self-contained SDK that implements the
5
+ [wasm-gaming engine contract](https://github.com/wasm-gaming/engine-specs) 1.0.
6
6
 
7
- The engine does not bake game data with `--preload-file`. Hosts provide
8
- `Data.rsdk` at runtime, so the same `rsdkv3.wasm` can be reused across installs.
7
+ The engine bakes no game data: the host hands over `Data.rsdk` at runtime, so one `rsdkv3.wasm`
8
+ serves any install.
9
9
 
10
- ## Contract surface
10
+ ## Install
11
11
 
12
- ```js
13
- import { manifest, load } from '@wasm-gaming/rsdkv3-wasm';
14
-
15
- const engine = await load({
16
- canvas,
17
- assets: { data: dataRsdkBytes /*, settings: iniBytes */ },
18
- onEvent: (e) => { /* 'ready' | 'error' */ },
19
- // Optional override when artifacts are hosted externally:
20
- // jsUrl, wasmUrl,
21
- });
22
-
23
- engine.pause();
24
- engine.resume();
25
- engine.setInput('rsdkv4');
26
- engine.destroy();
12
+ ```bash
13
+ npm install @wasm-gaming/rsdkv3-wasm
27
14
  ```
28
15
 
29
- - `manifest` defines required `data` (`/data/Data.rsdk`) and optional `settings`
30
- (`/data/settings.ini`) assets.
31
- - `load(config)` returns an `EngineInstance` and exposes `devMenu` bridge helpers:
32
- `getStageList()`, `loadStage(category, stage)`, `setPaused(bool)`.
16
+ The SDK carries the contract's runtime beside it (`dist/rsdkv3/engine-specs.js`) and imports it
17
+ relatively: it loads from any static server, with no bundler and no import map. The wasm and its
18
+ glue are built in CI and shipped in the GitHub Release (`rsdkv3.tar.gz`, layout `rsdkv3/rsdkv3/…`).
33
19
 
34
- ## Options
20
+ ## Use
35
21
 
36
- Engine-specific options are declared in
37
- [src/rsdkv3.options.ts](src/rsdkv3.options.ts) and mirrored into `manifest.options`:
22
+ ```js
23
+ import Rsdkv3SDK from './rsdkv3/rsdkv3.sdk.js';
24
+
25
+ const play = await new Rsdkv3SDK({ config: { soundtrack: 1 } }) // US soundtrack
26
+ .assets({ data: () => readDataRsdk() }) // bytes, or a thunk
27
+ .storage({ namespace: 'sonic-cd' }) // → OPFS rsdkv3/sonic-cd/
28
+ .on('saves', ({ detail }) => console.log('saved', detail.files))
29
+ .mount(document.querySelector('#stage'))
30
+ .start();
31
+
32
+ play.pause('menu'); play.resume('menu'); // owner-aware; sound stops too
33
+ play.devMenu.getStageList(); // draw your own stage select…
34
+ play.devMenu.loadStage(0, 2); // …and warp
35
+ await play.destroy(); // save flushed, loop stopped, audio closed
36
+ ```
38
37
 
39
- - `devMenu`
40
- - `engineDebugMode`
41
- - `vsync`
42
- - `soundtrack` (`0` JP/EU, `1` US)
43
- - `language`
44
- - `disableTouchControls`
38
+ | payload | keys |
39
+ | --- | --- |
40
+ | `config` | `devMenu`, `engineDebugMode`, `vsync`, `soundtrack` (0 JP/EU, 1 US), `language`, `disableTouchControls` (→ generated `settings.ini`), `jsUrl`, `wasmUrl` |
41
+ | `options` | — |
42
+ | `assets` | `data` (`Data.rsdk`, required), `settings` (`settings.ini`, optional) |
43
+ | `storage` | `namespace` (default `default`), `persist` (`'opfs'` \| `null`) |
45
44
 
46
- If `assets.settings` is omitted, the SDK generates `settings.ini` from these
47
- options.
45
+ Events: the contract's `start`, `error`, `exit`, `pause`, `resume`, plus `saves`.
46
+ RSDKv3 cannot restart in process: after `destroy()`, a new session needs a new page (or iframe).
48
47
 
49
- ## Build
48
+ ## Saves live in the engine's own folder
50
49
 
51
- All build logic is in [Makefile](Makefile):
50
+ The working dir is `/data/rsdkv3/<namespace>` (in memory). The SDK seeds `SData.bin` from OPFS
51
+ `rsdkv3/<namespace>/` before boot and mirrors it back when it changes — every 10 s, on pause, when
52
+ the page is hidden and on `destroy()` — so saves survive reloads. `play.storagePath` gives the
53
+ folder; `storagePath(engineId, namespace)` is exported.
54
+
55
+ ## Build
52
56
 
53
57
  ```bash
54
- make build # SDK (TypeScript) + WASM
55
- make build-sdk # SDK only
56
- make build-wasm # WASM via Docker wrapper
57
- make preview # serves dist/ at http://localhost:8080
58
+ make build-sdk # TypeScript → dist/rsdkv3/ (fast, no Docker)
59
+ make test # type-check + tests against the built package
60
+ make build-wasm # RSDKv3 → WebAssembly in emscripten/emsdk:6.0.2 (Docker)
61
+ make demo # dist/index.html: a no-build demo (pick or drop Data.rsdk)
62
+ make preview # serve dist/ on :8023
58
63
  ```
59
64
 
60
- - `scripts/build.sh` clones `Rubberduckycooly/Sonic-CD-11-Decompilation`, applies
61
- known Emscripten patches, vendors `libtheora`, and outputs:
62
- - `dist/rsdkv3/rsdkv3.js`
63
- - `dist/rsdkv3/rsdkv3.wasm`
64
- - `scripts/emit-manifest.mjs` writes `dist/manifest.json` from typed manifest.
65
- - `scripts/seed-settings.mjs` seeds `dist/settings.ini` from
66
- `src/settings.default.ini` when absent.
67
-
68
- ## Try locally
65
+ The upstream decompilation is pinned (`d1bbec59`, 2026-07-04) together with its submodules, and so
66
+ is the emsdk image, because the build's source patches are written against that exact revision.
69
67
 
70
- ```bash
71
- make build
72
- cp /path/to/Data.rsdk dist/
73
- make preview
74
- # open http://localhost:8080/
75
- ```
68
+ ## Project Specs
76
69
 
77
- The demo attempts `./Data.rsdk`; if missing, it shows a file picker and supports
78
- drag-and-drop.
70
+ - Contract 1.0 class (`Rsdkv3SDK` / `Rsdkv3Play`), self-contained ESM, engine-specs as the one
71
+ dependency; conformance line `RSDKV3_ENGINE` checked by `make test`.
72
+ - Engine-owned storage `rsdkv3/<namespace>/` with an `SData.bin` mirror.
73
+ - Records of decisions in [RECORD/](RECORD/).
79
74
 
80
- ## Status
75
+ ## Todos
81
76
 
82
- - ✅ TypeScript SDK + manifest build
83
- - ✅ CI workflow scaffold for SDK/WASM/release/pages
84
- - ⏳ Browser runtime verification with a real `Data.rsdk`
85
- - ⏳ Full WASM build verification (`make build-wasm`) on this new subproject
77
+ - [ ] Make the build's source patches assert that they applied.
78
+ - [ ] Verify with a real `Data.rsdk` (save written by the game → mirrored → restored).
86
79
 
87
80
  ## License
88
81
 
89
- MIT for this wrapper. Upstream engine and game data keep their own licenses.
82
+ MIT for this wrapper. The upstream engine and the game data keep their own licenses.
@@ -0,0 +1,382 @@
1
+ // ---- Introspectable property definitions ----
2
+ /**
3
+ * The listener bookkeeping, shipped rather than described — the one piece of runtime
4
+ * code in this package.
5
+ *
6
+ * It is a **convenience, not a requirement**: the contract stays structural, so an
7
+ * engine that already owns an emitter satisfies {@link EngineSurface} without this.
8
+ * What it saves is the part everyone gets subtly wrong — iterating a copy, so a
9
+ * listener that unsubscribes mid-emit does not corrupt the loop; de-duplicating a
10
+ * listener registered twice; and keeping one throwing listener from silencing the
11
+ * rest.
12
+ *
13
+ * Hold it **privately** and hand the same instance to every carrier. That is what
14
+ * makes `sdk.on(…)` and `play.on(…)` one channel rather than two, lets a host
15
+ * subscribe before the engine exists, and keeps `emit` out of the public API — a host
16
+ * must not be able to forge an engine event.
17
+ */
18
+ export class EventEmitter {
19
+ #listeners = new Map();
20
+ /** @param listeners Registered immediately — what `EngineInit.on` carries. */
21
+ constructor(listeners) {
22
+ for (const type of Object.keys(listeners ?? {})) {
23
+ const listener = listeners?.[type];
24
+ if (listener)
25
+ this.on(type, listener);
26
+ }
27
+ }
28
+ /** Registering the same listener twice registers it once, as `EventTarget` does. */
29
+ on(type, listener) {
30
+ let set = this.#listeners.get(type);
31
+ if (!set)
32
+ this.#listeners.set(type, (set = new Set()));
33
+ set.add(listener);
34
+ return this;
35
+ }
36
+ /**
37
+ * The listener is required, as in `EventTarget`. A convenience `off(type)` dropping
38
+ * every listener for a type is a footgun on a page where two components subscribed
39
+ * independently: one unsubscribing would silence the other.
40
+ */
41
+ off(type, listener) {
42
+ const set = this.#listeners.get(type);
43
+ if (set?.delete(listener) && set.size === 0) {
44
+ this.#listeners.delete(type);
45
+ }
46
+ return this;
47
+ }
48
+ /**
49
+ * Takes the **detail**, and wraps it. The rest tuple is what lets an event with no
50
+ * detail be emitted as `emit('exit')` while still checking the ones that have one.
51
+ */
52
+ emit(type, ...[detail]) {
53
+ const set = this.#listeners.get(type);
54
+ if (!set)
55
+ return;
56
+ // Built once and frozen: every listener gets this same object, so a mutable one
57
+ // would let the first rewrite what the rest read.
58
+ const event = Object.freeze({ type, detail: detail });
59
+ // A copy: a listener may call `off()` — on itself or another — while this runs.
60
+ for (const listener of [...set]) {
61
+ try {
62
+ listener(event);
63
+ }
64
+ catch (thrown) {
65
+ // One bad listener must neither silence the rest nor vanish. Rethrowing on a
66
+ // fresh task puts it in front of `window.onerror` with its stack intact.
67
+ queueMicrotask(() => {
68
+ throw thrown;
69
+ });
70
+ }
71
+ }
72
+ }
73
+ }
74
+ /**
75
+ * Wrap a promise of a live engine in the chainable surface.
76
+ *
77
+ * Exported because it is the single most duplicated function in an engine, and an
78
+ * engine that does not extend {@link EnginePlayBase} still needs exactly this.
79
+ *
80
+ * `on` and `off` do **not** go through the chain: they reach the channel now, so a
81
+ * listener is live before the promise settles. Routing them through it would bind
82
+ * after the session opened and lose whatever was emitted while it was opening.
83
+ */
84
+ export function hydratePlay(inner, events) {
85
+ const chain = (step) => hydratePlay(inner.then(async (play) => {
86
+ await step(play);
87
+ return play;
88
+ }), events);
89
+ const hydrated = {
90
+ then: (onfulfilled, onrejected) => inner.then(onfulfilled, onrejected),
91
+ catch: (onrejected) => inner.catch(onrejected),
92
+ finally: (onfinally) => inner.finally(onfinally),
93
+ [Symbol.toStringTag]: 'PromisePlay',
94
+ config: ((patch) => patch === undefined
95
+ ? inner.then((play) => play.config())
96
+ : chain((play) => play.config(patch))),
97
+ options: ((patch) => patch === undefined
98
+ ? inner.then((play) => play.options())
99
+ : chain((play) => play.options(patch))),
100
+ assets: ((patch) => patch === undefined
101
+ ? inner.then((play) => play.assets())
102
+ : chain((play) => play.assets(patch))),
103
+ storage: ((patch) => patch === undefined
104
+ ? inner.then((play) => play.storage())
105
+ : chain((play) => play.storage(patch))),
106
+ mount: (target) => chain((play) => play.mount(target)),
107
+ on: (type, listener) => {
108
+ events.on(type, listener);
109
+ return hydrated;
110
+ },
111
+ off: (type, listener) => {
112
+ events.off(type, listener);
113
+ return hydrated;
114
+ },
115
+ restart: (options) => chain((play) => play.restart(options)),
116
+ destroy: () => inner.then((play) => play.destroy()),
117
+ };
118
+ return hydrated;
119
+ }
120
+ /**
121
+ * The live engine, with everything the contract prescribes already written: state,
122
+ * the cumulative merge, the descriptors, the chainable promise, and the channel.
123
+ *
124
+ * A subclass supplies what only it can know — {@link EnginePlayBase.open} and
125
+ * {@link EnginePlayBase.close}, optionally {@link EnginePlayBase.mounted} and
126
+ * {@link EnginePlayBase.patched} — and its properties as an {@link EngineSpec}.
127
+ *
128
+ * The spec arrives as a **constructor argument**, not an abstract field, and that is
129
+ * not a style choice: a subclass field initialiser runs *after* `super()`, so a
130
+ * `protected abstract spec` would still be `undefined` while this constructor seeded
131
+ * state from it. Passing it up makes the ordering trap impossible rather than merely
132
+ * avoided.
133
+ */
134
+ export class EnginePlayBase {
135
+ #spec;
136
+ #state;
137
+ #events;
138
+ #target;
139
+ /** The target {@link EnginePlayBase.mounted} has already been told about. */
140
+ #attached;
141
+ /**
142
+ * @param events The factory's channel. Omitted only when a play is built on its
143
+ * own; the factory always passes its own, which is what makes `sdk.on(…)` and
144
+ * `play.on(…)` one channel rather than two.
145
+ */
146
+ constructor(spec, init, events) {
147
+ this.#spec = spec;
148
+ this.#events = events ?? new EventEmitter(init?.on);
149
+ this.#state = {
150
+ config: seed(spec.config, init?.config),
151
+ options: seed(spec.options, init?.options),
152
+ assets: seed(spec.assets, init?.assets),
153
+ storage: seed(spec.storage, init?.storage),
154
+ };
155
+ // Recorded, not applied. `mounted()` is overridable, and a subclass's own fields
156
+ // are still uninitialised while this constructor runs — so the hook is deferred to
157
+ // the first `restart()`, by which point the subclass is whole.
158
+ this.#target = init?.mount;
159
+ }
160
+ /** The element is already recorded when this runs. */
161
+ mounted(target) {
162
+ void target;
163
+ }
164
+ /** A payload changed on a running engine — apply what is `live`, ignore the rest. */
165
+ patched(kind, patch) {
166
+ void kind;
167
+ void patch;
168
+ }
169
+ /**
170
+ * Emit one of this engine's own events.
171
+ *
172
+ * `protected`, so a typed host cannot forge an engine event — but be exact about
173
+ * what that buys: TypeScript erases `protected`, so this is a compile-time guard,
174
+ * not a capability boundary. Plain JavaScript can still reach it. Only the `#`
175
+ * fields below — the channel and the state — are unreachable at runtime.
176
+ */
177
+ emit(type, ...detail) {
178
+ this.#events.emit(type, ...detail);
179
+ }
180
+ /** Where the picture is, for a subclass that needs the element after `mounted()`. */
181
+ get target() {
182
+ return this.#target;
183
+ }
184
+ config(patch) {
185
+ // `arguments.length`, not `patch === undefined`: `config(undefined)` is a write of
186
+ // nothing, not a read.
187
+ if (arguments.length === 0)
188
+ return Promise.resolve(this.#describe('config'));
189
+ return this.#patch('config', patch);
190
+ }
191
+ options(patch) {
192
+ if (arguments.length === 0)
193
+ return Promise.resolve(this.#describe('options'));
194
+ return this.#patch('options', patch);
195
+ }
196
+ assets(patch) {
197
+ if (arguments.length === 0)
198
+ return Promise.resolve(this.#describe('assets'));
199
+ return this.#patch('assets', patch);
200
+ }
201
+ storage(patch) {
202
+ if (arguments.length === 0)
203
+ return Promise.resolve(this.#describe('storage'));
204
+ return this.#patch('storage', patch);
205
+ }
206
+ mount(target) {
207
+ this.#target = target;
208
+ return this.#run(() => this.#attach());
209
+ }
210
+ on(type, listener) {
211
+ this.#events.on(type, listener);
212
+ return hydratePlay(Promise.resolve(this), this.#events);
213
+ }
214
+ off(type, listener) {
215
+ this.#events.off(type, listener);
216
+ return hydratePlay(Promise.resolve(this), this.#events);
217
+ }
218
+ restart(options) {
219
+ return this.#run(async () => {
220
+ if (options)
221
+ Object.assign(this.#state.options, options);
222
+ // A target supplied to the constructor lands here, which is what makes
223
+ // `new Sdk({ mount: el }).start()` and `new Sdk().mount(el).start()` the same
224
+ // call — the rule the contract states for everything on the surface.
225
+ await this.#attach();
226
+ const opened = { ...this.#state.options };
227
+ await this.open(opened);
228
+ this.#emitCore('start', opened);
229
+ });
230
+ }
231
+ async destroy() {
232
+ await this.#guard(async () => {
233
+ await this.close();
234
+ this.#target = undefined;
235
+ this.#attached = undefined;
236
+ this.#emitCore('exit', undefined);
237
+ });
238
+ }
239
+ /** Tell the engine where it is, once per distinct target. Reparenting is legal. */
240
+ async #attach() {
241
+ if (!this.#target || this.#target === this.#attached)
242
+ return;
243
+ this.#attached = this.#target;
244
+ await this.mounted(this.#target);
245
+ }
246
+ // ---- Shared machinery ----
247
+ /** One getter's answer: the spec, with the current value written into each entry. */
248
+ #describe(kind) {
249
+ const spec = this.#spec[kind];
250
+ const state = this.#state[kind];
251
+ const out = {};
252
+ for (const key of Object.keys(spec)) {
253
+ out[key] = { ...spec[key], value: state[key] };
254
+ }
255
+ return out;
256
+ }
257
+ /** Cumulative, merged flat, one level — `undefined` is a value, not "leave alone". */
258
+ #patch(kind, patch) {
259
+ Object.assign(this.#state[kind], patch);
260
+ return this.#run(async () => {
261
+ await this.patched(kind, patch ?? {});
262
+ });
263
+ }
264
+ /** A step, as a link in the chain — and as an `error` event if it throws. */
265
+ #run(step) {
266
+ return hydratePlay(this.#guard(step), this.#events);
267
+ }
268
+ /**
269
+ * The rule that errors reach a host **both ways**: the promise rejects *and*
270
+ * `error` is emitted. Written once here rather than at every throw site.
271
+ */
272
+ async #guard(step) {
273
+ try {
274
+ await step();
275
+ return this;
276
+ }
277
+ catch (thrown) {
278
+ const error = thrown instanceof Error ? thrown : new Error(String(thrown));
279
+ this.#emitCore('error', error);
280
+ throw error;
281
+ }
282
+ }
283
+ /**
284
+ * The core events, emitted from here rather than by a subclass.
285
+ *
286
+ * The cast is the one thing TypeScript will not check here: `emit` takes a rest
287
+ * tuple that is conditional on the detail type, and that conditional stays
288
+ * unresolved while `P` is still a type parameter. It is sound — `EventsOf<P>`
289
+ * always contains `CoreEvents<P>` by construction — and confining it to this one
290
+ * method is why the three call sites above read plainly.
291
+ */
292
+ #emitCore(type, detail) {
293
+ // Cast the channel, not the method: pulling `emit` out into a variable would call
294
+ // it unbound, and it reads its listeners off `this`.
295
+ const events = this.#events;
296
+ events.emit(type, detail);
297
+ }
298
+ }
299
+ /** Starting state: every `default` the spec declares, then whatever `init` overrides. */
300
+ function seed(spec, patch) {
301
+ const state = {};
302
+ for (const [key, property] of Object.entries(spec)) {
303
+ if (property.default !== undefined)
304
+ state[key] = property.default;
305
+ }
306
+ return Object.assign(state, patch);
307
+ }
308
+ /**
309
+ * The factory, with everything the contract prescribes already written: the
310
+ * cumulative init, the synchronous chain, the channel that outlives every session,
311
+ * and one live engine per factory.
312
+ *
313
+ * A subclass supplies its static identity and {@link EngineSDKBase.createPlay}.
314
+ */
315
+ export class EngineSDKBase {
316
+ #init;
317
+ #play;
318
+ /**
319
+ * Created before any engine exists and handed to every carrier downstream. That is
320
+ * what lets a host subscribe to an error thrown while the first session opens.
321
+ */
322
+ events;
323
+ constructor(init) {
324
+ this.#init = { ...init };
325
+ this.events = new EventEmitter(init?.on);
326
+ }
327
+ config(patch) {
328
+ if (arguments.length === 0)
329
+ return this.#pending().config();
330
+ return this.#patch('config', patch);
331
+ }
332
+ options(patch) {
333
+ if (arguments.length === 0)
334
+ return this.#pending().options();
335
+ return this.#patch('options', patch);
336
+ }
337
+ assets(patch) {
338
+ if (arguments.length === 0)
339
+ return this.#pending().assets();
340
+ return this.#patch('assets', patch);
341
+ }
342
+ storage(patch) {
343
+ if (arguments.length === 0)
344
+ return this.#pending().storage();
345
+ return this.#patch('storage', patch);
346
+ }
347
+ /** Recorded now, applied when the engine exists — same call as `new Sdk({ mount })`. */
348
+ mount(target) {
349
+ this.#init.mount = target;
350
+ this.#play?.mount(target);
351
+ return this;
352
+ }
353
+ on(type, listener) {
354
+ this.events.on(type, listener);
355
+ return this;
356
+ }
357
+ off(type, listener) {
358
+ this.events.off(type, listener);
359
+ return this;
360
+ }
361
+ /**
362
+ * The only way in. On a live engine it reopens the session rather than building a
363
+ * second one: a factory governs at most one engine.
364
+ */
365
+ start(options) {
366
+ this.#play ??= this.createPlay(this.#init, this.events);
367
+ return this.#play.restart(options);
368
+ }
369
+ /** Answers a read before there is an engine: the settings the next one will use. */
370
+ #pending() {
371
+ return this.#play ?? this.createPlay(this.#init, this.events);
372
+ }
373
+ #patch(kind, patch) {
374
+ this.#init[kind] = { ...this.#init[kind], ...patch };
375
+ // A live engine gets it too, so the factory does not silently describe a state
376
+ // the engine is not in.
377
+ if (this.#play && patch)
378
+ this.#play[kind](patch);
379
+ return this;
380
+ }
381
+ }
382
+ //# sourceMappingURL=engine-specs.js.map