@gameslate/sdk 0.3.20 → 0.3.22

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.
@@ -401,8 +401,8 @@ export declare const VerifySpecSchema: z.ZodObject<{
401
401
  core: z.ZodString;
402
402
  rom: z.ZodString;
403
403
  stateSlot: z.ZodNumber;
404
- /** run RetroArch through this (`["node", "<gameslate>/dist/gameslate.mjs", "run", "--"]`)
405
- * where only a game's parent may read its memory (ptrace_scope 1, ChimeraOS) */
404
+ /** run RetroArch through this; by default GameSlate's launch wrapper (`gameslate`
405
+ * `run --`), since GameSlate reads only games launched through it */
406
406
  launchPrefix: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
407
407
  /** a config appended to RetroArch's, which must turn network commands on */
408
408
  config: z.ZodOptional<z.ZodString>;
@@ -427,7 +427,7 @@ export declare const VerifySpecSchema: z.ZodObject<{
427
427
  /** any emulator, started with this command (the ROM on its command line, so the core finds it) */
428
428
  emulator: z.ZodOptional<z.ZodObject<{
429
429
  command: z.ZodArray<z.ZodString, "many">;
430
- /** as for RetroArch: through GameSlate's launch wrapper where only a parent may read */
430
+ /** as for RetroArch: by default through GameSlate's launch wrapper */
431
431
  launchPrefix: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
432
432
  }, "strip", z.ZodTypeAny, {
433
433
  launchPrefix: string[];
@@ -1015,6 +1015,12 @@ export declare const VerifySpecSchema: z.ZodObject<{
1015
1015
  } | {
1016
1016
  waitMs: number;
1017
1017
  })[];
1018
+ memory: {
1019
+ counter: string;
1020
+ size: 2 | 1 | 4;
1021
+ address: number;
1022
+ signed: boolean;
1023
+ }[];
1018
1024
  timeoutMs: number;
1019
1025
  game: string;
1020
1026
  daemon: {
@@ -1039,12 +1045,7 @@ export declare const VerifySpecSchema: z.ZodObject<{
1039
1045
  variant?: string | undefined;
1040
1046
  equipped?: string | null | undefined;
1041
1047
  };
1042
- memory: {
1043
- counter: string;
1044
- size: 2 | 1 | 4;
1045
- address: number;
1046
- signed: boolean;
1047
- }[];
1048
+ gameslate?: string | undefined;
1048
1049
  retroarch?: {
1049
1050
  binary: string;
1050
1051
  core: string;
@@ -1058,7 +1059,6 @@ export declare const VerifySpecSchema: z.ZodObject<{
1058
1059
  launchPrefix: string[];
1059
1060
  command: string[];
1060
1061
  } | undefined;
1061
- gameslate?: string | undefined;
1062
1062
  ui?: {
1063
1063
  url: string;
1064
1064
  tabs: ("Map" | "Inventory" | "Missions" | "Ref")[];
@@ -1149,6 +1149,13 @@ export declare const VerifySpecSchema: z.ZodObject<{
1149
1149
  } | {
1150
1150
  waitMs: number;
1151
1151
  })[] | undefined;
1152
+ memory?: {
1153
+ counter: string;
1154
+ size: 2 | 1 | 4;
1155
+ address: string;
1156
+ signed?: boolean | undefined;
1157
+ }[] | undefined;
1158
+ gameslate?: string | undefined;
1152
1159
  timeoutMs?: number | undefined;
1153
1160
  retroarch?: {
1154
1161
  binary: string;
@@ -1163,7 +1170,6 @@ export declare const VerifySpecSchema: z.ZodObject<{
1163
1170
  command: string[];
1164
1171
  launchPrefix?: string[] | undefined;
1165
1172
  } | undefined;
1166
- gameslate?: string | undefined;
1167
1173
  daemon?: {
1168
1174
  url?: string | undefined;
1169
1175
  } | undefined;
@@ -1172,15 +1178,15 @@ export declare const VerifySpecSchema: z.ZodObject<{
1172
1178
  tabs?: string[] | undefined;
1173
1179
  } | undefined;
1174
1180
  settleMs?: number | undefined;
1175
- memory?: {
1176
- counter: string;
1177
- size: 2 | 1 | 4;
1178
- address: string;
1179
- signed?: boolean | undefined;
1180
- }[] | undefined;
1181
1181
  }>;
1182
1182
  export type VerifySpec = z.infer<typeof VerifySpecSchema>;
1183
1183
  type MemoryCheck = VerifySpec['memory'][number];
1184
+ /**
1185
+ * What the emulator is started through: the spec's own prefix, else GameSlate's launch wrapper
1186
+ * (`node <gameslate> run --`). GameSlate reads memory only from games launched through it
1187
+ * ("Closing the sandbox" item 4), so an emulator started bare would never be read.
1188
+ */
1189
+ export declare function launchPrefixFor(launchPrefix: readonly string[], gameslate: string | undefined, nodePath: string): string[];
1184
1190
  /**
1185
1191
  * `${NAME}` in any string of a spec, from the environment, so a spec can be shared without one
1186
1192
  * machine's paths (`"${GOPHER64}"`, `"${N64_ROMS}/Mario Kart 64 (U).z64"`). Throws on a name that
@@ -79,8 +79,8 @@ export const VerifySpecSchema = z.object({
79
79
  core: z.string(),
80
80
  rom: z.string(),
81
81
  stateSlot: z.number().int().min(0).max(999),
82
- /** run RetroArch through this (`["node", "<gameslate>/dist/gameslate.mjs", "run", "--"]`)
83
- * where only a game's parent may read its memory (ptrace_scope 1, ChimeraOS) */
82
+ /** run RetroArch through this; by default GameSlate's launch wrapper (`gameslate`
83
+ * `run --`), since GameSlate reads only games launched through it */
84
84
  launchPrefix: z.array(z.string()).default([]),
85
85
  /** a config appended to RetroArch's, which must turn network commands on */
86
86
  config: z.string().optional(),
@@ -91,7 +91,7 @@ export const VerifySpecSchema = z.object({
91
91
  emulator: z
92
92
  .object({
93
93
  command: z.array(z.string()).min(1),
94
- /** as for RetroArch: through GameSlate's launch wrapper where only a parent may read */
94
+ /** as for RetroArch: by default through GameSlate's launch wrapper */
95
95
  launchPrefix: z.array(z.string()).default([]),
96
96
  })
97
97
  .optional(),
@@ -126,6 +126,19 @@ export const VerifySpecSchema = z.object({
126
126
  }))
127
127
  .default([]),
128
128
  });
129
+ /**
130
+ * What the emulator is started through: the spec's own prefix, else GameSlate's launch wrapper
131
+ * (`node <gameslate> run --`). GameSlate reads memory only from games launched through it
132
+ * ("Closing the sandbox" item 4), so an emulator started bare would never be read.
133
+ */
134
+ export function launchPrefixFor(launchPrefix, gameslate, nodePath) {
135
+ if (launchPrefix.length > 0)
136
+ return [...launchPrefix];
137
+ if (gameslate === undefined) {
138
+ throw new Error('GameSlate reads only games launched through it: give "gameslate" (its dist/gameslate.mjs) or a "launchPrefix"');
139
+ }
140
+ return [nodePath, gameslate, 'run', '--'];
141
+ }
129
142
  /**
130
143
  * `${NAME}` in any string of a spec, from the environment, so a spec can be shared without one
131
144
  * machine's paths (`"${GOPHER64}"`, `"${N64_ROMS}/Mario Kart 64 (U).z64"`). Throws on a name that
@@ -0,0 +1,51 @@
1
+ export declare const WASM_PAGE_BYTES: number;
2
+ /** the module the sandbox's capabilities are imported from */
3
+ export declare const WASM_HOST_MODULE = "gameslate";
4
+ /** the largest module a plugin may bundle */
5
+ export declare const WASM_MAX_MODULE_BYTES: number;
6
+ export interface WasmFile {
7
+ file: string;
8
+ bytes: Uint8Array<ArrayBuffer>;
9
+ }
10
+ /** A sandbox's capabilities as functions a module imports from `gameslate`, given a view of
11
+ * the module's memory as it is now (memory.grow replaces the buffer). */
12
+ export type WasmHostFunctions = (memory: () => Uint8Array) => Record<string, WebAssembly.ImportValue>;
13
+ export interface WasmSetup {
14
+ modules: readonly WasmFile[];
15
+ functions: WasmHostFunctions;
16
+ /** the most memory one module's instance may have */
17
+ maxMemoryBytes: number;
18
+ /** the largest range one `read` copies out to the guest */
19
+ maxReadBytes: number;
20
+ }
21
+ /** The function names a sandbox's modules may import from `gameslate`. */
22
+ export declare const wasmImportNames: (functions: WasmHostFunctions) => ReadonlySet<string>;
23
+ /**
24
+ * Why `bytes` can't run in a sandbox whose capabilities are `allowed` (function names imported
25
+ * from `gameslate`) and whose modules get at most `maxMemoryBytes`, or null.
26
+ */
27
+ export declare function wasmModuleProblem(bytes: Uint8Array<ArrayBuffer>, allowed: ReadonlySet<string>, maxMemoryBytes: number): string | null;
28
+ /** One sandbox's modules, instantiated when first used and called within a time budget. */
29
+ export declare class WasmInstances {
30
+ private readonly setup;
31
+ /** called once when a module overran its budget and was stopped */
32
+ private readonly onStopped;
33
+ private readonly instances;
34
+ private readonly global;
35
+ private readonly context;
36
+ private stopped;
37
+ private readonly allowed;
38
+ constructor(setup: WasmSetup,
39
+ /** called once when a module overran its budget and was stopped */
40
+ onStopped: (reason: string) => void);
41
+ /** Calls export `fn` of `file` with numbers; its number result (undefined for none). */
42
+ call(file: string, fn: string, args: readonly number[], ms: number): number | undefined;
43
+ /** A copy of `length` bytes of `file`'s memory from `ptr`. */
44
+ read(file: string, ptr: number, length: number, ms: number): Uint8Array;
45
+ write(file: string, ptr: number, bytes: Uint8Array, ms: number): void;
46
+ memoryBytes(file: string, ms: number): number;
47
+ private memoryOf;
48
+ private range;
49
+ private instance;
50
+ private timed;
51
+ }
@@ -0,0 +1,270 @@
1
+ import vm from 'node:vm';
2
+ /*
3
+ * A plugin's own WebAssembly modules ("Closing the sandbox" item 3 in
4
+ * docs/plugin-architecture.md), for work too slow in the QuickJS interpreter. The host's V8
5
+ * compiles and runs them, and the plugin's QuickJS code calls their exports with numbers and
6
+ * copies byte ranges in and out of their memory (quickjs-guest.ts bridges the two).
7
+ *
8
+ * What keeps them as boxed in as the QuickJS code:
9
+ * - Imports: a module may import only `env.memory` and the sandbox's capabilities as functions
10
+ * from `gameslate` (the allow-list). No WASI, no other function, table or global: checked with
11
+ * `WebAssembly.Module.imports` when the plugin loads and again when the module is instantiated.
12
+ * - Memory: the core owns it. A module that defines its own memory is refused (its maximum
13
+ * couldn't be enforced); the one it imports is created with the sandbox's maximum, so a
14
+ * `memory.grow` past it returns -1.
15
+ * - Time: every call, and the instantiation (a start function), runs under the guest call's
16
+ * deadline in a `vm` script with a timeout, whose watchdog stops V8 mid-loop. A module that was
17
+ * stopped is never called again and its guest is switched off.
18
+ * - Values: only numbers cross; an export that returns anything else (a function reference) is
19
+ * refused, so no host object reaches the guest.
20
+ */
21
+ export const WASM_PAGE_BYTES = 64 * 1024;
22
+ /** the one memory a module may import: what wasm-ld (Rust, C) and AssemblyScript name it with
23
+ * --import-memory */
24
+ const MEMORY_MODULE = 'env';
25
+ const MEMORY_NAME = 'memory';
26
+ /** the module the sandbox's capabilities are imported from */
27
+ export const WASM_HOST_MODULE = 'gameslate';
28
+ /** the largest module a plugin may bundle */
29
+ export const WASM_MAX_MODULE_BYTES = 8 * 1024 * 1024;
30
+ /** The function names a sandbox's modules may import from `gameslate`. */
31
+ export const wasmImportNames = (functions) => new Set(Object.keys(functions(() => new Uint8Array(0))));
32
+ /* A cursor over a module's bytes: LEB128 numbers and names. */
33
+ class ModuleReader {
34
+ bytes;
35
+ pos = 8; /* past the magic number and version */
36
+ constructor(bytes) {
37
+ this.bytes = bytes;
38
+ }
39
+ byte() {
40
+ const byte = this.bytes[this.pos++];
41
+ if (byte === undefined)
42
+ throw new Error('a read past the end of the module');
43
+ return byte;
44
+ }
45
+ u32() {
46
+ let result = 0;
47
+ for (let shift = 0;; shift += 7) {
48
+ const byte = this.byte();
49
+ result += (byte & 0x7f) * 2 ** shift;
50
+ if (byte < 0x80)
51
+ return result;
52
+ }
53
+ }
54
+ skipName() {
55
+ const length = this.u32();
56
+ this.pos += length;
57
+ }
58
+ }
59
+ /* The import section's memory, if any. Only called on imports that passed the allow-list, so
60
+ * they are functions and memories only. */
61
+ function importedMemory(r) {
62
+ for (let n = r.u32(); n > 0; n--) {
63
+ r.skipName();
64
+ r.skipName();
65
+ const kind = r.byte();
66
+ if (kind === 0)
67
+ r.u32();
68
+ else if (kind !== 2)
69
+ throw new Error(`an import of kind ${kind} got past the allow-list`);
70
+ else {
71
+ const flags = r.byte();
72
+ /* 0: min only; 1: min and max; anything else is shared or 64-bit */
73
+ if (flags !== 0 && flags !== 1)
74
+ return 'unsupported';
75
+ const minPages = r.u32();
76
+ /* one memory at most: the allow-list has one name and refuses it twice */
77
+ return { minPages, maxPages: flags === 1 ? r.u32() : null };
78
+ }
79
+ }
80
+ return null;
81
+ }
82
+ /* What the binary says about memory, which `WebAssembly.Module` doesn't reflect: whether it
83
+ * defines one, and the limits of the one it imports. */
84
+ function memoryLayout(bytes) {
85
+ const r = new ModuleReader(bytes);
86
+ let defines = false;
87
+ let imported = null;
88
+ while (r.pos < bytes.length) {
89
+ const id = r.byte();
90
+ const size = r.u32();
91
+ const end = r.pos + size;
92
+ if (id === 5)
93
+ defines = r.u32() > 0;
94
+ if (id === 2)
95
+ imported = importedMemory(r);
96
+ r.pos = end;
97
+ }
98
+ return { defines, imported };
99
+ }
100
+ /**
101
+ * Why `bytes` can't run in a sandbox whose capabilities are `allowed` (function names imported
102
+ * from `gameslate`) and whose modules get at most `maxMemoryBytes`, or null.
103
+ */
104
+ export function wasmModuleProblem(bytes, allowed, maxMemoryBytes) {
105
+ const checked = checkedModule(bytes, allowed, maxMemoryBytes);
106
+ return typeof checked === 'string' ? checked : null;
107
+ }
108
+ /* The compiled module, or why it can't run (see wasmModuleProblem). */
109
+ function checkedModule(bytes, allowed, maxMemoryBytes) {
110
+ if (bytes.byteLength > WASM_MAX_MODULE_BYTES)
111
+ return `it is over ${WASM_MAX_MODULE_BYTES} bytes`;
112
+ if (!WebAssembly.validate(bytes))
113
+ return 'it is not a valid WebAssembly module';
114
+ const compiled = new WebAssembly.Module(bytes);
115
+ const seen = new Set();
116
+ for (const imp of WebAssembly.Module.imports(compiled)) {
117
+ const name = `${imp.module}.${imp.name}`;
118
+ const isMemory = imp.module === MEMORY_MODULE && imp.name === MEMORY_NAME && imp.kind === 'memory';
119
+ const isCapability = imp.module === WASM_HOST_MODULE && allowed.has(imp.name) && imp.kind === 'function';
120
+ if (!isMemory && !isCapability) {
121
+ const list = [`${MEMORY_MODULE}.${MEMORY_NAME}`, ...allowed].join(', ');
122
+ return `it imports ${name} (${imp.kind}); a module may import only ${list}`;
123
+ }
124
+ if (seen.has(name))
125
+ return `it imports ${name} twice`;
126
+ seen.add(name);
127
+ }
128
+ const layout = memoryLayout(bytes);
129
+ if (layout.defines)
130
+ return 'it defines its own memory: import env.memory instead (link with --import-memory)';
131
+ if (layout.imported === 'unsupported')
132
+ return 'its memory is shared or 64-bit';
133
+ if (layout.imported && layout.imported.minPages * WASM_PAGE_BYTES > maxMemoryBytes)
134
+ return `it starts with more memory than a module may have (${maxMemoryBytes} bytes)`;
135
+ return compiled;
136
+ }
137
+ const TIMED_CALL = new vm.Script('__gsRun()');
138
+ const TIMEOUT_CODE = 'ERR_SCRIPT_EXECUTION_TIMEOUT';
139
+ /** One sandbox's modules, instantiated when first used and called within a time budget. */
140
+ export class WasmInstances {
141
+ setup;
142
+ onStopped;
143
+ instances = new Map();
144
+ /* the timed script's global object: createContext makes this object the context */
145
+ global = {};
146
+ context = vm.createContext(this.global);
147
+ stopped = null;
148
+ allowed;
149
+ constructor(setup,
150
+ /** called once when a module overran its budget and was stopped */
151
+ onStopped) {
152
+ this.setup = setup;
153
+ this.onStopped = onStopped;
154
+ this.allowed = wasmImportNames(setup.functions);
155
+ }
156
+ /** Calls export `fn` of `file` with numbers; its number result (undefined for none). */
157
+ call(file, fn, args, ms) {
158
+ return this.timed(ms, `${file} ${fn}`, () => {
159
+ const { exports } = this.instance(file);
160
+ const exported = exports[fn];
161
+ /* an exports object has no prototype, so only its own names are found */
162
+ if (typeof exported !== 'function')
163
+ throw new Error(`${file} exports no function ${fn}`);
164
+ return numberResult(file, fn, Reflect.apply(exported, undefined, args));
165
+ });
166
+ }
167
+ /** A copy of `length` bytes of `file`'s memory from `ptr`. */
168
+ read(file, ptr, length, ms) {
169
+ /* the copy lands in the interpreter's heap outside its memory limit, like an input read */
170
+ if (length > this.setup.maxReadBytes)
171
+ throw new Error(`a WebAssembly read of ${length} bytes is over the limit`);
172
+ return this.timed(ms, file, () => this.range(file, ptr, length).slice());
173
+ }
174
+ write(file, ptr, bytes, ms) {
175
+ this.timed(ms, file, () => this.range(file, ptr, bytes.length).set(bytes));
176
+ }
177
+ memoryBytes(file, ms) {
178
+ return this.timed(ms, file, () => this.memoryOf(file).buffer.byteLength);
179
+ }
180
+ memoryOf(file) {
181
+ const { memory } = this.instance(file);
182
+ if (!memory)
183
+ throw new Error(`${file} has no memory (it imports no env.memory)`);
184
+ return memory;
185
+ }
186
+ range(file, ptr, length) {
187
+ const memory = new Uint8Array(this.memoryOf(file).buffer);
188
+ if (!Number.isInteger(ptr) || !Number.isInteger(length) || ptr < 0 || length < 0)
189
+ throw new Error('a memory range needs a whole-number pointer and length');
190
+ if (ptr + length > memory.length)
191
+ throw new Error(`a range past the end of ${file}'s memory`);
192
+ return memory.subarray(ptr, ptr + length);
193
+ }
194
+ instance(file) {
195
+ const existing = this.instances.get(file);
196
+ if (existing)
197
+ return existing;
198
+ const found = this.setup.modules.find(m => m.file === file);
199
+ if (!found)
200
+ throw new Error(`the plugin bundles no WebAssembly module ${file}`);
201
+ const { maxMemoryBytes } = this.setup;
202
+ const compiled = checkedModule(found.bytes, this.allowed, maxMemoryBytes);
203
+ if (typeof compiled === 'string')
204
+ throw new Error(`${file}: ${compiled}`);
205
+ const limits = memoryLayout(found.bytes).imported;
206
+ if (limits === 'unsupported')
207
+ throw new Error(`${file}: its memory is shared or 64-bit`);
208
+ const capPages = Math.floor(maxMemoryBytes / WASM_PAGE_BYTES);
209
+ const memory = limits
210
+ ? new WebAssembly.Memory({
211
+ initial: limits.minPages,
212
+ maximum: Math.min(capPages, limits.maxPages ?? capPages),
213
+ })
214
+ : null;
215
+ const view = () => {
216
+ if (!memory)
217
+ throw new Error(`${file} has no memory (it imports no env.memory)`);
218
+ return new Uint8Array(memory.buffer);
219
+ };
220
+ const imports = {
221
+ [MEMORY_MODULE]: memory ? { [MEMORY_NAME]: memory } : {},
222
+ [WASM_HOST_MODULE]: this.setup.functions(view),
223
+ };
224
+ const instance = new WebAssembly.Instance(compiled, imports);
225
+ const made = { exports: instance.exports, memory };
226
+ this.instances.set(file, made);
227
+ return made;
228
+ }
229
+ /* `run` with a watchdog: past `ms` V8 is stopped wherever it is, even inside a loop with no
230
+ * calls in it, and the error comes back here */
231
+ timed(ms, what, run) {
232
+ if (this.stopped)
233
+ throw new Error(`WebAssembly is switched off: ${this.stopped}`);
234
+ const timeout = Math.ceil(ms);
235
+ if (timeout < 1)
236
+ throw new Error(`no time left in the budget for ${what}`);
237
+ const results = [];
238
+ this.global.__gsRun = () => {
239
+ results.push({ value: run() });
240
+ };
241
+ try {
242
+ TIMED_CALL.runInContext(this.context, { timeout });
243
+ }
244
+ catch (e) {
245
+ /* Node marks its watchdog's error by this code (checked by shape: the error can come
246
+ * from another realm) */
247
+ if (typeof e === 'object' && e !== null && 'code' in e && e.code === TIMEOUT_CODE) {
248
+ this.stopped = `${what} ran past its ${timeout} ms budget and was stopped`;
249
+ this.instances.clear();
250
+ this.onStopped(this.stopped);
251
+ throw new Error(this.stopped);
252
+ }
253
+ throw e;
254
+ }
255
+ finally {
256
+ this.global.__gsRun = undefined;
257
+ }
258
+ const [result] = results;
259
+ if (!result)
260
+ throw new Error(`${what} returned nothing`);
261
+ return result.value;
262
+ }
263
+ }
264
+ function numberResult(file, fn, value) {
265
+ if (typeof value === 'number' || value === undefined)
266
+ return value;
267
+ if (typeof value === 'bigint' && Number.isSafeInteger(Number(value)))
268
+ return Number(value);
269
+ throw new Error(`${file} ${fn} returned something other than a number`);
270
+ }
@@ -52,7 +52,8 @@ export interface GamePlugin {
52
52
  readonly executableHints: readonly string[];
53
53
  /**
54
54
  * Stats a launch wrapper from an older bundle may not send. While any is missing, the daemon
55
- * fills them (and flags) from its own direct read of the game, without a relaunch.
55
+ * fills them (and flags) from its own direct read of the game, without a relaunch, provided
56
+ * the wrapper introduced itself (cores after 2.3.0; older wrappers send no `bridge:hello`).
56
57
  */
57
58
  readonly wrapperMayOmitStats?: readonly string[];
58
59
  /**
@@ -1,3 +1,4 @@
1
1
  export * from './contract.js';
2
2
  export * from './seqlock.js';
3
3
  export * from './sandbox-guest.js';
4
+ export * from './wasm.js';
@@ -1,9 +1,10 @@
1
1
  /*
2
2
  * `@gameslate/sdk/plugin`: what a plugin's code builds against. The contract (GamePlugin,
3
3
  * GameMemory, AssetExtractor, PluginModule), pure helpers, and the sandbox's guest side
4
- * (`exposeToHost`, `exposeAssetsToHost`). No Node APIs: plugin bundles run in the core's QuickJS
5
- * sandbox.
4
+ * (`exposeToHost`, `exposeAssetsToHost`, `wasmModule`). No Node APIs: plugin bundles run in the
5
+ * core's QuickJS sandbox.
6
6
  */
7
7
  export * from './contract.js';
8
8
  export * from './seqlock.js';
9
9
  export * from './sandbox-guest.js';
10
+ export * from './wasm.js';
@@ -99,6 +99,7 @@ function inputFiles(host, json) {
99
99
  return files.map(f => ({
100
100
  name: f.name,
101
101
  size: f.size,
102
+ handle: f.handle,
102
103
  read: (offset, length) => new Uint8Array(host.inputRead(f.handle, offset, length)),
103
104
  }));
104
105
  }
@@ -0,0 +1,17 @@
1
+ import type { SandboxWasmHostApi } from '../index.js';
2
+ declare global {
3
+ var __gsWasm: SandboxWasmHostApi | undefined;
4
+ }
5
+ export interface WasmModule {
6
+ /** calls an export with numbers (i32, f32, f64; i64 results come back as numbers) */
7
+ call(fn: string, ...args: number[]): number | undefined;
8
+ /** a copy of `length` bytes of the module's memory from `ptr` */
9
+ read(ptr: number, length: number): Uint8Array;
10
+ /** copies `bytes` into the module's memory at `ptr` */
11
+ write(ptr: number, bytes: Uint8Array): void;
12
+ /** the module's memory size now, in bytes */
13
+ memoryBytes(): number;
14
+ }
15
+ /** The module the manifest lists as `file` (`palette.wasm`), as `gameslate-plugin build` copied
16
+ * it from the plugin's `wasm/` folder. */
17
+ export declare function wasmModule(file: string): WasmModule;
@@ -0,0 +1,17 @@
1
+ /** The module the manifest lists as `file` (`palette.wasm`), as `gameslate-plugin build` copied
2
+ * it from the plugin's `wasm/` folder. */
3
+ export function wasmModule(file) {
4
+ const host = () => {
5
+ const bridge = globalThis.__gsWasm;
6
+ if (!bridge)
7
+ throw new Error('the core gave no WebAssembly capability');
8
+ return bridge;
9
+ };
10
+ return {
11
+ call: (fn, ...args) => host().call(file, fn, ...args),
12
+ read: (ptr, length) => new Uint8Array(host().read(file, ptr, length)),
13
+ /* an exact-size copy, so only these bytes cross */
14
+ write: (ptr, bytes) => host().write(file, ptr, bytes.slice().buffer),
15
+ memoryBytes: () => host().memoryBytes(file),
16
+ };
17
+ }