vibedgames 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +17 -8
  2. package/assets/align-framing.py +242 -0
  3. package/assets/render-model.py +406 -0
  4. package/assets/tilemap-editor.html +630 -0
  5. package/dist/THIRD_PARTY_NOTICES.txt +59 -7
  6. package/dist/chunk-2KVQJKIZ.js +6495 -0
  7. package/dist/chunk-2SBBKY5C.js +16993 -0
  8. package/dist/chunk-2ZKS7V72.js +170 -0
  9. package/dist/{chunk-RAUJA3OY.js → chunk-3HGBIUM5.js} +21 -18
  10. package/dist/chunk-3UGGMFJJ.js +22 -0
  11. package/dist/{chunk-I6O4HIDY.js → chunk-42K3BJJH.js} +163 -131
  12. package/dist/chunk-43P4U7CB.js +104 -0
  13. package/dist/chunk-4FJXCS3K.js +741 -0
  14. package/dist/{chunk-NC5XCGYU.js → chunk-4UU622RK.js} +6 -5
  15. package/dist/{chunk-2QBYTIMH.js → chunk-5535KDYI.js} +1 -1
  16. package/dist/chunk-5YPLKGY3.js +87 -0
  17. package/dist/chunk-6KXXZXSO.js +475 -0
  18. package/dist/chunk-7RPLQWR2.js +91 -0
  19. package/dist/{chunk-C2IRIRAA.js → chunk-A556KALN.js} +15 -14
  20. package/dist/{chunk-N3XAUFKH.js → chunk-ABTUEIRC.js} +576 -301
  21. package/dist/{chunk-PEUP4MZR.js → chunk-AWJNAGPE.js} +6 -3
  22. package/dist/{chunk-QGEITHUP.js → chunk-BN3Q7UEC.js} +22 -19
  23. package/dist/chunk-BZOMEG3X.js +412 -0
  24. package/dist/{chunk-ZYCSYJWX.js → chunk-COSLGSVO.js} +14 -24
  25. package/dist/{chunk-PQDBCZRT.js → chunk-CTY2WZQK.js} +204 -158
  26. package/dist/{chunk-CU7UY5YJ.js → chunk-D2RF35HJ.js} +1 -1
  27. package/dist/chunk-DB7WVFS7.js +80 -0
  28. package/dist/chunk-DOOQUFPG.js +73 -0
  29. package/dist/chunk-E3FJUPLT.js +177 -0
  30. package/dist/chunk-E7NDOZ27.js +428 -0
  31. package/dist/chunk-F42QKWBB.js +39 -0
  32. package/dist/chunk-FXXVXDTW.js +168 -0
  33. package/dist/{chunk-VFFOT7KD.js → chunk-G66HRVDW.js} +1 -1
  34. package/dist/{chunk-CAKBGDCY.js → chunk-GKDUYJ7R.js} +5 -0
  35. package/dist/chunk-GLEW7VJQ.js +45 -0
  36. package/dist/{chunk-MGIASPED.js → chunk-H2C4QUTG.js} +9 -8
  37. package/dist/{chunk-HCMTSR7E.js → chunk-HRKVAXNN.js} +21 -17
  38. package/dist/{chunk-TLRL6FHW.js → chunk-HSMG6U7J.js} +10 -9
  39. package/dist/chunk-HX5Q63UA.js +48 -0
  40. package/dist/chunk-HYOXGNWS.js +53 -0
  41. package/dist/chunk-I5LELJSK.js +22 -0
  42. package/dist/{chunk-6FZPPUQH.js → chunk-JN4WZCR7.js} +5 -4
  43. package/dist/{chunk-QJZ72MSY.js → chunk-K36EOII3.js} +7 -6
  44. package/dist/chunk-KAGVI3CE.js +62 -0
  45. package/dist/chunk-KJK5CB6E.js +58 -0
  46. package/dist/chunk-KLFBAFXD.js +25 -0
  47. package/dist/{chunk-7MKUR7Y3.js → chunk-LONQWRTR.js} +112 -81
  48. package/dist/chunk-LORGE2NB.js +2484 -0
  49. package/dist/{chunk-HKA5LBYW.js → chunk-MEAO33XW.js} +22 -19
  50. package/dist/{chunk-PM5UOIKR.js → chunk-MR5KIFI7.js} +22 -21
  51. package/dist/{chunk-GCX5KQ6A.js → chunk-N2UHAQXC.js} +18 -11
  52. package/dist/chunk-NCX6LYNJ.js +117 -0
  53. package/dist/chunk-OGX4DKIS.js +215 -0
  54. package/dist/chunk-OPUCUUID.js +41 -0
  55. package/dist/chunk-Q2QC6KAZ.js +132 -0
  56. package/dist/{chunk-2GL2WJZX.js → chunk-Q3XQPNF6.js} +14 -14
  57. package/dist/{chunk-RYFO3ZPO.js → chunk-Q5NZNXJE.js} +15 -12
  58. package/dist/{chunk-JT2AU24K.js → chunk-QARXJGI5.js} +1 -1
  59. package/dist/chunk-QLCVLCPM.js +126 -0
  60. package/dist/chunk-R2WVORGD.js +91 -0
  61. package/dist/chunk-RKS7SI5L.js +64 -0
  62. package/dist/{chunk-4BGCA3W7.js → chunk-RPJR3S5S.js} +32 -18
  63. package/dist/chunk-RPSUFZAG.js +3307 -0
  64. package/dist/chunk-RRI23NK2.js +40 -0
  65. package/dist/chunk-S7HYWITX.js +57 -0
  66. package/dist/chunk-SBXCK2I2.js +48 -0
  67. package/dist/chunk-SUSX3QIA.js +62 -0
  68. package/dist/{chunk-PHEDW6C7.js → chunk-SXYQL4GK.js} +16 -7
  69. package/dist/{chunk-ZI6PKVXG.js → chunk-TMPBGXT4.js} +6 -5
  70. package/dist/chunk-TXOE5UY5.js +72 -0
  71. package/dist/chunk-U6DTE5IX.js +124 -0
  72. package/dist/chunk-UPHB5HWO.js +115 -0
  73. package/dist/chunk-UQ7VO6B3.js +91 -0
  74. package/dist/chunk-VB4WLJR2.js +47 -0
  75. package/dist/{chunk-FNYBZNW2.js → chunk-VIEKOGKG.js} +21 -3
  76. package/dist/{chunk-QIVCBUYD.js → chunk-VZEJ2ZHE.js} +18 -18
  77. package/dist/chunk-X75Y7LUW.js +126 -0
  78. package/dist/{chunk-Z4Z24FWO.js → chunk-YNCYMWER.js} +8 -5
  79. package/dist/chunk-ZHLPE6LI.js +71 -0
  80. package/dist/index.js +48 -34
  81. package/package.json +32 -16
  82. package/templates/none/src/main.ts +4 -0
  83. package/templates/none/vite.config.ts +0 -2
  84. package/templates/phaser/src/main.ts +0 -1
  85. package/templates/phaser/src/scenes/game-scene.ts +10 -8
  86. package/templates/phaser/vite.config.ts +0 -2
  87. package/templates/react-r3f/src/app.tsx +3 -1
  88. package/templates/react-r3f/src/main.tsx +1 -0
  89. package/templates/react-r3f/vite.config.ts +0 -2
  90. package/templates/threejs/src/main.ts +10 -1
  91. package/templates/threejs/vite.config.ts +0 -2
  92. package/LICENSE +0 -21
  93. package/dist/chunk-AYJQVZXY.js +0 -39
  94. package/dist/chunk-J6PKNPI2.js +0 -26
  95. package/dist/chunk-MJQSHP3Y.js +0 -415
  96. package/dist/chunk-MYFLYNPO.js +0 -68
@@ -0,0 +1,741 @@
1
+ import { createRequire as __createRequire } from "node:module";
2
+ import { dirname as __pathDirname } from "node:path";
3
+ import { fileURLToPath as __fileURLToPath } from "node:url";
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import {
8
+ isFiniteJsonNumber,
9
+ isJsonObject,
10
+ isJsonString,
11
+ parseJsonText
12
+ } from "./chunk-2KVQJKIZ.js";
13
+ import "./chunk-2SBBKY5C.js";
14
+ import "./chunk-GKDUYJ7R.js";
15
+
16
+ // src/checks/scripted-playtest.ts
17
+ import { readFileSync } from "node:fs";
18
+
19
+ // src/checks/scripted-harness.ts
20
+ import { spawnSync } from "node:child_process";
21
+ var isJsonBoolean = (v) => v === true || v === false;
22
+ var HARNESS_FAILURE = 2;
23
+ var vgEntry = process.argv[1] ?? "vg";
24
+ var programName = "playtest";
25
+ var setProgramName = (name) => {
26
+ programName = name;
27
+ };
28
+ var SAMPLE_MS = 40;
29
+ var MOVEMENT_CODES = /* @__PURE__ */ new Set([
30
+ "KeyW",
31
+ "KeyA",
32
+ "KeyS",
33
+ "KeyD",
34
+ "ArrowUp",
35
+ "ArrowLeft",
36
+ "ArrowDown",
37
+ "ArrowRight"
38
+ ]);
39
+ var held = null;
40
+ var claimHeld = (inputs) => {
41
+ held = inputs;
42
+ };
43
+ var disownHeld = () => {
44
+ held = null;
45
+ };
46
+ var releaseHeldInputs = () => {
47
+ const inputs = held;
48
+ held = null;
49
+ if (inputs === null) {
50
+ return;
51
+ }
52
+ const parts = [
53
+ "clearInterval(window.__BOT_TICK__);",
54
+ ...keyParts("keyup", inputs.keys ?? []),
55
+ ...pointerParts(inputs.pointer, "up")
56
+ ];
57
+ spawnSync(
58
+ process.execPath,
59
+ [vgEntry, "playtest", "eval", `(() => { ${parts.join("\n")}
60
+ return true; })()`],
61
+ {
62
+ encoding: "utf-8",
63
+ timeout: 3e4
64
+ }
65
+ );
66
+ };
67
+ for (const signal of ["SIGINT", "SIGTERM"]) {
68
+ process.on(signal, () => {
69
+ releaseHeldInputs();
70
+ process.exit(HARNESS_FAILURE);
71
+ });
72
+ }
73
+ var fail = (message) => {
74
+ releaseHeldInputs();
75
+ console.error(`${programName}: ${message}`);
76
+ process.exit(HARNESS_FAILURE);
77
+ };
78
+ var NAMED_KEYS = {
79
+ AltLeft: 18,
80
+ AltRight: 18,
81
+ ArrowDown: 40,
82
+ ArrowLeft: 37,
83
+ ArrowRight: 39,
84
+ ArrowUp: 38,
85
+ Backquote: 192,
86
+ Backslash: 220,
87
+ Backspace: 8,
88
+ BracketLeft: 219,
89
+ BracketRight: 221,
90
+ Comma: 188,
91
+ ControlLeft: 17,
92
+ ControlRight: 17,
93
+ Delete: 46,
94
+ Enter: 13,
95
+ Equal: 187,
96
+ Escape: 27,
97
+ Minus: 189,
98
+ Period: 190,
99
+ Quote: 222,
100
+ Semicolon: 186,
101
+ ShiftLeft: 16,
102
+ ShiftRight: 16,
103
+ Slash: 191,
104
+ Space: 32,
105
+ Tab: 9
106
+ };
107
+ var NAMED_VALUES = new Map(
108
+ Object.entries({
109
+ AltLeft: "Alt",
110
+ AltRight: "Alt",
111
+ Backquote: "`",
112
+ Backslash: "\\",
113
+ BracketLeft: "[",
114
+ BracketRight: "]",
115
+ Comma: ",",
116
+ ControlLeft: "Control",
117
+ ControlRight: "Control",
118
+ Equal: "=",
119
+ Minus: "-",
120
+ Period: ".",
121
+ Quote: "'",
122
+ Semicolon: ";",
123
+ ShiftLeft: "Shift",
124
+ ShiftRight: "Shift",
125
+ Slash: "/",
126
+ Space: " "
127
+ })
128
+ );
129
+ var KEY_CODES = new Map(Object.entries(NAMED_KEYS));
130
+ var SHIFTED = new Map(
131
+ Object.entries({
132
+ Backquote: "~",
133
+ Backslash: "|",
134
+ BracketLeft: "{",
135
+ BracketRight: "}",
136
+ Comma: "<",
137
+ Digit0: ")",
138
+ Digit1: "!",
139
+ Digit2: "@",
140
+ Digit3: "#",
141
+ Digit4: "$",
142
+ Digit5: "%",
143
+ Digit6: "^",
144
+ Digit7: "&",
145
+ Digit8: "*",
146
+ Digit9: "(",
147
+ Equal: "+",
148
+ Minus: "_",
149
+ Period: ">",
150
+ Quote: '"',
151
+ Semicolon: ":",
152
+ Slash: "?"
153
+ })
154
+ );
155
+ var shiftedKey = (code, key) => {
156
+ if (/^Key[A-Z]$/u.test(code)) {
157
+ return key.toUpperCase();
158
+ }
159
+ return SHIFTED.get(code) ?? key;
160
+ };
161
+ var keyFields = (code) => {
162
+ const letter = /^Key(?<letter>[A-Z])$/u.exec(code)?.groups?.letter;
163
+ if (letter !== void 0) {
164
+ const fields = [letter.codePointAt(0) ?? 0, letter.toLowerCase()];
165
+ return fields;
166
+ }
167
+ const digit = /^Digit(?<digit>[0-9])$/u.exec(code)?.groups?.digit;
168
+ if (digit !== void 0) {
169
+ const fields = [48 + Number(digit), digit];
170
+ return fields;
171
+ }
172
+ const keyCode = KEY_CODES.get(code);
173
+ if (keyCode !== void 0) {
174
+ const fields = [keyCode, NAMED_VALUES.get(code) ?? code];
175
+ return fields;
176
+ }
177
+ return fail(
178
+ `unsupported key code "${code}". Supported: Key<A-Z>, Digit<0-9>, and ${Object.keys(NAMED_KEYS).join(", ")}.`
179
+ );
180
+ };
181
+ var keyInits = (codes) => {
182
+ const modifiers = {
183
+ altKey: codes.some((c) => c === "AltLeft" || c === "AltRight"),
184
+ ctrlKey: codes.some((c) => c === "ControlLeft" || c === "ControlRight"),
185
+ shiftKey: codes.some((c) => c === "ShiftLeft" || c === "ShiftRight")
186
+ };
187
+ return codes.map((code) => {
188
+ const [keyCode, key] = keyFields(code);
189
+ const reported = modifiers.shiftKey ? shiftedKey(code, key) : key;
190
+ return JSON.stringify({
191
+ code,
192
+ key: reported,
193
+ keyCode,
194
+ which: keyCode,
195
+ ...modifiers,
196
+ bubbles: true
197
+ });
198
+ });
199
+ };
200
+ var keyParts = (type, codes) => {
201
+ if (codes.length === 0) {
202
+ return [];
203
+ }
204
+ return [
205
+ `{ const t = document.activeElement ?? document.body ?? window;
206
+ for (const init of [${keyInits(codes).join(",")}]) t.dispatchEvent(new KeyboardEvent(${JSON.stringify(type)}, init)); }`
207
+ ];
208
+ };
209
+ var POINTER_FN = `window.__botPointer = (frac, type, buttons) => {
210
+ const cx = Math.round(window.innerWidth * frac.x);
211
+ const cy = Math.round(window.innerHeight * frac.y);
212
+ const target = document.elementFromPoint(cx, cy) || document.querySelector("canvas") || window;
213
+ const init = { clientX: cx, clientY: cy, screenX: cx, screenY: cy, bubbles: true, cancelable: true, composed: true, pointerId: 1, isPrimary: true, pointerType: "mouse", button: 0, buttons };
214
+ target.dispatchEvent(new PointerEvent(type, init));
215
+ target.dispatchEvent(new MouseEvent(type === "pointermove" ? "mousemove" : type === "pointerdown" ? "mousedown" : "mouseup", init));
216
+ };`;
217
+ var pointerCall = (pointer, type, buttons) => `window.__botPointer(${JSON.stringify({ x: pointer.x, y: pointer.y })}, ${JSON.stringify(type)}, ${buttons});`;
218
+ var pointerParts = (pointer, phase) => {
219
+ if (pointer === void 0) {
220
+ return [];
221
+ }
222
+ const down = pointer.down === true;
223
+ if (phase === "up") {
224
+ return down ? [POINTER_FN, pointerCall(pointer, "pointerup", 0)] : [];
225
+ }
226
+ return [
227
+ POINTER_FN,
228
+ pointerCall(pointer, "pointermove", down ? 1 : 0),
229
+ ...down ? [pointerCall(pointer, "pointerdown", 1)] : []
230
+ ];
231
+ };
232
+ var isFraction = (v) => isFiniteJsonNumber(v) && v >= 0 && v <= 1;
233
+ var validatePointer = (pointer, where) => {
234
+ const { x, y, down } = isJsonObject(pointer) ? pointer : {};
235
+ if (!isFraction(x)) {
236
+ return fail(`${where}: \`pointer.x\` must be a viewport fraction between 0 and 1.`);
237
+ }
238
+ if (!isFraction(y)) {
239
+ return fail(`${where}: \`pointer.y\` must be a viewport fraction between 0 and 1.`);
240
+ }
241
+ if (down !== void 0 && down !== true && down !== false) {
242
+ return fail(`${where}: \`pointer.down\` must be a boolean.`);
243
+ }
244
+ const checked = down === void 0 ? { x, y } : { down, x, y };
245
+ return checked;
246
+ };
247
+ var READ_FN = `const __botRead = () => {
248
+ const d = window.__GAME_DIAGNOSTICS__, p = (d && d.player) || {};
249
+ return { x: p.x ?? 0, y: p.y ?? 0, z: p.z ?? 0, frame: (d && d.frame) ?? 0, score: (d && d.score) ?? 0, complete: !!(d && d.complete) };
250
+ };
251
+ const __botDist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);`;
252
+ var TRACK_BEGIN_BODY = `const s = __botRead();
253
+ const t = { start: s, last: s, path: 0, peak: 0, score: s.score };
254
+ window.__BOT_TRACK__ = t;
255
+ clearInterval(window.__BOT_TICK__);
256
+ window.__BOT_TICK__ = setInterval(() => {
257
+ const c = __botRead();
258
+ t.path += __botDist(c, t.last);
259
+ t.peak = Math.max(t.peak, __botDist(c, t.start));
260
+ t.last = c;
261
+ if (c.score > t.score) t.score = c.score;
262
+ }, ${SAMPLE_MS});`;
263
+ var TRACK_BEGIN = `${READ_FN}
264
+ ${TRACK_BEGIN_BODY}`;
265
+ var TRACK_SUMMARY = `(() => {
266
+ clearInterval(window.__BOT_TICK__);
267
+ const t = window.__BOT_TRACK__;
268
+ if (!t) return null;
269
+ const c = __botRead();
270
+ const path = t.path + __botDist(c, t.last);
271
+ const peak = Math.max(t.peak, __botDist(c, t.start));
272
+ return { path: +path.toFixed(3), peak: +peak.toFixed(3), frameBefore: t.start.frame, frame: c.frame, scoreBefore: t.start.score, score: Math.max(t.score, c.score), x: c.x, y: c.y, z: c.z, complete: c.complete };
273
+ })()`;
274
+ var TRACK_END = `${READ_FN}
275
+ return ${TRACK_SUMMARY};`;
276
+ var SAMPLE = `(() => { ${READ_FN} return __botRead(); })()`;
277
+ var sleep = (ms) => {
278
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
279
+ };
280
+ var playtest = (args) => {
281
+ const res = spawnSync(process.execPath, [vgEntry, "playtest", ...args], {
282
+ encoding: "utf-8",
283
+ timeout: 12e4
284
+ });
285
+ if (res.error !== void 0) {
286
+ fail(`couldn't run \`vg playtest\` \u2014 is the vg CLI installed? (${res.error.message})`);
287
+ }
288
+ return { status: res.status ?? 1, stderr: res.stderr ?? "", stdout: res.stdout ?? "" };
289
+ };
290
+ var parseJson = (text, onError) => {
291
+ try {
292
+ return parseJsonText(text);
293
+ } catch {
294
+ return onError();
295
+ }
296
+ };
297
+ var payload = (args, key) => {
298
+ const command = args[0] ?? "";
299
+ const { status, stdout, stderr } = playtest([...args, "--json"]);
300
+ const text = stdout.trim();
301
+ if (status !== 0) {
302
+ const detail = stderr.trim();
303
+ fail(`\`${command}\` failed: ${detail === "" ? text : detail}`);
304
+ }
305
+ const parsed = parseJson(
306
+ text,
307
+ () => fail(`\`${command} --json\` did not return JSON: ${text.slice(0, 200)}`)
308
+ );
309
+ const envelope = isJsonObject(parsed) ? parsed : {};
310
+ if (envelope.success === false) {
311
+ fail(`\`${command}\` failed: ${JSON.stringify(envelope.error)}`);
312
+ }
313
+ const { data } = envelope;
314
+ if (!isJsonObject(data) || !(key in data)) {
315
+ return fail(
316
+ `unexpected agent-browser response for \`${command}\` (no data.${key}): ${text.slice(0, 200)}`
317
+ );
318
+ }
319
+ return data[key];
320
+ };
321
+ var evaluate = (expression) => payload(["eval", expression], "result");
322
+ var readConsoleErrors = () => {
323
+ const entries = payload(["console"], "messages");
324
+ if (!Array.isArray(entries)) {
325
+ return fail("`console` returned a non-array `messages`.");
326
+ }
327
+ return entries.filter((entry) => isJsonObject(entry) && entry.type === "error").map((entry) => (isJsonObject(entry) ? entry.text : void 0) ?? JSON.stringify(entry));
328
+ };
329
+ var collectErrors = () => {
330
+ const consoleErrors = readConsoleErrors();
331
+ const pageErrors = payload(["errors"], "errors");
332
+ if (!Array.isArray(pageErrors)) {
333
+ return fail("`errors` returned a non-array `errors`.");
334
+ }
335
+ return { consoleErrors, pageErrors };
336
+ };
337
+ var numberIn = (fields, name, what) => {
338
+ const value = fields[name];
339
+ if (!isFiniteJsonNumber(value)) {
340
+ return fail(`${what} read a non-number \`${name}\`: ${JSON.stringify(fields)}`);
341
+ }
342
+ return value;
343
+ };
344
+ var readSample = (value, what) => {
345
+ if (!isJsonObject(value)) {
346
+ return fail(`${what} was not an object: ${JSON.stringify(value)}`);
347
+ }
348
+ const sample = {
349
+ complete: value.complete === true,
350
+ frame: numberIn(value, "frame", what),
351
+ score: numberIn(value, "score", what),
352
+ x: numberIn(value, "x", what),
353
+ y: numberIn(value, "y", what),
354
+ z: numberIn(value, "z", what)
355
+ };
356
+ return sample;
357
+ };
358
+ var readSummary = (value, what) => {
359
+ if (value === null) {
360
+ return null;
361
+ }
362
+ const sample = readSample(value, what);
363
+ const fields = isJsonObject(value) ? value : {};
364
+ const summary = {
365
+ ...sample,
366
+ frameBefore: numberIn(fields, "frameBefore", what),
367
+ path: numberIn(fields, "path", what),
368
+ peak: numberIn(fields, "peak", what),
369
+ scoreBefore: numberIn(fields, "scoreBefore", what)
370
+ };
371
+ return summary;
372
+ };
373
+ var readGpuInfo = () => {
374
+ const info = evaluate(
375
+ `(() => {
376
+ const canvas = document.querySelector("canvas");
377
+ let gl = null;
378
+ try { gl = canvas?.getContext("webgl2") ?? canvas?.getContext("webgl") ?? null; } catch { gl = null; }
379
+ if (!gl) { return null; }
380
+ const debug = gl.getExtension("WEBGL_debug_renderer_info");
381
+ return {
382
+ renderer: debug ? gl.getParameter(debug.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER),
383
+ vendor: debug ? gl.getParameter(debug.UNMASKED_VENDOR_WEBGL) : gl.getParameter(gl.VENDOR),
384
+ };
385
+ })()`
386
+ );
387
+ const { renderer, vendor } = isJsonObject(info) ? info : {};
388
+ if (!isJsonString(renderer)) {
389
+ return { renderer: null, softwareRendered: null, vendor: null };
390
+ }
391
+ return {
392
+ renderer,
393
+ softwareRendered: /swiftshader|llvmpipe|software|basic render/iu.test(renderer),
394
+ vendor: isJsonString(vendor) ? vendor : null
395
+ };
396
+ };
397
+ var CONTRACT_READY = "window.__GAME_DIAGNOSTICS__ !== undefined && window.__GAME_TEST_HOOKS__ !== undefined";
398
+ var boot = (target, headed, whenAbsent) => {
399
+ playtest(["console", "--clear"]);
400
+ playtest(["errors", "--clear"]);
401
+ const open = playtest(["open", ...target, ...headed ? ["--headed"] : []]);
402
+ if (open.status !== 0) {
403
+ const detail = open.stderr.trim();
404
+ fail(`couldn't open the game: ${detail === "" ? open.stdout.trim() : detail}`);
405
+ }
406
+ if (playtest(["wait", "--fn", CONTRACT_READY]).status !== 0) {
407
+ fail(whenAbsent);
408
+ }
409
+ };
410
+ var applySeed = (seed, headed) => {
411
+ const boot0 = evaluate(
412
+ "({ hasSeedHook: typeof window.__GAME_TEST_HOOKS__?.seed === 'function', href: location.href })"
413
+ );
414
+ const { hasSeedHook, href } = isJsonObject(boot0) ? boot0 : {};
415
+ if (hasSeedHook === true) {
416
+ return "hook";
417
+ }
418
+ if (!isJsonString(href)) {
419
+ return fail("couldn't read location.href to apply the seed.");
420
+ }
421
+ const url = new URL(href);
422
+ url.searchParams.set("seed", String(seed));
423
+ boot(
424
+ [url.toString()],
425
+ headed,
426
+ "the game stopped publishing diagnostics after the seeded reload."
427
+ );
428
+ return "boot-param";
429
+ };
430
+ var launch = ({
431
+ headed,
432
+ seed,
433
+ target
434
+ }) => {
435
+ boot(
436
+ target,
437
+ headed,
438
+ "the game never published window.__GAME_DIAGNOSTICS__ / window.__GAME_TEST_HOOKS__. Either it crashed on boot, or it doesn't implement the diagnostics contract (see references/scripted-playtest.md)."
439
+ );
440
+ const seedApplied = applySeed(seed, headed);
441
+ const ack = evaluate(
442
+ `(async () => { const h = window.__GAME_TEST_HOOKS__; h.seed?.(${seed}); const ack = await h.setState?.('active-play'); window.__BOT_F0__ = h && window.__GAME_DIAGNOSTICS__.frame; return ack === undefined ? null : ack; })()`
443
+ );
444
+ if (ack !== null && (!isJsonObject(ack) || ack.state !== "active-play")) {
445
+ fail(
446
+ `setState('active-play') acknowledged ${JSON.stringify(ack)} instead of { state: 'active-play' } \u2014 the hook applied a different state or is a no-op (see references/scripted-playtest.md).`
447
+ );
448
+ }
449
+ const live = playtest([
450
+ "wait",
451
+ "--fn",
452
+ "(window.__GAME_DIAGNOSTICS__?.frame ?? 0) > 10 && window.__GAME_DIAGNOSTICS__.frame !== window.__BOT_F0__"
453
+ ]);
454
+ if (live.status !== 0) {
455
+ fail(
456
+ "diagnostics are published but the loop never advanced after seed()/setState('active-play') \u2014 check they aren't no-ops (see references/scripted-playtest.md)."
457
+ );
458
+ }
459
+ return { before: readSample(evaluate(SAMPLE), "the baseline sample"), seedApplied };
460
+ };
461
+
462
+ // src/checks/scripted-playtest.ts
463
+ setProgramName("vg check scripted-playtest");
464
+ var USAGE = "usage: vg check scripted-playtest --url <url> | --game <slug> [--seed n] [--script steps.json] [--reaction-delay ms] [--expect-progress] [--headed] [--keep-open]";
465
+ var DEFAULT_SCRIPT = [
466
+ { keys: ["KeyW"], ms: 1e3 },
467
+ { keys: ["KeyA"], ms: 1900 },
468
+ { keys: ["KeyD"], ms: 3400 },
469
+ { keys: ["KeyS"], ms: 1700 },
470
+ { keys: ["KeyA"], ms: 3400 },
471
+ { keys: ["Space"], ms: 600 }
472
+ ];
473
+ var THRESHOLDS = {
474
+ displacement: 5,
475
+ framesAdvanced: 100,
476
+ motionEpsilon: 0.2,
477
+ stuckRun: 2
478
+ };
479
+ var parseArgs = (argv) => {
480
+ const opts = {
481
+ expectProgress: false,
482
+ game: null,
483
+ headed: false,
484
+ keepOpen: false,
485
+ reactionDelay: 0,
486
+ script: DEFAULT_SCRIPT,
487
+ seed: 12345,
488
+ url: null
489
+ };
490
+ for (let i = 0; i < argv.length; i += 1) {
491
+ const arg = argv[i];
492
+ const takeValue = () => {
493
+ const value = argv[i + 1];
494
+ if (value === void 0) {
495
+ fail(`\`${arg}\` needs a value.`);
496
+ }
497
+ i += 1;
498
+ return value;
499
+ };
500
+ const num = () => {
501
+ const raw = takeValue();
502
+ return raw.trim() === "" ? Number.NaN : Number(raw);
503
+ };
504
+ if (arg === "--url") {
505
+ opts.url = takeValue();
506
+ } else if (arg === "--game") {
507
+ opts.game = takeValue();
508
+ } else if (arg === "--seed") {
509
+ opts.seed = num();
510
+ } else if (arg === "--reaction-delay") {
511
+ opts.reactionDelay = num();
512
+ } else if (arg === "--script") {
513
+ opts.script = readScript(takeValue());
514
+ } else if (arg === "--expect-progress") {
515
+ opts.expectProgress = true;
516
+ } else if (arg === "--headed") {
517
+ opts.headed = true;
518
+ } else if (arg === "--keep-open") {
519
+ opts.keepOpen = true;
520
+ } else if (arg === "--help" || arg === "-h") {
521
+ console.log(USAGE);
522
+ process.exit(0);
523
+ } else {
524
+ fail(`Unknown argument: ${arg}`);
525
+ }
526
+ }
527
+ if (opts.url === null && opts.game === null) {
528
+ fail("Pass --url <url> or --game <slug>.");
529
+ }
530
+ if (opts.url !== null && opts.game !== null) {
531
+ fail("Pass either --url or --game, not both.");
532
+ }
533
+ if (!Number.isFinite(opts.seed)) {
534
+ fail("`--seed` must be a finite number.");
535
+ }
536
+ if (!Number.isFinite(opts.reactionDelay) || opts.reactionDelay < 0) {
537
+ fail("`--reaction-delay` must be a non-negative number of milliseconds.");
538
+ }
539
+ return { ...opts, script: validateScript(opts.script) };
540
+ };
541
+ var readText = (path) => {
542
+ try {
543
+ return readFileSync(path, "utf-8");
544
+ } catch {
545
+ return fail(`couldn't read --script ${path}.`);
546
+ }
547
+ };
548
+ var readScript = (path) => {
549
+ const text = readText(path);
550
+ try {
551
+ return parseJsonText(text);
552
+ } catch (error) {
553
+ return fail(
554
+ `--script ${path} isn't valid JSON: ${error instanceof Error ? error.message : String(error)}`
555
+ );
556
+ }
557
+ };
558
+ var validateStep = (step, index) => {
559
+ const keys = step.keys ?? [];
560
+ const { pointer, ms, expectMotion } = step;
561
+ if (!Array.isArray(keys)) {
562
+ return fail(`step ${index}: \`keys\` must be an array.`);
563
+ }
564
+ const hasPointer = pointer !== void 0 && Boolean(pointer);
565
+ if (keys.length === 0 && !hasPointer) {
566
+ fail(`step ${index} needs a non-empty \`keys\` array or a \`pointer\`.`);
567
+ }
568
+ if (!isFiniteJsonNumber(ms) || ms <= 0) {
569
+ return fail(`step ${index} needs a positive \`ms\` duration.`);
570
+ }
571
+ if (expectMotion !== void 0 && !isJsonBoolean(expectMotion)) {
572
+ return fail(`step ${index}: \`expectMotion\` must be a boolean.`);
573
+ }
574
+ const checked = {
575
+ keys: keys.map(
576
+ (code) => isJsonString(code) ? code : fail(`step ${index}: \`keys\` must be KeyboardEvent code strings.`)
577
+ ),
578
+ ms
579
+ };
580
+ if (hasPointer) {
581
+ checked.pointer = validatePointer(pointer, `step ${index}`);
582
+ }
583
+ for (const code of checked.keys) {
584
+ keyFields(code);
585
+ }
586
+ if (expectMotion !== void 0) {
587
+ checked.expectMotion = expectMotion;
588
+ }
589
+ return checked;
590
+ };
591
+ var validateScript = (script) => {
592
+ if (!Array.isArray(script) || script.length === 0) {
593
+ return fail("`--script` must be a non-empty JSON array of { keys, ms } steps.");
594
+ }
595
+ return script.map(
596
+ (step, index) => isJsonObject(step) ? validateStep(step, index) : fail(`step ${index} must be an object.`)
597
+ );
598
+ };
599
+ var expectsMotion = (step) => {
600
+ if (step.expectMotion === true || step.expectMotion === false) {
601
+ return step.expectMotion;
602
+ }
603
+ return step.pointer !== void 0 || step.keys.some((code) => MOVEMENT_CODES.has(code));
604
+ };
605
+ var beginStep = (step) => {
606
+ const parts = [
607
+ TRACK_BEGIN,
608
+ ...pointerParts(step.pointer, "down"),
609
+ ...keyParts("keydown", step.keys)
610
+ ];
611
+ claimHeld(step);
612
+ evaluate(`(() => { ${parts.join("\n")}
613
+ return true; })()`);
614
+ };
615
+ var endStep = (step, index) => {
616
+ const parts = [...keyParts("keyup", step.keys), ...pointerParts(step.pointer, "up"), TRACK_END];
617
+ const summary = evaluate(`(() => { ${parts.join("\n")} })()`);
618
+ disownHeld();
619
+ return readSummary(summary, `step ${index}'s tracker`);
620
+ };
621
+ var runScript = (opts, before) => {
622
+ let prev = before;
623
+ let distance = 0;
624
+ let maxStepDisplacement = 0;
625
+ let stuckSteps = 0;
626
+ let stuckRun = 0;
627
+ let longestStuckRun = 0;
628
+ let stepOfFirstScore = null;
629
+ for (const [index, step] of opts.script.entries()) {
630
+ beginStep(step);
631
+ sleep(step.ms);
632
+ const moved = endStep(step, index);
633
+ if (opts.reactionDelay > 0) {
634
+ sleep(opts.reactionDelay);
635
+ }
636
+ if (moved === null) {
637
+ fail(`step ${index} lost its in-page tracker; the page probably navigated mid-run.`);
638
+ }
639
+ distance += moved.path;
640
+ maxStepDisplacement = Math.max(maxStepDisplacement, moved.peak);
641
+ const progressed = moved.score > moved.scoreBefore;
642
+ if (progressed && stepOfFirstScore === null) {
643
+ stepOfFirstScore = index;
644
+ }
645
+ if (expectsMotion(step)) {
646
+ const stuck = moved.frame > moved.frameBefore && moved.peak < THRESHOLDS.motionEpsilon && !progressed;
647
+ if (stuck) {
648
+ stuckSteps += 1;
649
+ stuckRun += 1;
650
+ longestStuckRun = Math.max(longestStuckRun, stuckRun);
651
+ } else {
652
+ stuckRun = 0;
653
+ }
654
+ }
655
+ prev = moved;
656
+ }
657
+ return { distance, longestStuckRun, maxStepDisplacement, prev, stepOfFirstScore, stuckSteps };
658
+ };
659
+ var run = (argv) => {
660
+ const opts = parseArgs([...argv]);
661
+ const { before, seedApplied } = launch({
662
+ headed: opts.headed,
663
+ seed: opts.seed,
664
+ target: opts.game === null ? [opts.url ?? ""] : ["--game", opts.game]
665
+ });
666
+ const { distance, longestStuckRun, maxStepDisplacement, prev, stepOfFirstScore, stuckSteps } = runScript(opts, before);
667
+ const { consoleErrors, pageErrors } = collectErrors();
668
+ const gpu = readGpuInfo();
669
+ const report = {
670
+ complete: prev.complete,
671
+ consoleErrors,
672
+ distanceTravelled: Number(distance.toFixed(2)),
673
+ framesAdvanced: prev.frame - before.frame,
674
+ gpu,
675
+ longestStuckRun,
676
+ maxStepDisplacement: Number(maxStepDisplacement.toFixed(2)),
677
+ pageErrors,
678
+ reactionDelay: opts.reactionDelay,
679
+ scoreAfter: prev.score,
680
+ scoreBefore: before.score,
681
+ seed: opts.seed,
682
+ seedApplied,
683
+ stepOfFirstScore,
684
+ steps: opts.script.length,
685
+ stuckSteps,
686
+ target: opts.game === null ? opts.url : `game:${opts.game}`
687
+ };
688
+ const failures = [];
689
+ const warnings = [];
690
+ if (report.framesAdvanced <= THRESHOLDS.framesAdvanced) {
691
+ failures.push(`game loop stalled (framesAdvanced ${report.framesAdvanced})`);
692
+ }
693
+ if (report.maxStepDisplacement <= THRESHOLDS.displacement) {
694
+ failures.push(
695
+ `player did not respond to input (maxStepDisplacement ${report.maxStepDisplacement}) \u2014 if this game steers with the mouse, give the script \`pointer\` steps`
696
+ );
697
+ }
698
+ if (report.longestStuckRun > THRESHOLDS.stuckRun) {
699
+ failures.push(
700
+ `player wedged for ${report.longestStuckRun} consecutive movement steps (longestStuckRun)`
701
+ );
702
+ }
703
+ const motionSteps = opts.script.filter(expectsMotion).length;
704
+ if (motionSteps <= THRESHOLDS.stuckRun) {
705
+ warnings.push(
706
+ `stuck detection never applied: ${motionSteps} step(s) ask the player to move, and failing needs more than ${THRESHOLDS.stuckRun} in a row`
707
+ );
708
+ }
709
+ if (report.scoreAfter <= report.scoreBefore) {
710
+ const message = "the run never progressed the objective";
711
+ if (opts.expectProgress) {
712
+ failures.push(message);
713
+ } else {
714
+ warnings.push(
715
+ `${message} \u2014 pass \`--expect-progress\` once your script performs this game's scoring verb, to make that an assertion`
716
+ );
717
+ }
718
+ }
719
+ if (report.consoleErrors.length > 0) {
720
+ failures.push(`${report.consoleErrors.length} console error(s)`);
721
+ }
722
+ if (report.pageErrors.length > 0) {
723
+ failures.push(`${report.pageErrors.length} uncaught page error(s)`);
724
+ }
725
+ console.log(JSON.stringify({ ...report, failures, warnings }, null, 2));
726
+ if (!opts.keepOpen) {
727
+ playtest(["close"]);
728
+ }
729
+ if (failures.length > 0) {
730
+ console.error(`
731
+ scripted-playtest: FAILED \u2014 ${failures.join("; ")}`);
732
+ process.exit(1);
733
+ }
734
+ for (const warning of warnings) {
735
+ console.error(`scripted-playtest: warning \u2014 ${warning}`);
736
+ }
737
+ console.error("\nscripted-playtest: PASSED");
738
+ };
739
+ export {
740
+ run
741
+ };