@gameslate/sdk 0.3.11 → 0.3.12

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,306 @@
1
+ import { z } from 'zod';
2
+ import { parseSupportYaml } from './game-support-yaml.js';
3
+ /*
4
+ * Per-game README support specification: YAML frontmatter + required Markdown sections, validated
5
+ * against the schema and cross-checked against the game's actual pack, live sources and asset
6
+ * extractor, plus a generator for the parent folder's summary table.
7
+ */
8
+ export const SUPPORT_TABLE_START = '<!-- gameslate:support-table:start -->';
9
+ export const SUPPORT_TABLE_END = '<!-- gameslate:support-table:end -->';
10
+ export const REQUIRED_SUPPORT_HEADINGS = [
11
+ '## Builds & Asset Extraction',
12
+ '## Map',
13
+ '## Vitals, Inventory, Missions & Reference',
14
+ '## Known Gaps',
15
+ '## Verification',
16
+ ];
17
+ export const SupportBuildSchema = z.object({
18
+ id: z.string().min(1),
19
+ label: z.string().min(1),
20
+ verification: z.enum([
21
+ 'live_played',
22
+ 'live_route',
23
+ 'tas_verified',
24
+ 'attract_only',
25
+ 'unit_only',
26
+ ]),
27
+ });
28
+ export const GameSupportSchema = z.object({
29
+ gameId: z.string().min(1),
30
+ title: z.string().min(1),
31
+ builds: z.array(SupportBuildSchema).min(1),
32
+ map: z.object({
33
+ status: z.enum(['done', 'partial', 'puzzle_panel', 'open']),
34
+ assetSource: z.enum(['local_rom', 'local_files', 'registry', 'none']),
35
+ geometry: z.enum([
36
+ '3d_mesh',
37
+ 'textured_2d',
38
+ 'vector_surfaces',
39
+ 'vector_walls',
40
+ 'route_lanes',
41
+ 'none',
42
+ ]),
43
+ layers: z.enum(['multi_floor', 'per_room', 'mode_switched', 'single', 'none']),
44
+ controls: z.object({
45
+ panZoom: z.boolean(),
46
+ rotate2d: z.boolean(),
47
+ tilt3d: z.boolean(),
48
+ }),
49
+ player: z.object({
50
+ position: z.boolean(),
51
+ heading: z.boolean(),
52
+ roomOrFloor: z.boolean(),
53
+ }),
54
+ actors: z.object({
55
+ enemies: z.enum(['tokens', 'dots', 'none']),
56
+ npcs: z.enum(['tokens', 'dots', 'none']),
57
+ rivalsOrPlayers: z.enum(['dots', 'none']),
58
+ }),
59
+ pins: z.object({
60
+ exits: z.boolean(),
61
+ collectiblesOrItems: z.boolean(),
62
+ objectives: z.boolean(),
63
+ autoHideCollected: z.boolean(),
64
+ customNotes: z.boolean(),
65
+ wayfinding: z.boolean(),
66
+ }),
67
+ }),
68
+ panels: z.object({
69
+ vitals: z.array(z.string().min(1)),
70
+ inventory: z.object({
71
+ items: z.enum(['full', 'partial', 'none']),
72
+ equipment: z.boolean(),
73
+ counters: z.boolean(),
74
+ icons: z.enum(['extracted_hd', 'glyphs', 'none']),
75
+ }),
76
+ missions: z.object({
77
+ main: z.boolean(),
78
+ side: z.boolean(),
79
+ collectibles: z.boolean(),
80
+ }),
81
+ reference: z.array(z.string().min(1)),
82
+ timelines: z.boolean(),
83
+ ai: z.object({
84
+ stateFacts: z.boolean(),
85
+ chips: z.boolean(),
86
+ curatedHints: z.boolean(),
87
+ wayfindNudges: z.boolean(),
88
+ }),
89
+ }),
90
+ });
91
+ /** Parses a per-game `<game>/README.md` into its validated `GameSupport` spec and checks required headings. */
92
+ export function parseGameSupportReadme(markdown) {
93
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/.exec(markdown);
94
+ if (!match) {
95
+ throw new Error('missing YAML frontmatter ("--- ... ---") at start of README.md');
96
+ }
97
+ const [, yamlBlock = '', body = ''] = match;
98
+ const value = parseSupportYaml(yamlBlock);
99
+ const parsed = GameSupportSchema.safeParse(value);
100
+ if (!parsed.success) {
101
+ const issues = parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ');
102
+ throw new Error(`invalid support frontmatter: ${issues}`);
103
+ }
104
+ const problems = [];
105
+ let lastPos = -1;
106
+ for (const heading of REQUIRED_SUPPORT_HEADINGS) {
107
+ const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
108
+ const hm = new RegExp(`^${escaped}\\s*$`, 'm').exec(body);
109
+ if (!hm || hm.index === undefined) {
110
+ problems.push(`missing required section "${heading}"`);
111
+ }
112
+ else if (hm.index < lastPos) {
113
+ problems.push(`section "${heading}" is out of order`);
114
+ }
115
+ else {
116
+ lastPos = hm.index;
117
+ }
118
+ }
119
+ return { support: parsed.data, body, problems };
120
+ }
121
+ function checkMapAgainstCode(support, ctx, problems) {
122
+ const hasMapCap = ctx.sources.some(s => s.capabilities.includes('map_2d'));
123
+ if ((support.map.status === 'done' || support.map.status === 'partial') && !hasMapCap) {
124
+ problems.push(`map.status is "${support.map.status}" but no source declares map_2d`);
125
+ }
126
+ if (support.map.status === 'open' && hasMapCap) {
127
+ problems.push('map.status is "open" but source already declares map_2d');
128
+ }
129
+ const needsLocal = support.map.assetSource === 'local_rom' || support.map.assetSource === 'local_files';
130
+ if (needsLocal && !ctx.hasAssetExtractor) {
131
+ problems.push(`map.assetSource is "${support.map.assetSource}" but no asset extractor is registered`);
132
+ }
133
+ if (!needsLocal && ctx.hasAssetExtractor) {
134
+ problems.push(`game has an asset extractor so map.assetSource should be local_rom or local_files`);
135
+ }
136
+ if (support.map.controls.tilt3d && support.map.geometry !== '3d_mesh') {
137
+ problems.push('map.controls.tilt3d may only be true when map.geometry is "3d_mesh"');
138
+ }
139
+ }
140
+ function checkPanelsAgainstCode(support, ctx, problems) {
141
+ const { catalogue } = ctx.pack;
142
+ const hasInvCap = ctx.sources.some(s => s.capabilities.includes('inventory'));
143
+ if (support.panels.inventory.items !== 'none' && catalogue.items.length === 0 && !hasInvCap) {
144
+ problems.push(`panels.inventory.items is "${support.panels.inventory.items}" but catalogue.items is empty and no source declares inventory`);
145
+ }
146
+ const hasObjCap = ctx.sources.some(s => s.capabilities.includes('objectives'));
147
+ const hasMain = catalogue.missions.some(m => m.group !== 'side') || hasObjCap;
148
+ const hasSide = catalogue.missions.some(m => m.group === 'side');
149
+ if (support.panels.missions.main && !hasMain) {
150
+ problems.push('panels.missions.main is true but neither main missions nor objectives capability exist');
151
+ }
152
+ if (support.panels.missions.side !== hasSide) {
153
+ problems.push(`panels.missions.side (${support.panels.missions.side}) disagrees with side missions in catalogue (${hasSide})`);
154
+ }
155
+ if (support.panels.missions.collectibles !== catalogue.collectibles.length > 0) {
156
+ problems.push(`panels.missions.collectibles (${support.panels.missions.collectibles}) disagrees with catalogue.collectibles (${catalogue.collectibles.length})`);
157
+ }
158
+ const actualRef = catalogue.reference.map(r => r.id);
159
+ if (support.panels.reference.join(',') !== actualRef.join(',')) {
160
+ problems.push(`panels.reference [${support.panels.reference.join(', ')}] != catalogue.reference [${actualRef.join(', ')}]`);
161
+ }
162
+ if (ctx.hasTimelines !== undefined && support.panels.timelines !== ctx.hasTimelines) {
163
+ problems.push(`panels.timelines (${support.panels.timelines}) != Boolean(pack.ui?.timelines) (${ctx.hasTimelines})`);
164
+ }
165
+ if (support.panels.ai.chips !== catalogue.chips.length > 0) {
166
+ problems.push(`panels.ai.chips (${support.panels.ai.chips}) != catalogue.chips (${catalogue.chips.length > 0})`);
167
+ }
168
+ }
169
+ /** Verifies that a game's README support spec agrees with its actual pack, sources, and extractor. */
170
+ export function checkSupportAgainstCode(support, ctx) {
171
+ const problems = [];
172
+ if (support.gameId !== ctx.pack.id) {
173
+ problems.push(`gameId "${support.gameId}" != pack.id "${ctx.pack.id}"`);
174
+ }
175
+ const actualBuilds = new Set();
176
+ for (const s of ctx.sources) {
177
+ for (const id of s.supportedBuildIds.keys())
178
+ actualBuilds.add(id);
179
+ }
180
+ const docBuilds = new Set(support.builds.map(b => b.id));
181
+ for (const b of actualBuilds) {
182
+ if (!docBuilds.has(b))
183
+ problems.push(`source build "${b}" is missing from README builds`);
184
+ }
185
+ for (const b of docBuilds) {
186
+ if (!actualBuilds.has(b))
187
+ problems.push(`README build "${b}" is not in supportedBuildIds`);
188
+ }
189
+ checkMapAgainstCode(support, ctx, problems);
190
+ checkPanelsAgainstCode(support, ctx, problems);
191
+ return problems;
192
+ }
193
+ const VERIFY_BADGE = {
194
+ live_played: 'live',
195
+ live_route: 'live route',
196
+ tas_verified: 'TAS',
197
+ attract_only: 'attract',
198
+ unit_only: 'unit',
199
+ };
200
+ const GEOM_LABEL = {
201
+ '3d_mesh': '3D mesh + 2D',
202
+ textured_2d: 'Textured 2D',
203
+ vector_surfaces: '2D surfaces',
204
+ vector_walls: '2D walls',
205
+ route_lanes: '2D lanes',
206
+ none: '—',
207
+ };
208
+ const LAYER_LABEL = {
209
+ multi_floor: 'multi-floor',
210
+ per_room: 'per-room',
211
+ mode_switched: 'per-mode',
212
+ single: 'single',
213
+ none: '',
214
+ };
215
+ function mapControlsCell(m) {
216
+ const parts = [
217
+ m.controls.panZoom ? 'pan/zoom' : '',
218
+ m.controls.rotate2d ? '2D rotate' : '',
219
+ m.controls.tilt3d ? '3D tilt' : '',
220
+ ].filter(Boolean);
221
+ return parts.length > 0 ? parts.join(', ') : '—';
222
+ }
223
+ function liveMapCell(m) {
224
+ const parts = [];
225
+ if (m.player.position) {
226
+ const detail = [
227
+ m.player.heading ? 'heading' : '',
228
+ m.player.roomOrFloor ? 'room' : '',
229
+ ].filter(Boolean);
230
+ parts.push(detail.length ? `player (${detail.join('+')})` : 'player');
231
+ }
232
+ if (m.actors.enemies !== 'none')
233
+ parts.push(`enemies (${m.actors.enemies})`);
234
+ if (m.actors.npcs !== 'none')
235
+ parts.push(`NPCs (${m.actors.npcs})`);
236
+ if (m.actors.rivalsOrPlayers !== 'none')
237
+ parts.push('rivals/players');
238
+ return parts.length > 0 ? parts.join(', ') : '—';
239
+ }
240
+ function pinsCell(p) {
241
+ const parts = [
242
+ p.exits ? 'exits' : '',
243
+ p.collectiblesOrItems ? 'items' : '',
244
+ p.objectives ? 'objectives' : '',
245
+ p.autoHideCollected ? 'auto-hide' : '',
246
+ p.wayfinding ? 'wayfind' : '',
247
+ p.customNotes ? 'notes' : '',
248
+ ].filter(Boolean);
249
+ return parts.length > 0 ? parts.join(', ') : '—';
250
+ }
251
+ function invMissionsCell(panels) {
252
+ const inv = [
253
+ panels.inventory.items !== 'none' ? `items (${panels.inventory.items})` : '',
254
+ panels.inventory.equipment ? 'gear' : '',
255
+ panels.inventory.icons === 'extracted_hd' ? 'HD icons' : '',
256
+ ].filter(Boolean);
257
+ const mis = [
258
+ panels.missions.main ? 'main' : '',
259
+ panels.missions.side ? 'side' : '',
260
+ panels.missions.collectibles ? 'collectibles' : '',
261
+ ].filter(Boolean);
262
+ const left = inv.length ? inv.join('+') : panels.inventory.counters ? 'counters' : '—';
263
+ const right = mis.length ? `missions (${mis.join('+')})` : 'no missions';
264
+ return `${left}; ${right}`;
265
+ }
266
+ function refAiCell(panels) {
267
+ const parts = [
268
+ panels.reference.length > 0 ? `ref (${panels.reference.length})` : '',
269
+ panels.timelines ? 'timeline' : '',
270
+ panels.ai.chips ? 'chips' : '',
271
+ panels.ai.curatedHints ? 'hints' : '',
272
+ panels.ai.wayfindNudges ? 'wayfind UI' : '',
273
+ ].filter(Boolean);
274
+ return parts.length > 0 ? parts.join(', ') : '—';
275
+ }
276
+ const shortBuildId = (id) => /^[0-9a-f]{16,}$/i.test(id) ? `${id.slice(0, 8)}…` : id;
277
+ /** Renders a standard Markdown support table from a list of per-game support entries. */
278
+ export function renderSupportTable(entries) {
279
+ const header = [
280
+ '| Game | Builds | Map & Layers | Camera | Live on Map | Pins & Wayfind | Inventory & Missions | Ref & AI |',
281
+ '|---|---|---|---|---|---|---|---|',
282
+ ];
283
+ const rows = entries.map(({ support: s, readmeRelPath }) => {
284
+ const builds = s.builds
285
+ .map(b => `\`${shortBuildId(b.id)}\` (${VERIFY_BADGE[b.verification]})`)
286
+ .join(', ');
287
+ const layer = LAYER_LABEL[s.map.layers];
288
+ const mapCol = s.map.status === 'done' || s.map.status === 'partial'
289
+ ? `${GEOM_LABEL[s.map.geometry]}${layer ? ` · ${layer}` : ''}`
290
+ : s.map.status === 'puzzle_panel'
291
+ ? 'puzzle (n/a)'
292
+ : `_${s.map.status}_`;
293
+ return `| [${s.title}](${readmeRelPath}) | ${builds} | ${mapCol} | ${mapControlsCell(s.map)} | ${liveMapCell(s.map)} | ${pinsCell(s.map.pins)} | ${invMissionsCell(s.panels)} | ${refAiCell(s.panels)} |`;
294
+ });
295
+ return [...header, ...rows].join('\n');
296
+ }
297
+ /** Replaces the region between SUPPORT_TABLE_START and SUPPORT_TABLE_END in a top-level README. */
298
+ export function spliceSupportTable(readmeMarkdown, entries) {
299
+ const startIdx = readmeMarkdown.indexOf(SUPPORT_TABLE_START);
300
+ const endIdx = readmeMarkdown.indexOf(SUPPORT_TABLE_END);
301
+ if (startIdx < 0 || endIdx < 0 || endIdx < startIdx) {
302
+ throw new Error(`README is missing ${SUPPORT_TABLE_START} ... ${SUPPORT_TABLE_END} markers`);
303
+ }
304
+ const table = renderSupportTable(entries);
305
+ return `${readmeMarkdown.slice(0, startIdx + SUPPORT_TABLE_START.length)}\n\n${table}\n\n${readmeMarkdown.slice(endIdx)}`;
306
+ }
@@ -24,6 +24,27 @@ export declare const AddressSpecSchema: z.ZodObject<{
24
24
  binary?: string | undefined;
25
25
  }>;
26
26
  symbols: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
27
+ /** file-static variables, which IDO leaves out of the ld map and the object's symbol table:
28
+ * each is its object's section base (from the ld map) plus the offset the code that reads it
29
+ * shows (`objdump -dr` on an accessor: `lui/addiu` against `.bss` + offset). Say which
30
+ * accessor in `evidence`. */
31
+ statics: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
32
+ /** the object as the ld map names it, e.g. `build/us.v10/src/core2/playerposition.c.o` */
33
+ object: z.ZodString;
34
+ section: z.ZodDefault<z.ZodEnum<[".bss", ".data", ".rodata", ".sbss", ".sdata"]>>;
35
+ offset: z.ZodPipeline<z.ZodUnion<[z.ZodNumber, z.ZodEffects<z.ZodString, number, string>]>, z.ZodNumber>;
36
+ evidence: z.ZodString;
37
+ }, "strip", z.ZodTypeAny, {
38
+ object: string;
39
+ section: ".bss" | ".data" | ".rodata" | ".sbss" | ".sdata";
40
+ offset: number;
41
+ evidence: string;
42
+ }, {
43
+ object: string;
44
+ offset: string | number;
45
+ evidence: string;
46
+ section?: ".bss" | ".data" | ".rodata" | ".sbss" | ".sdata" | undefined;
47
+ }>>>;
27
48
  /** `Type.field.path` (a type may be `struct Name`) */
28
49
  offsets: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
29
50
  sizes: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
@@ -45,6 +66,12 @@ export declare const AddressSpecSchema: z.ZodObject<{
45
66
  args: string[];
46
67
  };
47
68
  symbols: string[];
69
+ statics: Record<string, {
70
+ object: string;
71
+ section: ".bss" | ".data" | ".rodata" | ".sbss" | ".sdata";
72
+ offset: number;
73
+ evidence: string;
74
+ }>;
48
75
  offsets: string[];
49
76
  sizes: string[];
50
77
  constants: Record<string, string>;
@@ -60,6 +87,12 @@ export declare const AddressSpecSchema: z.ZodObject<{
60
87
  subtract?: string | number | undefined;
61
88
  stubHeaders?: string[] | undefined;
62
89
  symbols?: string[] | undefined;
90
+ statics?: Record<string, {
91
+ object: string;
92
+ offset: string | number;
93
+ evidence: string;
94
+ section?: ".bss" | ".data" | ".rodata" | ".sbss" | ".sdata" | undefined;
95
+ }> | undefined;
63
96
  offsets?: string[] | undefined;
64
97
  sizes?: string[] | undefined;
65
98
  constants?: Record<string, string> | undefined;
@@ -68,6 +101,13 @@ export declare const AddressSpecSchema: z.ZodObject<{
68
101
  export type AddressSpec = z.infer<typeof AddressSpecSchema>;
69
102
  /** Symbols from an ld map (` 0x800dc50c gGamestate`) or a splat file (`gGameState = 0x80177834;`). */
70
103
  export declare function parseSymbolFile(text: string): Map<string, number>;
104
+ export interface SectionPlacement {
105
+ base: number;
106
+ size: number;
107
+ }
108
+ /** Where an ld map put each object's sections: `build/x.c.o(.bss)` to every placement listed
109
+ * (a section can appear more than once; a static may use it only when it appears once). */
110
+ export declare function parseSectionBases(text: string): Map<string, SectionPlacement[]>;
71
111
  /** How much of a decomp's symbol map names the game itself: the triage before writing a reader
72
112
  * (a byte-identical decomp can still name nothing past boot code, like Yoshi's Story's). */
73
113
  export declare function triageNames(symbols: ReadonlyMap<string, number>): {
@@ -30,6 +30,19 @@ export const AddressSpecSchema = z.object({
30
30
  /** clang's arguments besides the probe itself (target, ABI, defines, include paths) */
31
31
  clang: z.object({ binary: z.string().default('clang-18'), args: z.array(z.string()) }),
32
32
  symbols: z.array(z.string()).default([]),
33
+ /** file-static variables, which IDO leaves out of the ld map and the object's symbol table:
34
+ * each is its object's section base (from the ld map) plus the offset the code that reads it
35
+ * shows (`objdump -dr` on an accessor: `lui/addiu` against `.bss` + offset). Say which
36
+ * accessor in `evidence`. */
37
+ statics: z
38
+ .record(z.string(), z.object({
39
+ /** the object as the ld map names it, e.g. `build/us.v10/src/core2/playerposition.c.o` */
40
+ object: z.string(),
41
+ section: z.enum(['.bss', '.data', '.rodata', '.sbss', '.sdata']).default('.bss'),
42
+ offset: Hex.pipe(z.number().int().nonnegative()),
43
+ evidence: z.string().min(1),
44
+ }))
45
+ .default({}),
33
46
  /** `Type.field.path` (a type may be `struct Name`) */
34
47
  offsets: z.array(z.string()).default([]),
35
48
  sizes: z.array(z.string()).default([]),
@@ -58,6 +71,27 @@ export function parseSymbolFile(text) {
58
71
  }
59
72
  return out;
60
73
  }
74
+ const LD_SECTION_LINE = /^\s*(\.[a-z]+)\s+0x([0-9a-fA-F]{8,16})\s+0x([0-9a-fA-F]+)\s+(\S+)\s*$/;
75
+ /** Where an ld map put each object's sections: `build/x.c.o(.bss)` to every placement listed
76
+ * (a section can appear more than once; a static may use it only when it appears once). */
77
+ export function parseSectionBases(text) {
78
+ const out = new Map();
79
+ for (const line of text.split('\n')) {
80
+ const m = LD_SECTION_LINE.exec(line);
81
+ if (!m?.[1] || !m[2] || !m[3] || !m[4])
82
+ continue;
83
+ const key = `${m[4]}(${m[1]})`;
84
+ const placement = {
85
+ base: Number.parseInt(m[2].slice(-8), 16),
86
+ size: Number.parseInt(m[3], 16),
87
+ };
88
+ /* ld also lists empty input sections (often at 0): they hold nothing, so no static is there */
89
+ if (placement.size === 0)
90
+ continue;
91
+ out.set(key, [...(out.get(key) ?? []), placement]);
92
+ }
93
+ return out;
94
+ }
61
95
  /* splat's and m2c's placeholders for unnamed code and data */
62
96
  const PLACEHOLDER = /^(func|D|B|jtbl|L|lbl|sub|unk|RO|dlabel|jlabel)_[0-9A-Fa-f]+/;
63
97
  /* libultra, the audio library and the compiler runtime: named, but not the game */
@@ -134,17 +168,39 @@ export function parseProbeAssembly(asm, count) {
134
168
  return v;
135
169
  });
136
170
  }
171
+ /** Each file-static at its object's section base plus the accessor's offset, into `known`. */
172
+ function placeStatics(spec, sections, known) {
173
+ for (const [name, st] of Object.entries(spec.statics)) {
174
+ const placements = sections.get(`${st.object}(${st.section})`) ?? [];
175
+ const [placement] = placements;
176
+ if (!placement)
177
+ throw new Error(`static ${name}: no ${st.section} for ${st.object} in ${spec.symbolFiles.join(', ')}`);
178
+ if (placements.length > 1)
179
+ throw new Error(`static ${name}: ${st.object}(${st.section}) is placed ${placements.length} times in the maps`);
180
+ if (st.offset >= placement.size)
181
+ throw new Error(`static ${name}: offset ${hex(st.offset)} is past ${st.object}(${st.section})'s ${hex(placement.size)} bytes`);
182
+ if (known.has(name))
183
+ throw new Error(`static ${name} is also a mapped symbol: list it under symbols`);
184
+ known.set(name, placement.base + st.offset);
185
+ }
186
+ }
137
187
  /** The table a spec names; throws on any symbol the maps don't have or value clang didn't fold. */
138
188
  export function buildAddressTable(spec, effects) {
139
189
  const known = new Map();
140
- for (const f of spec.symbolFiles)
141
- for (const [k, v] of parseSymbolFile(effects.read(f)))
190
+ const sections = new Map();
191
+ for (const f of spec.symbolFiles) {
192
+ const text = effects.read(f);
193
+ for (const [k, v] of parseSymbolFile(text))
142
194
  known.set(k, v);
195
+ for (const [k, v] of parseSectionBases(text))
196
+ sections.set(k, [...(sections.get(k) ?? []), ...v]);
197
+ }
198
+ placeStatics(spec, sections, known);
143
199
  const missing = spec.symbols.filter(s => !known.has(s));
144
200
  if (missing.length)
145
201
  throw new Error(`not in ${spec.symbolFiles.join(', ')}: ${missing.join(', ')}`);
146
202
  const table = { symbols: {}, offsets: {}, sizes: {}, constants: {} };
147
- for (const s of spec.symbols)
203
+ for (const s of [...spec.symbols, ...Object.keys(spec.statics)])
148
204
  table.symbols[s] = ((known.get(s) ?? 0) - spec.subtract) >>> 0;
149
205
  const entries = probeEntries(spec);
150
206
  if (entries.length) {
@@ -0,0 +1,27 @@
1
+ import { type GameSupport, type SupportCodeContext } from '../game-support.js';
2
+ import type { InspectedPlugin } from './inspect.js';
3
+ export interface LoadedSupportEntry {
4
+ gameId: string;
5
+ filePath: string;
6
+ readmeRelPath: string;
7
+ support: GameSupport;
8
+ }
9
+ export interface VerifySupportOptions {
10
+ /** Directory holding `<gameId>/README.md` subfolders (or `README.md` for a single-game folder). */
11
+ gamesDir: string;
12
+ /** Top-level README containing `<!-- gameslate:support-table:start/end -->` markers. */
13
+ topReadmePath: string;
14
+ /** Optional gameIds expected (e.g. from `manifest.games`); defaults to subfolders with README.md. */
15
+ expectedGameIds?: readonly string[];
16
+ /** Optional code contexts keyed by gameId to cross-check frontmatter against live code. */
17
+ codeByGame?: ReadonlyMap<string, SupportCodeContext>;
18
+ /** When true, writes the updated table to `topReadmePath` instead of failing if out of date. */
19
+ write?: boolean;
20
+ }
21
+ /** Builds `SupportCodeContext` map from an `InspectedPlugin` loaded by `inspectPlugin`. */
22
+ export declare function supportContextsFromPlugin(inspected: InspectedPlugin): Map<string, SupportCodeContext>;
23
+ /** Validates every per-game README under `gamesDir` and checks or updates `topReadmePath`. */
24
+ export declare function verifyOrWriteSupportDocs(opts: VerifySupportOptions): {
25
+ entries: LoadedSupportEntry[];
26
+ problems: string[];
27
+ };
@@ -0,0 +1,101 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { checkSupportAgainstCode, parseGameSupportReadme, spliceSupportTable, } from '../game-support.js';
4
+ function locateGameReadme(gamesDir, gameId, singleFallback) {
5
+ const sub = path.join(gamesDir, gameId, 'README.md');
6
+ if (fs.existsSync(sub))
7
+ return sub;
8
+ if (singleFallback) {
9
+ const direct = path.join(gamesDir, 'README.md');
10
+ if (fs.existsSync(direct))
11
+ return direct;
12
+ }
13
+ return null;
14
+ }
15
+ function discoverGameIds(gamesDir) {
16
+ return fs
17
+ .readdirSync(gamesDir, { withFileTypes: true })
18
+ .filter(d => d.isDirectory() && fs.existsSync(path.join(gamesDir, d.name, 'README.md')))
19
+ .map(d => d.name)
20
+ .sort();
21
+ }
22
+ /** Builds `SupportCodeContext` map from an `InspectedPlugin` loaded by `inspectPlugin`. */
23
+ export function supportContextsFromPlugin(inspected) {
24
+ const assetGames = new Set(inspected.assets?.games ?? []);
25
+ const map = new Map();
26
+ for (const pack of inspected.live.packs) {
27
+ const sources = inspected.live.sources.filter(s => s.gameId === pack.id);
28
+ map.set(pack.id, {
29
+ pack,
30
+ sources,
31
+ hasAssetExtractor: assetGames.has(pack.id),
32
+ });
33
+ }
34
+ return map;
35
+ }
36
+ function loadOneSupportEntry(gameId, filePath, topDir, ctx) {
37
+ const problems = [];
38
+ const rel = path.relative(topDir, filePath).split(path.sep).join('/');
39
+ try {
40
+ const parsed = parseGameSupportReadme(fs.readFileSync(filePath, 'utf8'));
41
+ if (parsed.support.gameId !== gameId) {
42
+ problems.push(`${rel}: frontmatter gameId "${parsed.support.gameId}" != folder "${gameId}"`);
43
+ }
44
+ for (const p of parsed.problems)
45
+ problems.push(`${rel}: ${p}`);
46
+ if (ctx) {
47
+ for (const p of checkSupportAgainstCode(parsed.support, ctx))
48
+ problems.push(`${rel}: ${p}`);
49
+ }
50
+ return {
51
+ entry: { gameId, filePath, readmeRelPath: rel, support: parsed.support },
52
+ problems,
53
+ };
54
+ }
55
+ catch (e) {
56
+ problems.push(`${rel}: ${e instanceof Error ? e.message : String(e)}`);
57
+ return { entry: null, problems };
58
+ }
59
+ }
60
+ function syncSupportTable(topReadmePath, entries, write, problems) {
61
+ const current = fs.readFileSync(topReadmePath, 'utf8');
62
+ try {
63
+ const next = spliceSupportTable(current, entries);
64
+ if (next === current)
65
+ return;
66
+ if (write) {
67
+ fs.writeFileSync(topReadmePath, next);
68
+ }
69
+ else {
70
+ problems.push(`${path.basename(topReadmePath)}: support table is out of date (rerun with --write to regenerate)`);
71
+ }
72
+ }
73
+ catch (e) {
74
+ problems.push(`${path.basename(topReadmePath)}: ${e instanceof Error ? e.message : String(e)}`);
75
+ }
76
+ }
77
+ /** Validates every per-game README under `gamesDir` and checks or updates `topReadmePath`. */
78
+ export function verifyOrWriteSupportDocs(opts) {
79
+ const topDir = path.dirname(path.resolve(opts.topReadmePath));
80
+ const gameIds = opts.expectedGameIds
81
+ ? [...opts.expectedGameIds]
82
+ : discoverGameIds(opts.gamesDir);
83
+ const singleFallback = gameIds.length === 1;
84
+ const entries = [];
85
+ const problems = [];
86
+ for (const gameId of gameIds) {
87
+ const filePath = locateGameReadme(opts.gamesDir, gameId, singleFallback);
88
+ if (!filePath) {
89
+ problems.push(`${gameId}: missing README.md in ${path.join(opts.gamesDir, gameId)}`);
90
+ continue;
91
+ }
92
+ const loaded = loadOneSupportEntry(gameId, filePath, topDir, opts.codeByGame?.get(gameId));
93
+ problems.push(...loaded.problems);
94
+ if (loaded.entry)
95
+ entries.push(loaded.entry);
96
+ }
97
+ if (problems.length === 0) {
98
+ syncSupportTable(opts.topReadmePath, entries, Boolean(opts.write), problems);
99
+ }
100
+ return { entries, problems };
101
+ }
@@ -5,3 +5,4 @@ export * from './inspect.js';
5
5
  export * from './verify.js';
6
6
  export * from './addresses.js';
7
7
  export * from './udp-ports.js';
8
+ export * from './game-support.js';
package/lib/host/index.js CHANGED
@@ -9,3 +9,4 @@ export * from './inspect.js';
9
9
  export * from './verify.js';
10
10
  export * from './addresses.js';
11
11
  export * from './udp-ports.js';
12
+ export * from './game-support.js';
@@ -20,6 +20,7 @@ export declare class PluginSandbox {
20
20
  private readonly log;
21
21
  private readonly now;
22
22
  private readonly memories;
23
+ private readonly sessionGames;
23
24
  private nextHandle;
24
25
  private readonly viewsCache;
25
26
  constructor(quickJs: QuickJSWASMModule, code: string, name: string, opts: {
@@ -36,6 +36,7 @@ export class PluginSandbox {
36
36
  log;
37
37
  now;
38
38
  memories = new Map();
39
+ sessionGames = new Map();
39
40
  nextHandle = 1;
40
41
  /* each state's views, so a pack's three view accessors cost one call */
41
42
  viewsCache = new WeakMap();
@@ -72,6 +73,7 @@ export class PluginSandbox {
72
73
  this.restarts.push(now);
73
74
  this.guest.dispose();
74
75
  this.memories.clear();
76
+ this.sessionGames.clear();
75
77
  this.guest = this.newGuest();
76
78
  this.log(`[plugins] ${this.name}: restarted after breaking a sandbox limit`);
77
79
  }
@@ -124,6 +126,7 @@ export class PluginSandbox {
124
126
  this.restartIfSwitchedOff();
125
127
  const handle = this.nextHandle++;
126
128
  this.memories.set(handle, memory);
129
+ this.sessionGames.set(handle, { gameId, lastLog: null });
127
130
  const info = {
128
131
  buildId: memory.buildId,
129
132
  commandLine: [...memory.commandLine],
@@ -138,6 +141,7 @@ export class PluginSandbox {
138
141
  }
139
142
  if (!started) {
140
143
  this.memories.delete(handle);
144
+ this.sessionGames.delete(handle);
141
145
  return null;
142
146
  }
143
147
  let lastProblem = null;
@@ -167,6 +171,7 @@ export class PluginSandbox {
167
171
  }
168
172
  finally {
169
173
  this.memories.delete(handle);
174
+ this.sessionGames.delete(handle);
170
175
  }
171
176
  },
172
177
  };
@@ -236,6 +241,20 @@ export class PluginSandbox {
236
241
  const at = memory.scan(sig);
237
242
  return at === null ? vm().null : vm().newString(at.toString());
238
243
  },
244
+ log: (handle, message) => {
245
+ const meta = this.sessionGames.get(vm().getNumber(handle));
246
+ if (!meta)
247
+ return;
248
+ const clean = vm()
249
+ .getString(message)
250
+ .replace(/[\r\n]+/g, ' ')
251
+ .slice(0, 500);
252
+ if (!clean || clean === meta.lastLog)
253
+ return;
254
+ meta.lastLog = clean;
255
+ this.log(`[plugins] ${this.name}: ${meta.gameId}: ${clean}`);
256
+ this.memories.get(vm().getNumber(handle))?.log?.(clean);
257
+ },
239
258
  };
240
259
  }
241
260
  }