@gameslate/sdk 0.3.6 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,292 @@
1
+ import { z } from 'zod';
2
+ import { guestToRa } from '../n64-address.js';
3
+ import { GameStateSchema } from '../types.js';
4
+ /*
5
+ * `gameslate-plugin verify`: run a game to a known moment, read what the plugin reports through
6
+ * a local GameSlate daemon, and check it against what the moment shows (`verify.json`). For an
7
+ * emulated console the emulator's own memory reads are a second opinion on the plugin's: RetroArch
8
+ * answers READ_CORE_RAM with RetroAchievements' addressing, independent of GameSlate's.
9
+ * The steps take their effects as parameters (verify-effects.ts has the real ones).
10
+ */
11
+ const Hex = z
12
+ .string()
13
+ .regex(/^0x[0-9a-fA-F]{1,8}$/, 'a hex address such as 0x801EF6AA')
14
+ .transform(h => Number.parseInt(h, 16));
15
+ const Expected = z.union([z.number(), z.object({ min: z.number(), max: z.number() })]);
16
+ /** A guest value to watch while driving: `{ "peek": "0x800dc50c:4", "equals": 4 }`. */
17
+ const PeekCheck = z.object({
18
+ peek: z.string().regex(/^0x[0-9a-fA-F]{1,8}:[124]$/, 'a guest address and size: 0x800dc50c:4'),
19
+ equals: z.number().int(),
20
+ });
21
+ /** What a moment must read: the plugin's state, field by field (counters exact or in a range). */
22
+ const ExpectSchema = z.object({
23
+ phase: z.string().optional(),
24
+ locationId: z.string().optional(),
25
+ difficulty: z.string().optional(),
26
+ variant: z.string().optional(),
27
+ roomId: z.number().int().optional(),
28
+ counters: z.record(z.string(), Expected).default({}),
29
+ });
30
+ /** Wait on the plugin's own state, for moments no fixed address shows (a PlayState that moves):
31
+ * `{ "state": { "phase": "in_stage", "locationId": "lost_woods_intro" } }`. */
32
+ const StateCheck = z.object({ state: ExpectSchema });
33
+ /* `times`: how many reads in a row must match. Transitions can pass through a state for a frame
34
+ * (MM's opening reads as gameplay between its scripted shots), which shouldn't count. */
35
+ const Times = { times: z.number().int().min(1).default(1) };
36
+ const WaitCheck = z.union([PeekCheck.extend(Times), StateCheck.extend(Times)]);
37
+ /* One step of driving the game to its moment, run through `gameslate drive`. */
38
+ const StepSchema = z.union([
39
+ z.object({
40
+ /** a key (X keysym name) to press, once, or until a value matches; several keys take
41
+ * turns (a map where Start selects and A reads on through the briefing) */
42
+ press: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]),
43
+ holdMs: z.number().int().min(0).default(100),
44
+ until: WaitCheck.optional(),
45
+ everyMs: z.number().int().min(0).default(2000),
46
+ maxTries: z.number().int().min(1).default(20),
47
+ }),
48
+ z.object({
49
+ waitFor: WaitCheck,
50
+ timeoutMs: z.number().int().min(0).default(30_000),
51
+ everyMs: z.number().int().min(100).default(1000),
52
+ }),
53
+ /** the screen the game drew, saved under this name beside the spec */
54
+ z.object({ frame: z.string().min(1) }),
55
+ /** a pause, for screens nothing in memory marks (a boot, a menu's fade) */
56
+ z.object({ waitMs: z.number().int().min(0) }),
57
+ ]);
58
+ /* the web app's tabs; one missing for a game (a pack without missions) is reported, not an error */
59
+ const UI_TABS = ['Map', 'Inventory', 'Missions', 'Ref'];
60
+ export const VerifySpecSchema = z.object({
61
+ /** the game id the daemon must report */
62
+ game: z.string().min(1),
63
+ /** RetroArch with a core, a ROM and a save state slot, loaded on start (no input needed) */
64
+ retroarch: z
65
+ .object({
66
+ binary: z.string(),
67
+ core: z.string(),
68
+ rom: z.string(),
69
+ stateSlot: z.number().int().min(0).max(999),
70
+ /** run RetroArch through this (`["node", "<gameslate>/dist/gameslate.mjs", "run", "--"]`)
71
+ * where only a game's parent may read its memory (ptrace_scope 1, ChimeraOS) */
72
+ launchPrefix: z.array(z.string()).default([]),
73
+ /** a config appended to RetroArch's, which must turn network commands on */
74
+ config: z.string().optional(),
75
+ port: z.number().int().default(55355),
76
+ })
77
+ .optional(),
78
+ /** any emulator, started with this command (the ROM on its command line, so the core finds it) */
79
+ emulator: z
80
+ .object({
81
+ command: z.array(z.string()).min(1),
82
+ /** as for RetroArch: through GameSlate's launch wrapper where only a parent may read */
83
+ launchPrefix: z.array(z.string()).default([]),
84
+ })
85
+ .optional(),
86
+ /** GameSlate's `dist/gameslate.mjs`, whose `drive` commands run the steps */
87
+ gameslate: z.string().optional(),
88
+ /** how to get to the moment: keys, waits on values, screenshots (docs/emulator-driving.md) */
89
+ steps: z.array(StepSchema).default([]),
90
+ daemon: z.object({ url: z.string().default('ws://localhost:4310/ws') }).default({}),
91
+ /** the GameSlate page to screenshot beside the game: a URL (with its `#token=`), or the URL and
92
+ * the tabs to open and screenshot one by one at the moment */
93
+ ui: z
94
+ .union([
95
+ z.string().transform(url => ({ url, tabs: [...UI_TABS] })),
96
+ z.object({ url: z.string(), tabs: z.array(z.string().min(1)).default([...UI_TABS]) }),
97
+ ])
98
+ .optional(),
99
+ /** how long to let the game run before reading */
100
+ settleMs: z.number().int().min(0).default(5000),
101
+ timeoutMs: z.number().int().min(1000).default(60_000),
102
+ expect: ExpectSchema,
103
+ /** values to read through the emulator too: each must equal the plugin's counter */
104
+ memory: z
105
+ .array(z
106
+ .object({
107
+ address: Hex,
108
+ size: z.union([z.literal(1), z.literal(2), z.literal(4)]),
109
+ signed: z.boolean().default(false),
110
+ counter: z.string(),
111
+ })
112
+ .refine(m => m.address % m.size === 0, {
113
+ message: 'a memory address must be aligned to its size',
114
+ }))
115
+ .default([]),
116
+ });
117
+ /**
118
+ * `${NAME}` in any string of a spec, from the environment, so a spec can be shared without one
119
+ * machine's paths (`"${GOPHER64}"`, `"${N64_ROMS}/Mario Kart 64 (U).z64"`). Throws on a name that
120
+ * isn't set.
121
+ */
122
+ export function expandEnv(value, env) {
123
+ if (typeof value === 'string')
124
+ return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => {
125
+ const set = env[name];
126
+ if (set === undefined)
127
+ throw new Error(`the spec uses \${${name}}, which isn't set`);
128
+ return set;
129
+ });
130
+ if (Array.isArray(value))
131
+ return value.map(v => expandEnv(v, env));
132
+ if (typeof value === 'object' && value !== null)
133
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, expandEnv(v, env)]));
134
+ return value;
135
+ }
136
+ /** What doesn't match: one line each. */
137
+ export function stateMismatches(expect, state) {
138
+ const out = [];
139
+ const same = (what, want, got) => {
140
+ if (want !== undefined && want !== got)
141
+ out.push(`${what}: expected ${String(want)}, got ${String(got)}`);
142
+ };
143
+ same('phase', expect.phase, state.phase);
144
+ same('location', expect.locationId, state.locationId);
145
+ same('difficulty', expect.difficulty, state.difficulty);
146
+ same('variant', expect.variant, state.variant);
147
+ same('room', expect.roomId, state.position?.roomId);
148
+ for (const [id, want] of Object.entries(expect.counters)) {
149
+ const got = state.counters?.[id];
150
+ if (got === undefined)
151
+ out.push(`counter ${id}: not reported`);
152
+ else if (typeof want === 'number')
153
+ same(`counter ${id}`, want, got);
154
+ else if (got < want.min || got > want.max)
155
+ out.push(`counter ${id}: expected ${want.min}..${want.max}, got ${got}`);
156
+ }
157
+ return out;
158
+ }
159
+ /** RetroArch's network command reading a value with RetroAchievements' addressing. */
160
+ export function readCoreRamCommand(check) {
161
+ return `READ_CORE_RAM ${guestToRa(check.address, check.size).toString(16)} ${check.size}`;
162
+ }
163
+ /** The value in RetroArch's reply (bytes in the emulator's little-endian words), or why not. */
164
+ export function valueFromReply(reply, check) {
165
+ const parts = reply.trim().split(/\s+/);
166
+ if (parts[0] !== 'READ_CORE_RAM' || parts.length < 3)
167
+ return `unexpected reply "${reply}"`;
168
+ if (parts[2] === '-1')
169
+ return `RetroArch couldn't read it: "${reply}"`;
170
+ const bytes = parts.slice(2).map(b => Number.parseInt(b, 16));
171
+ if (bytes.length !== check.size || bytes.some(b => Number.isNaN(b)))
172
+ return `malformed reply "${reply}"`;
173
+ const unsigned = bytes.reduceRight((value, b) => value * 256 + b, 0);
174
+ const bits = check.size * 8;
175
+ return check.signed && unsigned >= 2 ** (bits - 1) ? unsigned - 2 ** bits : unsigned;
176
+ }
177
+ async function memoryProblems(spec, state, effects) {
178
+ const out = [];
179
+ for (const check of spec.memory) {
180
+ const reply = await effects
181
+ .command(spec, readCoreRamCommand(check))
182
+ .catch((e) => (e instanceof Error ? e.message : String(e)));
183
+ const read = reply.startsWith('READ_CORE_RAM') ? valueFromReply(reply, check) : reply;
184
+ const reported = state.counters?.[check.counter];
185
+ const at = `0x${check.address.toString(16)}`;
186
+ if (typeof read === 'string')
187
+ out.push(`memory ${at}: ${read}`);
188
+ else if (reported !== read)
189
+ out.push(`memory ${at}: the emulator reads ${read}, the plugin reports ${check.counter} = ${String(reported)}`);
190
+ }
191
+ return out;
192
+ }
193
+ /* A watched value (through `gameslate drive peek`) or the plugin's state (from the daemon). */
194
+ async function checkMatches(d, check) {
195
+ if ('state' in check) {
196
+ const parsed = GameStateSchema.safeParse(await d.effects.state(d.spec));
197
+ return parsed.success && stateMismatches(check.state, parsed.data).length === 0;
198
+ }
199
+ const out = await d.effects.drive(d.spec, ['peek', String(d.pid), check.peek]);
200
+ const values = JSON.parse(out);
201
+ return (typeof values === 'object' &&
202
+ values !== null &&
203
+ Reflect.get(values, check.peek) === check.equals);
204
+ }
205
+ const describeCheck = (check) => 'state' in check
206
+ ? `the state ${JSON.stringify(check.state)}`
207
+ : `${check.peek} = ${check.equals}`;
208
+ /* One step; a problem when it couldn't do what it says, or null. */
209
+ async function runStep(d, step, frames) {
210
+ if ('frame' in step) {
211
+ await d.effects.drive(d.spec, ['frame', String(d.pid), step.frame]);
212
+ frames.push(step.frame);
213
+ return null;
214
+ }
215
+ if ('waitMs' in step) {
216
+ await d.effects.wait(step.waitMs);
217
+ return null;
218
+ }
219
+ if ('waitFor' in step) {
220
+ let streak = 0;
221
+ for (let waited = 0; waited <= step.timeoutMs; waited += step.everyMs) {
222
+ streak = (await checkMatches(d, step.waitFor)) ? streak + 1 : 0;
223
+ if (streak >= step.waitFor.times)
224
+ return null;
225
+ await d.effects.wait(step.everyMs);
226
+ }
227
+ return `waited ${step.timeoutMs} ms for ${describeCheck(step.waitFor)}`;
228
+ }
229
+ const keys = typeof step.press === 'string' ? [step.press] : step.press;
230
+ let streak = 0;
231
+ for (let i = 0; i < (step.until ? step.maxTries : 1); i++) {
232
+ const key = keys[i % keys.length] ?? '';
233
+ await d.effects.drive(d.spec, ['press', '--pid', String(d.pid), key, String(step.holdMs)]);
234
+ if (!step.until)
235
+ return null;
236
+ await d.effects.wait(step.everyMs);
237
+ streak = (await checkMatches(d, step.until)) ? streak + 1 : 0;
238
+ if (streak >= step.until.times)
239
+ return null;
240
+ }
241
+ return `pressed ${keys.join('/')} ${step.maxTries} times without ${step.until ? describeCheck(step.until) : ''}`;
242
+ }
243
+ /** Drives the game to its moment; the first problem stops it. */
244
+ async function runSteps(spec, effects, pid) {
245
+ const frames = [];
246
+ if (!spec.steps.length)
247
+ return { problem: null, frames };
248
+ if (pid === undefined)
249
+ return { problem: 'steps need an emulator the run started', frames };
250
+ for (const step of spec.steps) {
251
+ const problem = await runStep({ spec, effects, pid }, step, frames).catch((e) => e instanceof Error ? e.message : String(e));
252
+ if (problem)
253
+ return { problem, frames };
254
+ }
255
+ return { problem: null, frames };
256
+ }
257
+ /** Runs one check: start the game, drive it to its moment, let it settle, compare, screenshot, stop. */
258
+ export async function runVerify(spec, effects) {
259
+ const game = await effects.launch(spec);
260
+ try {
261
+ const driven = await runSteps(spec, effects, game.pid);
262
+ if (driven.problem)
263
+ return {
264
+ ok: false,
265
+ problems: [driven.problem],
266
+ screenshots: driven.frames,
267
+ state: null,
268
+ };
269
+ await effects.wait(spec.settleMs);
270
+ const raw = await effects.state(spec).catch((e) => e);
271
+ if (raw instanceof Error)
272
+ return { ok: false, problems: [raw.message], screenshots: driven.frames, state: null };
273
+ const parsed = GameStateSchema.safeParse(raw);
274
+ if (!parsed.success)
275
+ return {
276
+ ok: false,
277
+ problems: [`the daemon's state: ${parsed.error.message}`],
278
+ screenshots: driven.frames,
279
+ state: null,
280
+ };
281
+ const state = parsed.data;
282
+ const problems = [
283
+ ...stateMismatches(spec.expect, state),
284
+ ...(await memoryProblems(spec, state, effects)),
285
+ ];
286
+ const screenshots = [...driven.frames, ...(await effects.screenshots(spec))];
287
+ return { ok: problems.length === 0, problems, screenshots, state };
288
+ }
289
+ finally {
290
+ game.stop();
291
+ }
292
+ }
package/lib/index.d.ts CHANGED
@@ -15,3 +15,4 @@ export * from './sandbox-protocol.js';
15
15
  export * from './assets.js';
16
16
  export * from './plugins-api.js';
17
17
  export * from './signature.js';
18
+ export * from './n64-address.js';
package/lib/index.js CHANGED
@@ -15,3 +15,4 @@ export * from './sandbox-protocol.js';
15
15
  export * from './assets.js';
16
16
  export * from './plugins-api.js';
17
17
  export * from './signature.js';
18
+ export * from './n64-address.js';
@@ -0,0 +1,5 @@
1
+ export type N64ValueBytes = 1 | 2 | 4;
2
+ /** A guest address (0x80…) for a value RA notes at `ra` (an RDRAM offset), of `size` bytes. */
3
+ export declare function raToGuest(ra: number, size: N64ValueBytes): number;
4
+ /** The RA address (an RDRAM offset) of the `size`-byte value at guest address `guest`. */
5
+ export declare function guestToRa(guest: number, size: N64ValueBytes): number;
@@ -0,0 +1,25 @@
1
+ /*
2
+ * RetroAchievements' N64 addresses and the console's own. RA (rcheevos) reads RDRAM as the
3
+ * emulator stores it: physical offsets in little-endian 32-bit words. GameSlate reads guest
4
+ * addresses (0x80…) in the console's big-endian order. A value's bytes keep their place within
5
+ * its aligned word, so only the address moves: a byte by ^3, a 16-bit value by ^2, a 32-bit one
6
+ * not at all. (Checked on 2026-11-29: 16 OoT and 16 MM save fields land on RA's notes this way.)
7
+ */
8
+ const KSEG0 = 0x80000000;
9
+ const PHYSICAL_MASK = 0x1fffffff;
10
+ const swizzle = (size) => (size === 1 ? 3 : size === 2 ? 2 : 0);
11
+ function checkAligned(address, size, what) {
12
+ if (address % size !== 0)
13
+ throw new Error(`${what} 0x${address.toString(16)} isn't aligned to ${size}`);
14
+ }
15
+ /** A guest address (0x80…) for a value RA notes at `ra` (an RDRAM offset), of `size` bytes. */
16
+ export function raToGuest(ra, size) {
17
+ const physical = ra ^ swizzle(size);
18
+ checkAligned(physical, size, 'RA address');
19
+ return (KSEG0 | physical) >>> 0;
20
+ }
21
+ /** The RA address (an RDRAM offset) of the `size`-byte value at guest address `guest`. */
22
+ export function guestToRa(guest, size) {
23
+ checkAligned(guest, size, 'guest address');
24
+ return (guest & PHYSICAL_MASK) ^ swizzle(size);
25
+ }
package/lib/pack.d.ts CHANGED
@@ -44,17 +44,17 @@ export declare const PackDataSchema: z.ZodObject<{
44
44
  id: string;
45
45
  icon?: string | undefined;
46
46
  max?: string | number | undefined;
47
+ format?: "number" | "percent" | undefined;
47
48
  display?: Record<string, string> | undefined;
48
49
  role?: "keys" | "health" | "magic" | "armor" | undefined;
49
- format?: "number" | "percent" | undefined;
50
50
  }, {
51
51
  label: string;
52
52
  id: string;
53
53
  icon?: string | undefined;
54
54
  max?: string | number | undefined;
55
+ format?: "number" | "percent" | undefined;
55
56
  display?: Record<string, string> | undefined;
56
57
  role?: "keys" | "health" | "magic" | "armor" | undefined;
57
- format?: "number" | "percent" | undefined;
58
58
  }>, "many">;
59
59
  flagSets: z.ZodArray<z.ZodString, "many">;
60
60
  inventoryLayouts: z.ZodArray<z.ZodDiscriminatedUnion<"kind", [z.ZodObject<{
@@ -459,9 +459,9 @@ export declare const PackDataSchema: z.ZodObject<{
459
459
  id: string;
460
460
  icon?: string | undefined;
461
461
  max?: string | number | undefined;
462
+ format?: "number" | "percent" | undefined;
462
463
  display?: Record<string, string> | undefined;
463
464
  role?: "keys" | "health" | "magic" | "armor" | undefined;
464
- format?: "number" | "percent" | undefined;
465
465
  }[];
466
466
  flagSets: string[];
467
467
  items: {
@@ -578,9 +578,9 @@ export declare const PackDataSchema: z.ZodObject<{
578
578
  id: string;
579
579
  icon?: string | undefined;
580
580
  max?: string | number | undefined;
581
+ format?: "number" | "percent" | undefined;
581
582
  display?: Record<string, string> | undefined;
582
583
  role?: "keys" | "health" | "magic" | "armor" | undefined;
583
- format?: "number" | "percent" | undefined;
584
584
  }[];
585
585
  flagSets: string[];
586
586
  items: {
@@ -717,9 +717,9 @@ export declare const PackDataSchema: z.ZodObject<{
717
717
  id: string;
718
718
  icon?: string | undefined;
719
719
  max?: string | number | undefined;
720
+ format?: "number" | "percent" | undefined;
720
721
  display?: Record<string, string> | undefined;
721
722
  role?: "keys" | "health" | "magic" | "armor" | undefined;
722
- format?: "number" | "percent" | undefined;
723
723
  }[];
724
724
  flagSets: string[];
725
725
  items: {
@@ -844,9 +844,9 @@ export declare const PackDataSchema: z.ZodObject<{
844
844
  id: string;
845
845
  icon?: string | undefined;
846
846
  max?: string | number | undefined;
847
+ format?: "number" | "percent" | undefined;
847
848
  display?: Record<string, string> | undefined;
848
849
  role?: "keys" | "health" | "magic" | "armor" | undefined;
849
- format?: "number" | "percent" | undefined;
850
850
  }[];
851
851
  flagSets: string[];
852
852
  items: {
@@ -110,8 +110,17 @@ export interface PluginAssetsModule {
110
110
  * The Python map renderer's hooks (the Zelda ports). Still unsandboxed, with Node, until the
111
111
  * renderer is ported and those games get an AssetExtractor.
112
112
  */
113
+ /** What a game's after-assets step gets: where its assets were written. */
114
+ export interface AfterAssetsContext {
115
+ outDir: string;
116
+ }
113
117
  export interface PluginExtractModule {
114
118
  /** must equal the manifest's id */
115
119
  id: string;
120
+ /** @deprecated the Python map renderer is gone (GameSlate builds assets in the sandbox);
121
+ * kept so plugins built against older sdk versions still load */
116
122
  pythonExtract?: PythonExtract;
123
+ /** per game: a step after its extraction job, unsandboxed (e.g. notes built from data fetched
124
+ * over the network); it must not fail the extraction when it can't run */
125
+ afterAssets?: ReadonlyMap<string, (ctx: AfterAssetsContext) => Promise<void>>;
117
126
  }
@@ -57,7 +57,9 @@ function find(list, match, what) {
57
57
  /** Makes `plugin` callable by the core. A plugin bundle's entry calls this once. */
58
58
  export function exposeToHost(plugin) {
59
59
  const sessions = new Map();
60
- const source = (gameId) => find(plugin.sources, s => s.gameId === gameId, `source for ${gameId}`);
60
+ /* One game can have a source per kind of build (Ocarina of Time on PC and in an N64
61
+ * emulator): the one that verified this build. No other: its offsets would be guesses. */
62
+ const source = (gameId, buildId) => find(plugin.sources, s => s.gameId === gameId && buildId !== null && s.supportedBuildIds.has(buildId), `source for ${gameId} that verified build ${buildId ?? '(none)'}`);
61
63
  const pack = (gameId) => find(plugin.packs, p => p.id === gameId, `pack for ${gameId}`);
62
64
  globalThis.__gs = {
63
65
  describe: () => JSON.stringify(describe(plugin)),
@@ -66,7 +68,7 @@ export function exposeToHost(plugin) {
66
68
  if (!host)
67
69
  throw new Error('the core gave no memory capability');
68
70
  const info = SandboxMemoryInfoSchema.parse(JSON.parse(memoryInfo));
69
- const session = source(gameId).createSession(memoryFor(host, handle, info));
71
+ const session = source(gameId, info.buildId).createSession(memoryFor(host, handle, info));
70
72
  if (session)
71
73
  sessions.set(handle, session);
72
74
  return session !== null;
@@ -6,6 +6,8 @@ import { z } from 'zod';
6
6
  * the Python renderer's hooks.
7
7
  */
8
8
  export declare const SDK_API = 3;
9
+ /** Why a manifest may not offer `folder`, or null. */
10
+ export declare function homeFolderProblem(folder: string): string | null;
9
11
  export declare const PluginManifestSchema: z.ZodObject<{
10
12
  id: z.ZodString;
11
13
  name: z.ZodString;
@@ -35,7 +37,8 @@ export declare const PluginManifestSchema: z.ZodObject<{
35
37
  file: string;
36
38
  sha256: string;
37
39
  }>>;
38
- /** the Python map renderer's hooks: still unsandboxed, until that renderer is ported */
40
+ /** steps that run unsandboxed after a game's extraction job (e.g. data fetched over the
41
+ * network); the Python renderer's hooks lived here too */
39
42
  extract: z.ZodOptional<z.ZodObject<{
40
43
  file: z.ZodString;
41
44
  sha256: z.ZodString;
@@ -49,16 +52,23 @@ export declare const PluginManifestSchema: z.ZodObject<{
49
52
  games: z.ZodArray<z.ZodObject<{
50
53
  id: z.ZodString;
51
54
  title: z.ZodString;
55
+ /** short names a player may type for it (`gameslate extract-assets oot`) */
56
+ aliases: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
52
57
  /** where the player's own files for asset extraction usually are */
53
58
  inputs: z.ZodDefault<z.ZodArray<z.ZodObject<{
54
59
  label: z.ZodString;
55
60
  folders: z.ZodArray<z.ZodEffects<z.ZodString, string, string>, "many">;
61
+ /** folders inside the picked one whose files are inputs too, named `<subfolder>/<file>`
62
+ * (e.g. a port's `mods`) */
63
+ subfolders: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
56
64
  }, "strip", z.ZodTypeAny, {
57
65
  label: string;
58
66
  folders: string[];
67
+ subfolders?: string[] | undefined;
59
68
  }, {
60
69
  label: string;
61
70
  folders: string[];
71
+ subfolders?: string[] | undefined;
62
72
  }>, "many">>;
63
73
  }, "strip", z.ZodTypeAny, {
64
74
  id: string;
@@ -66,13 +76,17 @@ export declare const PluginManifestSchema: z.ZodObject<{
66
76
  inputs: {
67
77
  label: string;
68
78
  folders: string[];
79
+ subfolders?: string[] | undefined;
69
80
  }[];
81
+ aliases?: string[] | undefined;
70
82
  }, {
71
83
  id: string;
72
84
  title: string;
85
+ aliases?: string[] | undefined;
73
86
  inputs?: {
74
87
  label: string;
75
88
  folders: string[];
89
+ subfolders?: string[] | undefined;
76
90
  }[] | undefined;
77
91
  }>, "many">;
78
92
  }, "strip", z.ZodTypeAny, {
@@ -88,7 +102,9 @@ export declare const PluginManifestSchema: z.ZodObject<{
88
102
  inputs: {
89
103
  label: string;
90
104
  folders: string[];
105
+ subfolders?: string[] | undefined;
91
106
  }[];
107
+ aliases?: string[] | undefined;
92
108
  }[];
93
109
  version: string;
94
110
  sdkApi: number;
@@ -111,9 +127,11 @@ export declare const PluginManifestSchema: z.ZodObject<{
111
127
  games: {
112
128
  id: string;
113
129
  title: string;
130
+ aliases?: string[] | undefined;
114
131
  inputs?: {
115
132
  label: string;
116
133
  folders: string[];
134
+ subfolders?: string[] | undefined;
117
135
  }[] | undefined;
118
136
  }[];
119
137
  version: string;
@@ -16,15 +16,39 @@ const Id = z
16
16
  .regex(/^[a-z0-9][a-z0-9-]*$/, 'plugin and game ids are lower-case words and dashes');
17
17
  /* a file next to the manifest, never a path out of the plugin's folder */
18
18
  const FileName = z.string().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/, 'a plain file name');
19
- /* A folder under the player's home (`~/...`), never a path out of it. */
20
- const HomeFolder = z
21
- .string()
22
- .regex(/^~\/[^\0]*$/, 'a folder under the home directory, starting with ~/')
23
- .refine(p => !p.split('/').includes('..'), 'no ".." in folders');
19
+ /* Hidden folders where games live; any other (`~/.ssh`, `~/.config/gameslate` with the pairing
20
+ * token) is refused, since a sandboxed plugin can read every file in an offered folder and show
21
+ * it in what it builds. */
22
+ const GAME_DOT_FOLDERS = ['~/.var/app/', '~/.local/share/', '~/.steam/'];
23
+ const OWN_FOLDER = '~/.local/share/gameslate';
24
+ /** Why a manifest may not offer `folder`, or null. */
25
+ export function homeFolderProblem(folder) {
26
+ if (!/^~\/[^\0]+$/.test(folder))
27
+ return 'a folder under the home directory, starting with ~/';
28
+ const parts = folder.split('/');
29
+ if (parts.includes('..') || parts.includes('.'))
30
+ return 'no "." or ".." in folders';
31
+ const prefix = GAME_DOT_FOLDERS.find(p => folder.startsWith(p));
32
+ const rest = prefix ? folder.slice(prefix.length) : folder.slice(2);
33
+ if (rest === '' || rest.split('/').some(p => p.startsWith('.')))
34
+ return `a game's folder: no hidden folders except under ${GAME_DOT_FOLDERS.join(', ')}`;
35
+ if (`${folder}/`.startsWith(`${OWN_FOLDER}/`))
36
+ return "not GameSlate's own folder";
37
+ return null;
38
+ }
39
+ /* A folder under the player's home (`~/...`) that a game's files may be in. */
40
+ const HomeFolder = z.string().superRefine((p, ctx) => {
41
+ const problem = homeFolderProblem(p);
42
+ if (problem)
43
+ ctx.addIssue({ code: 'custom', message: problem });
44
+ });
24
45
  /** Where to find the files an extractor builds from, offered to the player to pick from. */
25
46
  const InputLocation = z.object({
26
47
  label: z.string().min(1).max(100),
27
48
  folders: z.array(HomeFolder).min(1).max(20),
49
+ /** folders inside the picked one whose files are inputs too, named `<subfolder>/<file>`
50
+ * (e.g. a port's `mods`) */
51
+ subfolders: z.array(FileName).max(10).optional(),
28
52
  });
29
53
  const CodeFile = z.object({
30
54
  file: FileName,
@@ -41,12 +65,15 @@ export const PluginManifestSchema = z.object({
41
65
  code: CodeFile,
42
66
  /** asset extractors, run in the core's sandbox by extraction jobs */
43
67
  assets: CodeFile.optional(),
44
- /** the Python map renderer's hooks: still unsandboxed, until that renderer is ported */
68
+ /** steps that run unsandboxed after a game's extraction job (e.g. data fetched over the
69
+ * network); the Python renderer's hooks lived here too */
45
70
  extract: CodeFile.optional(),
46
71
  games: z
47
72
  .array(z.object({
48
73
  id: Id,
49
74
  title: z.string().min(1),
75
+ /** short names a player may type for it (`gameslate extract-assets oot`) */
76
+ aliases: z.array(Id).max(5).optional(),
50
77
  /** where the player's own files for asset extraction usually are */
51
78
  inputs: z.array(InputLocation).default([]),
52
79
  }))
@@ -134,7 +134,10 @@ export declare const JobStatusSchema: z.ZodObject<{
134
134
  /** assets skipped because an earlier run built them from the same code and inputs */
135
135
  upToDate: z.ZodNumber;
136
136
  failed: z.ZodNumber;
137
+ /** the asset that finished last */
137
138
  current: z.ZodOptional<z.ZodString>;
139
+ /** the assets being built right now (several, across builder threads) */
140
+ building: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
138
141
  notes: z.ZodArray<z.ZodString, "many">;
139
142
  failures: z.ZodArray<z.ZodObject<{
140
143
  label: z.ZodString;
@@ -164,6 +167,7 @@ export declare const JobStatusSchema: z.ZodObject<{
164
167
  }[];
165
168
  current?: string | undefined;
166
169
  error?: string | undefined;
170
+ building?: string[] | undefined;
167
171
  }, {
168
172
  id: number;
169
173
  done: number;
@@ -181,6 +185,7 @@ export declare const JobStatusSchema: z.ZodObject<{
181
185
  }[];
182
186
  current?: string | undefined;
183
187
  error?: string | undefined;
188
+ building?: string[] | undefined;
184
189
  }>;
185
190
  export type JobStatus = z.infer<typeof JobStatusSchema>;
186
191
  export declare const PluginsResponseSchema: z.ZodObject<{
@@ -317,7 +322,10 @@ export declare const PluginsResponseSchema: z.ZodObject<{
317
322
  /** assets skipped because an earlier run built them from the same code and inputs */
318
323
  upToDate: z.ZodNumber;
319
324
  failed: z.ZodNumber;
325
+ /** the asset that finished last */
320
326
  current: z.ZodOptional<z.ZodString>;
327
+ /** the assets being built right now (several, across builder threads) */
328
+ building: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
321
329
  notes: z.ZodArray<z.ZodString, "many">;
322
330
  failures: z.ZodArray<z.ZodObject<{
323
331
  label: z.ZodString;
@@ -347,6 +355,7 @@ export declare const PluginsResponseSchema: z.ZodObject<{
347
355
  }[];
348
356
  current?: string | undefined;
349
357
  error?: string | undefined;
358
+ building?: string[] | undefined;
350
359
  }, {
351
360
  id: number;
352
361
  done: number;
@@ -364,6 +373,7 @@ export declare const PluginsResponseSchema: z.ZodObject<{
364
373
  }[];
365
374
  current?: string | undefined;
366
375
  error?: string | undefined;
376
+ building?: string[] | undefined;
367
377
  }>>;
368
378
  }, "strip", z.ZodTypeAny, {
369
379
  plugins: {
@@ -407,6 +417,7 @@ export declare const PluginsResponseSchema: z.ZodObject<{
407
417
  }[];
408
418
  current?: string | undefined;
409
419
  error?: string | undefined;
420
+ building?: string[] | undefined;
410
421
  } | null;
411
422
  }, {
412
423
  plugins: {
@@ -450,6 +461,7 @@ export declare const PluginsResponseSchema: z.ZodObject<{
450
461
  }[];
451
462
  current?: string | undefined;
452
463
  error?: string | undefined;
464
+ building?: string[] | undefined;
453
465
  } | null;
454
466
  }>;
455
467
  export type PluginsResponse = z.infer<typeof PluginsResponseSchema>;
@@ -29,7 +29,10 @@ export const JobStatusSchema = z.object({
29
29
  /** assets skipped because an earlier run built them from the same code and inputs */
30
30
  upToDate: z.number().int(),
31
31
  failed: z.number().int(),
32
+ /** the asset that finished last */
32
33
  current: z.string().optional(),
34
+ /** the assets being built right now (several, across builder threads) */
35
+ building: z.array(z.string()).optional(),
33
36
  notes: z.array(z.string()),
34
37
  failures: z.array(z.object({ label: z.string(), error: z.string() })),
35
38
  error: z.string().optional(),