@seriousgaming/sdk-tools 1.5.0 → 1.6.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 (160) hide show
  1. package/dist/bundling/ui-bundler.d.ts +12 -0
  2. package/dist/cli-25RWY5BQ.js +41 -0
  3. package/dist/cli-272KBNJH.js +97 -0
  4. package/dist/cli-2BH7FX27.js +52 -0
  5. package/dist/cli-2GOFEW26.js +81 -0
  6. package/dist/cli-3E3MD5U4.js +21 -0
  7. package/dist/cli-3HE4AVZG.js +115 -0
  8. package/dist/cli-4AKVLEC4.js +1387 -0
  9. package/dist/cli-4BV45LBH.js +126 -0
  10. package/dist/cli-4LKXZQ2B.js +48 -0
  11. package/dist/cli-4UWFQNGF.js +54 -0
  12. package/dist/cli-4YB3ROVR.js +78 -0
  13. package/dist/cli-57RXC3HQ.js +36 -0
  14. package/dist/cli-5JEGTVTG.js +96 -0
  15. package/dist/cli-6AMT3BUO.js +97 -0
  16. package/dist/cli-6RRVEGFB.js +80 -0
  17. package/dist/cli-6WXLXJVX.js +36 -0
  18. package/dist/cli-7OGYADZ3.js +97 -0
  19. package/dist/cli-AK7OIPWY.js +229 -0
  20. package/dist/cli-B4TN6PJP.js +124 -0
  21. package/dist/cli-B6YHEKIJ.js +248 -0
  22. package/dist/cli-BPYMTOUL.js +89 -0
  23. package/dist/cli-BWX5E7TQ.js +23 -0
  24. package/dist/cli-BYJWFFCF.js +37 -0
  25. package/dist/cli-C3NVCKO6.js +43 -0
  26. package/dist/cli-C47GJATR.js +42 -0
  27. package/dist/cli-C5QOJJWX.js +46 -0
  28. package/dist/cli-C6TH5S7K.js +6417 -0
  29. package/dist/cli-DL2CVMRF.js +89 -0
  30. package/dist/cli-DMW2OQIJ.js +76 -0
  31. package/dist/cli-DZW3XD5F.js +143 -0
  32. package/dist/cli-E2NLWIFE.js +1331 -0
  33. package/dist/cli-E33CJRRQ.js +36 -0
  34. package/dist/cli-E6DJIMYD.js +142 -0
  35. package/dist/cli-EEFJKIGL.js +151 -0
  36. package/dist/cli-EVFS55WN.js +185 -0
  37. package/dist/cli-F2D4GGUA.js +549 -0
  38. package/dist/cli-FBTRTIZJ.js +226 -0
  39. package/dist/cli-FWFRKQNE.js +11 -0
  40. package/dist/cli-FYINNRML.js +760 -0
  41. package/dist/cli-G522CPRL.js +88 -0
  42. package/dist/cli-G6KELFSX.js +2847 -0
  43. package/dist/cli-G6UE5NL4.js +90 -0
  44. package/dist/cli-GBFM76BF.js +16 -0
  45. package/dist/cli-GDQ6ILJY.js +101 -0
  46. package/dist/cli-GFBGYFYD.js +50 -0
  47. package/dist/cli-GGPDQNM3.js +35 -0
  48. package/dist/cli-GTSGLN3Z.js +307 -0
  49. package/dist/cli-GUXKQMJ7.js +13641 -0
  50. package/dist/cli-GXD36NF2.js +60 -0
  51. package/dist/cli-HCRTYQQS.js +16 -0
  52. package/dist/cli-HYY64SUD.js +185 -0
  53. package/dist/cli-I355WTAF.js +463 -0
  54. package/dist/cli-IDKYF5XB.js +59 -0
  55. package/dist/cli-ILKCQNM6.js +8 -0
  56. package/dist/cli-IRZ5KB7D.js +36 -0
  57. package/dist/cli-IUS2YCD3.js +31 -0
  58. package/dist/cli-J4DKUUTK.js +138 -0
  59. package/dist/cli-JFU22EJ2.js +187 -0
  60. package/dist/cli-JMZLT65J.js +226 -0
  61. package/dist/cli-JZM7XTNV.js +89 -0
  62. package/dist/cli-K2B6WHKA.js +81 -0
  63. package/dist/cli-KL3756X6.js +126 -0
  64. package/dist/cli-KNOOKGYW.js +88 -0
  65. package/dist/cli-LFGRFIEO.js +226 -0
  66. package/dist/cli-LFM7GJHI.js +0 -0
  67. package/dist/cli-LMDJCHHD.js +304 -0
  68. package/dist/cli-LXYPE3L5.js +99 -0
  69. package/dist/cli-M6BCQRID.js +153 -0
  70. package/dist/cli-MBNMPVDC.js +367 -0
  71. package/dist/cli-MJUYJIEP.js +13 -0
  72. package/dist/cli-MMN4BPO4.js +145 -0
  73. package/dist/cli-MYJGMA6U.js +40 -0
  74. package/dist/cli-N6H6T2E2.js +616 -0
  75. package/dist/cli-O5KP4OVN.js +61 -0
  76. package/dist/cli-O6PWMJTZ.js +25 -0
  77. package/dist/cli-ORIG557O.js +141 -0
  78. package/dist/cli-PFFCNGHI.js +243 -0
  79. package/dist/cli-PNLYX6R6.js +131 -0
  80. package/dist/cli-PQBXVLEU.js +649 -0
  81. package/dist/cli-PTT5RGKO.js +62 -0
  82. package/dist/cli-Q2XJF5AS.js +127 -0
  83. package/dist/cli-QEVDDBNO.js +60 -0
  84. package/dist/cli-QEVE5HUM.js +167 -0
  85. package/dist/cli-QUIJCBYB.js +391 -0
  86. package/dist/cli-QUNIRH7A.js +57 -0
  87. package/dist/cli-QVASWX2A.js +187 -0
  88. package/dist/cli-QWQMPCL6.js +253 -0
  89. package/dist/cli-R4PCG5YX.js +131 -0
  90. package/dist/cli-RA673NGF.js +53 -0
  91. package/dist/cli-RN6IWTL2.js +36 -0
  92. package/dist/cli-ROT3DRKU.js +145 -0
  93. package/dist/cli-RZITKPJX.js +367 -0
  94. package/dist/cli-S5IVGDDD.js +32 -0
  95. package/dist/cli-S5QDONIQ.js +218 -0
  96. package/dist/cli-SIPDUBFL.js +36 -0
  97. package/dist/cli-SMFSZF2G.js +4009 -0
  98. package/dist/cli-SRHBXZCN.js +159 -0
  99. package/dist/cli-TCY5LJ7E.js +88 -0
  100. package/dist/cli-TDSQSCX4.js +131 -0
  101. package/dist/cli-TIDQ4WUE.js +257 -0
  102. package/dist/cli-TLLA6KAP.js +79 -0
  103. package/dist/cli-TPU4TUR6.js +132 -0
  104. package/dist/cli-U2UE7I7J.js +30 -0
  105. package/dist/cli-UELGBQG7.js +101 -0
  106. package/dist/cli-UHSZBKYO.js +97 -0
  107. package/dist/cli-UJ4UCL2Z.js +38 -0
  108. package/dist/cli-UKQYZYFK.js +31 -0
  109. package/dist/cli-UMFFURZ7.js +81 -0
  110. package/dist/cli-UNAJ2OTE.js +15 -0
  111. package/dist/cli-UNJ5X6BU.js +89 -0
  112. package/dist/cli-UTJU4IYG.js +117 -0
  113. package/dist/cli-V4GHRWOV.js +1837 -0
  114. package/dist/cli-VCI3CG36.js +73 -0
  115. package/dist/cli-VCKOC2EV.js +256 -0
  116. package/dist/cli-VL2P354N.js +46 -0
  117. package/dist/cli-WAE26SVW.js +72 -0
  118. package/dist/cli-WOGIAU2E.js +100 -0
  119. package/dist/cli-WU43JT4T.js +52 -0
  120. package/dist/cli-XCO2VQOH.js +122 -0
  121. package/dist/cli-XSVGKI3R.js +39 -0
  122. package/dist/cli-YOTGR3NB.js +82 -0
  123. package/dist/cli-YVVXUD2G.js +197 -0
  124. package/dist/cli-ZISJ36MM.js +89 -0
  125. package/dist/cli-ZTWOE3ZT.js +65 -0
  126. package/dist/cli-ZVSFYDPQ.js +205 -0
  127. package/dist/cli-ZWPYIXNI.js +68 -0
  128. package/dist/cli.js +148 -43093
  129. package/dist/client/build-surfaces.d.ts +33 -0
  130. package/dist/client/dev-server.d.ts +6 -0
  131. package/dist/client/index.d.ts +1 -0
  132. package/dist/client/playwright.d.ts +62 -0
  133. package/dist/client.js +228 -48
  134. package/dist/core/session.d.ts +15 -1
  135. package/dist/dev/console/assets/{index-BVF8exas.js → index-CuMOOH9m.js} +1 -1
  136. package/dist/dev/console/index.html +1 -1
  137. package/dist/dev/shell.d.ts +19 -0
  138. package/dist/dev/surfaces.d.ts +7 -0
  139. package/dist/docs/api/index.md +14 -12
  140. package/dist/docs/api/sdk-tools-client.md +29 -0
  141. package/dist/docs/api/sdk-tools-playwright.md +104 -0
  142. package/dist/docs/changelog.md +19 -0
  143. package/dist/docs/cli-and-dev-server.md +21 -0
  144. package/dist/docs/cli-reference.md +45 -31
  145. package/dist/docs/environment-variables.md +6 -0
  146. package/dist/docs/guides/designing-a-game.md +29 -4
  147. package/dist/docs/guides/starter-game.md +2 -2
  148. package/dist/docs/guides/testing.md +33 -18
  149. package/dist/docs/page-index.md +8 -7
  150. package/dist/docs/recipes/e2e-testing.md +19 -20
  151. package/dist/playwright.js +32232 -0
  152. package/dist/templates/package/claude/rules/workflow-test-engine-or-ui.md +1 -1
  153. package/dist/templates/package/global-setup.ts.template +7 -18
  154. package/dist/templates/package/playwright.config.ts.liquid +8 -11
  155. package/dist/templates/starter-game/playwright.config.ts +8 -11
  156. package/dist/templates/starter-game/testing/e2e/game.spec.ts +1 -1
  157. package/dist/templates/starter-game/testing/e2e/global-setup.ts +7 -18
  158. package/dist/utils/prompt.d.ts +5 -5
  159. package/dist/utils/resource-scan.d.ts +39 -0
  160. package/package.json +7 -3
@@ -0,0 +1,2847 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ blobLinks
4
+ } from "./cli-BWX5E7TQ.js";
5
+ import {
6
+ validatePackage
7
+ } from "./cli-V4GHRWOV.js";
8
+ import {
9
+ PackageScenarioError,
10
+ createPackageScenario,
11
+ deletePackageScenario
12
+ } from "./cli-LFM7GJHI.js";
13
+ import {
14
+ PENDING_CHANGES_HINT,
15
+ REINITIALISED_ON_CHANGE,
16
+ Session,
17
+ commandError,
18
+ describePendingChanges,
19
+ hasPendingChanges,
20
+ isQuery,
21
+ pendingHeadline,
22
+ rebuildsWalkthrough
23
+ } from "./cli-C6TH5S7K.js";
24
+ import {
25
+ newInstanceId,
26
+ removeLockFile,
27
+ writeLockFile
28
+ } from "./cli-SRHBXZCN.js";
29
+ import {
30
+ hmrClientTarget,
31
+ publicAssetOrigin,
32
+ publicHmrOrigin,
33
+ publicHostnames
34
+ } from "./cli-YOTGR3NB.js";
35
+ import {
36
+ describeScenarioProblems,
37
+ runScenarioGates
38
+ } from "./cli-VCKOC2EV.js";
39
+ import {
40
+ mediaTypeOf,
41
+ readBlob,
42
+ redirectBlobs,
43
+ storeBlob
44
+ } from "./cli-QWQMPCL6.js";
45
+ import {
46
+ collectSettingsOverrideErrors,
47
+ createAjv,
48
+ errorMessage,
49
+ gameSettingsOf,
50
+ settingsSchemas,
51
+ withoutLockedDefaults
52
+ } from "./cli-SMFSZF2G.js";
53
+ import {
54
+ logger
55
+ } from "./cli-4YB3ROVR.js";
56
+ import {
57
+ CliError,
58
+ diagnosticLocation
59
+ } from "./cli-N6H6T2E2.js";
60
+
61
+ // cli/dev/view/route.ts
62
+ var PATTERNS = [
63
+ [/^\/walkthrough\/?$/, () => ({ kind: "player", teamIndex: 0, participant: 1 })],
64
+ [/^\/team\/(\d+)\/player\/(\d+)\/?$/, (m) => player(m[1], m[2])],
65
+ [/^\/team\/(\d+)\/player\/?$/, (m) => player(m[1], "1")],
66
+ [/^\/team\/(\d+)\/observe\/?$/, (m) => ({ kind: "observer", teamIndex: index(m[1]) })],
67
+ [/^\/team\/(\d+)\/join\/?$/, (m) => ({ kind: "join", teamIndex: index(m[1]) })],
68
+ [/^\/team\/(\d+)\/waiting-room\/?$/, (m) => ({ kind: "waiting-room", teamIndex: index(m[1]) })],
69
+ [/^\/setup\/?$/, () => ({ kind: "setup" })],
70
+ [/^\/scenario-editor\/?$/, () => ({ kind: "scenario-editor" })],
71
+ [/^\/guide\/?$/, () => ({ kind: "guide" })],
72
+ [/^\/print\/?$/, () => ({ kind: "print" })],
73
+ [/^\/presentation\/?$/, () => ({ kind: "presentation" })]
74
+ ];
75
+ function player(team, participant) {
76
+ return {
77
+ kind: "player",
78
+ teamIndex: index(team),
79
+ participant: Math.max(1, Number(participant))
80
+ };
81
+ }
82
+ function index(team) {
83
+ return Math.max(0, Number(team) - 1);
84
+ }
85
+ function parseRoute(pathname, search) {
86
+ const query = new URLSearchParams(search);
87
+ const bare = query.has("bare");
88
+ const preview = query.has("preview");
89
+ const scenario = query.get("scenario");
90
+ const run = /^\/walkthrough(\/|$)/.test(pathname) ? "walkthrough" : "session";
91
+ for (const [pattern, build] of PATTERNS) {
92
+ const match = pathname.match(pattern);
93
+ if (match) {
94
+ return {
95
+ ...build(match),
96
+ bare,
97
+ run,
98
+ ...scenario === null ? {} : { scenario },
99
+ ...preview ? { preview } : {}
100
+ };
101
+ }
102
+ }
103
+ return { kind: "console", bare, run };
104
+ }
105
+ function routeHref(route) {
106
+ const team = (route.teamIndex ?? 0) + 1;
107
+ const path = route.run === "walkthrough" ? "/walkthrough" : route.kind === "player" ? `/team/${team}/player/${route.participant ?? 1}` : route.kind === "observer" ? `/team/${team}/observe` : route.kind === "join" ? `/team/${team}/join` : route.kind === "waiting-room" ? `/team/${team}/waiting-room` : route.kind === "console" ? "/" : `/${route.kind}`;
108
+ const query = new URLSearchParams();
109
+ if (route.scenario !== void 0) query.set("scenario", route.scenario);
110
+ if (route.preview) query.set("preview", "");
111
+ if (route.bare) query.set("bare", "");
112
+ const search = query.toString().replace(/(bare|preview)=(?=&|$)/g, "$1");
113
+ return search ? `${path}?${search}` : path;
114
+ }
115
+
116
+ // cli/dev/shell.ts
117
+ import { statSync } from "fs";
118
+ import { mkdtemp as mkdtemp2, rm as rm2 } from "fs/promises";
119
+ import { createServer } from "http";
120
+ import { tmpdir as tmpdir2 } from "os";
121
+ import { dirname as dirname2, join as join5 } from "path";
122
+ import { fileURLToPath as fileURLToPath2 } from "url";
123
+ import react from "@vitejs/plugin-react";
124
+ import express2 from "express";
125
+ import { createServer as createViteServer } from "vite";
126
+ import { WebSocketServer } from "ws";
127
+
128
+ // cli/core/listen-with-fallback.ts
129
+ import { createServer as createSocket } from "net";
130
+ async function listenWithPortFallback(server, startPort, options = {}) {
131
+ const maxAttempts = options.maxAttempts ?? 100;
132
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
133
+ const port = startPort + attempt;
134
+ const bound = await isFree(port) && await tryListen(server, port, options.host);
135
+ if (bound) {
136
+ const address = server.address();
137
+ return address !== null && typeof address === "object" ? address.port : port;
138
+ }
139
+ options.onPortInUse?.(port);
140
+ }
141
+ throw new CliError(
142
+ "PORT_IN_USE",
143
+ `Could not find available port after ${maxAttempts} attempts`
144
+ );
145
+ }
146
+ function tryListen(server, port, host) {
147
+ return new Promise((resolve3, reject) => {
148
+ const cleanup = () => {
149
+ server.removeListener("error", onError);
150
+ server.removeListener("listening", onListening);
151
+ };
152
+ const onError = (err) => {
153
+ cleanup();
154
+ if (err.code === "EADDRINUSE") {
155
+ resolve3(false);
156
+ } else {
157
+ reject(err);
158
+ }
159
+ };
160
+ const onListening = () => {
161
+ cleanup();
162
+ resolve3(true);
163
+ };
164
+ server.once("error", onError);
165
+ server.once("listening", onListening);
166
+ try {
167
+ server.listen(port, host);
168
+ } catch (err) {
169
+ cleanup();
170
+ reject(err);
171
+ }
172
+ });
173
+ }
174
+ async function findFreePort(startPort, maxAttempts = 100) {
175
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
176
+ const port = startPort + attempt;
177
+ if (await isFree(port)) return port;
178
+ }
179
+ throw new CliError(
180
+ "PORT_IN_USE",
181
+ `Could not find available port after ${maxAttempts} attempts`
182
+ );
183
+ }
184
+ var PROBED_ADDRESSES = [void 0, "127.0.0.1", "::1"];
185
+ async function isFree(port) {
186
+ for (const host of PROBED_ADDRESSES) {
187
+ if (!await isFreeOn(port, host)) return false;
188
+ }
189
+ return true;
190
+ }
191
+ function isFreeOn(port, host) {
192
+ return new Promise((resolve3) => {
193
+ const probe = createSocket();
194
+ probe.once(
195
+ "error",
196
+ (error) => resolve3(error.code === "EADDRNOTAVAIL" || error.code === "EAFNOSUPPORT")
197
+ );
198
+ probe.once("listening", () => probe.close(() => resolve3(true)));
199
+ probe.listen(port, host);
200
+ });
201
+ }
202
+
203
+ // cli/server/vite-plugin.ts
204
+ import { readFile } from "fs/promises";
205
+ import { isAbsolute, join, relative } from "path";
206
+ function toRootRelative(html, documentDirectory) {
207
+ return html.replace(
208
+ /(\s(?:src|href)=")(?!https?:|\/\/|\/|data:|#)(\.\/)?([^"]+)(")/g,
209
+ (_match, before, _dot, path, after) => `${before}${documentDirectory}/${path}${after}`
210
+ );
211
+ }
212
+ var RECOVERY_MODULE_ID = "virtual:seriousgaming-surface-recovery";
213
+ var RECOVERY_RESOLVED_ID = `\0${RECOVERY_MODULE_ID}`;
214
+ var RECOVERY_MODULE_URL = `/@id/__x00__${RECOVERY_MODULE_ID}`;
215
+ var RECOVERY_MODULE = `
216
+ if (import.meta.hot) {
217
+ let broken = false;
218
+ const fail = () => { broken = true; };
219
+ window.addEventListener('error', fail);
220
+ window.addEventListener('unhandledrejection', fail);
221
+
222
+ const blank = () => {
223
+ if (!document.body) return true;
224
+ for (const child of document.body.children) {
225
+ const tag = child.tagName.toLowerCase();
226
+ if (tag === 'script' || tag === 'vite-error-overlay') continue;
227
+ if (child.getBoundingClientRect().height > 0) return false;
228
+ }
229
+ return true;
230
+ };
231
+
232
+ const recover = () => {
233
+ if (!broken || !blank()) return;
234
+ broken = false;
235
+ location.reload();
236
+ };
237
+
238
+ import.meta.hot.on('vite:beforeUpdate', recover);
239
+ }
240
+ `;
241
+ async function serveHtmlWithVite(server, res, next, htmlFilePath, documentUrl) {
242
+ try {
243
+ const html = await readFile(htmlFilePath, "utf-8");
244
+ const directory = documentUrl.slice(0, documentUrl.lastIndexOf("/"));
245
+ const transformed = await server.transformIndexHtml(
246
+ documentUrl,
247
+ toRootRelative(html, directory)
248
+ );
249
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
250
+ res.end(transformed);
251
+ } catch {
252
+ next();
253
+ }
254
+ }
255
+ async function serveStatic(res, next, absolutePath) {
256
+ try {
257
+ const data = await readFile(absolutePath);
258
+ res.setHeader("Content-Type", contentTypeFor(absolutePath));
259
+ res.end(data);
260
+ } catch {
261
+ next();
262
+ }
263
+ }
264
+ function contentTypeFor(filePath) {
265
+ const ext = filePath.toLowerCase().match(/\.[^.]+$/)?.[0];
266
+ switch (ext) {
267
+ case ".js":
268
+ case ".mjs":
269
+ return "application/javascript; charset=utf-8";
270
+ case ".css":
271
+ return "text/css; charset=utf-8";
272
+ case ".html":
273
+ return "text/html; charset=utf-8";
274
+ case ".json":
275
+ case ".map":
276
+ return "application/json; charset=utf-8";
277
+ case ".svg":
278
+ return "image/svg+xml";
279
+ case ".png":
280
+ return "image/png";
281
+ case ".jpg":
282
+ case ".jpeg":
283
+ return "image/jpeg";
284
+ case ".gif":
285
+ return "image/gif";
286
+ case ".webp":
287
+ return "image/webp";
288
+ case ".ico":
289
+ return "image/x-icon";
290
+ case ".woff":
291
+ return "font/woff";
292
+ case ".woff2":
293
+ return "font/woff2";
294
+ case ".ttf":
295
+ return "font/ttf";
296
+ case ".otf":
297
+ return "font/otf";
298
+ default:
299
+ return "application/octet-stream";
300
+ }
301
+ }
302
+ function buildRoutes(options) {
303
+ const toRoute = (prefix) => (ui) => ({
304
+ prefix: `${prefix}/${ui.definition.identifier}`,
305
+ rootDirectory: ui.rootDirectory,
306
+ entrypoint: ui.ui.entrypoint
307
+ });
308
+ return [
309
+ ...options.setups.map(toRoute("/setup-user-interfaces")),
310
+ ...options.scenarioEditors.map(toRoute("/scenario-editor-user-interfaces")),
311
+ ...options.sessionUserInterfaces.map(toRoute("/session-user-interfaces")),
312
+ ...options.waitingRoomUserInterfaces.map(toRoute("/waiting-room-user-interfaces")),
313
+ ...(options.presentations ?? []).map(toRoute("/presentation-user-interfaces")),
314
+ ...options.userInterfaces.map(toRoute("/user-interfaces"))
315
+ ];
316
+ }
317
+ function resolveAbsolute(workingDir, rootDirectory, urlPath) {
318
+ const baseDir = isAbsolute(rootDirectory) ? rootDirectory : join(workingDir, rootDirectory);
319
+ return join(baseDir, urlPath);
320
+ }
321
+ function seriousgamingUiPlugin(options) {
322
+ const { workingDir } = options;
323
+ const fixed = "surfaces" in options ? null : buildRoutes(options);
324
+ const routes = () => fixed ?? buildRoutes(options.surfaces());
325
+ return {
326
+ name: "seriousgaming-ui-plugin",
327
+ /**
328
+ * Teach Vite's module graph the same rewrite the middleware performs.
329
+ *
330
+ * A surface's HTML is served from under its prefix, so a relative
331
+ * `./src/main.tsx` in it resolves to
332
+ * `/session-user-interfaces/session/src/main.tsx`. The browser's fetch
333
+ * for that goes through connect and is rewritten below, but Vite also
334
+ * warms the modules it found in the transformed HTML, and that path
335
+ * does not pass through connect — so every page load logged a
336
+ * pre-transform error for a file that loads perfectly well. Resolving
337
+ * it here makes the two agree.
338
+ */
339
+ resolveId(id) {
340
+ if (id === RECOVERY_MODULE_ID) return RECOVERY_RESOLVED_ID;
341
+ const match = routes().find((route) => id.startsWith(route.prefix));
342
+ if (!match || isAbsolute(match.rootDirectory)) return null;
343
+ const urlPath = id.slice(match.prefix.length).split("?")[0];
344
+ if (!urlPath || urlPath.endsWith(".html")) return null;
345
+ return resolveAbsolute(workingDir, match.rootDirectory, urlPath);
346
+ },
347
+ load(id) {
348
+ return id === RECOVERY_RESOLVED_ID ? RECOVERY_MODULE : null;
349
+ },
350
+ /**
351
+ * Head-prepended, so the listener is registered before any module the
352
+ * document loads has had a chance to throw.
353
+ */
354
+ transformIndexHtml() {
355
+ return [
356
+ {
357
+ tag: "script",
358
+ attrs: { type: "module", src: RECOVERY_MODULE_URL },
359
+ injectTo: "head-prepend"
360
+ }
361
+ ];
362
+ },
363
+ configureServer(server) {
364
+ server.middlewares.use(async (req, res, next) => {
365
+ const url = req.url;
366
+ if (!url) return next();
367
+ const match = routes().find((route) => url.startsWith(route.prefix));
368
+ if (!match) return next();
369
+ let urlPath = url.replace(match.prefix, "");
370
+ if (!urlPath || urlPath === "/") {
371
+ urlPath = `/${match.entrypoint.replace(/\\/g, "/")}`;
372
+ }
373
+ const urlPathOnly = urlPath.split("?")[0];
374
+ const absolutePath = resolveAbsolute(workingDir, match.rootDirectory, urlPathOnly);
375
+ if (isAbsolute(match.rootDirectory)) {
376
+ return serveStatic(res, next, absolutePath);
377
+ }
378
+ const relativePath = "/" + relative(workingDir, absolutePath).replace(/\\/g, "/");
379
+ if (urlPathOnly.endsWith(".html")) {
380
+ return serveHtmlWithVite(server, res, next, absolutePath, relativePath);
381
+ }
382
+ req.url = relativePath;
383
+ next();
384
+ });
385
+ }
386
+ };
387
+ }
388
+
389
+ // cli/dev/brands.ts
390
+ import { existsSync, readFileSync } from "fs";
391
+ import { dirname, isAbsolute as isAbsolute2, join as join2, normalize, resolve, sep } from "path";
392
+ import { fileURLToPath } from "url";
393
+ var ROLES = ["primary", "secondary", "success", "error", "warning", "info"];
394
+ var NEUTRALS = ["background", "surface", "text"];
395
+ var COLOUR = { type: "string", minLength: 1 };
396
+ var MODE_SCHEMA = {
397
+ type: "object",
398
+ properties: Object.fromEntries([...ROLES, ...NEUTRALS].map((name) => [name, COLOUR])),
399
+ additionalProperties: false
400
+ };
401
+ var FONT_SCHEMA = {
402
+ type: "object",
403
+ required: ["family", "sources"],
404
+ properties: {
405
+ family: { type: "string", minLength: 1 },
406
+ sources: {
407
+ type: "array",
408
+ minItems: 1,
409
+ items: {
410
+ type: "object",
411
+ required: ["url"],
412
+ properties: {
413
+ url: { type: "string", minLength: 1 },
414
+ weight: { type: "string", minLength: 1 },
415
+ style: { type: "string", minLength: 1 }
416
+ },
417
+ additionalProperties: false
418
+ }
419
+ }
420
+ },
421
+ additionalProperties: false
422
+ };
423
+ var BRAND_FILE_SCHEMA = {
424
+ $schema: "http://json-schema.org/draft-07/schema#",
425
+ title: "Serious Gaming dev server brand",
426
+ type: "object",
427
+ required: ["name"],
428
+ properties: {
429
+ $schema: { type: "string" },
430
+ name: { type: "string", minLength: 1 },
431
+ light: MODE_SCHEMA,
432
+ dark: MODE_SCHEMA,
433
+ logo: {
434
+ type: "object",
435
+ properties: { onLight: { type: "string" }, onDark: { type: "string" } },
436
+ additionalProperties: false
437
+ },
438
+ loader: {
439
+ type: "object",
440
+ properties: { onLight: { type: "string" }, onDark: { type: "string" } },
441
+ additionalProperties: false
442
+ },
443
+ icon: {
444
+ oneOf: [
445
+ { type: "string", minLength: 1 },
446
+ {
447
+ type: "object",
448
+ properties: { onLight: { type: "string" }, onDark: { type: "string" } },
449
+ additionalProperties: false
450
+ }
451
+ ]
452
+ },
453
+ fonts: {
454
+ type: "object",
455
+ properties: { heading: FONT_SCHEMA, body: FONT_SCHEMA },
456
+ additionalProperties: false
457
+ }
458
+ },
459
+ additionalProperties: false
460
+ };
461
+ var SERIOUS_GAMING = "serious-gaming";
462
+ var PLAIN = "plain";
463
+ var PLAIN_LIGHT = {
464
+ primary: "#1976d2",
465
+ secondary: "#9c27b0",
466
+ success: "#2e7d32",
467
+ error: "#d32f2f",
468
+ warning: "#ed6c02",
469
+ info: "#0288d1"
470
+ };
471
+ var PLAIN_DARK = {
472
+ primary: "#90caf9",
473
+ secondary: "#ce93d8",
474
+ success: "#66bb6a",
475
+ error: "#f44336",
476
+ warning: "#ffa726",
477
+ info: "#29b6f6"
478
+ };
479
+ function builtInBrandsDirectory() {
480
+ return join2(dirname(fileURLToPath(import.meta.url)), "brands");
481
+ }
482
+ function invalid(path, problem) {
483
+ return new CliError("INPUT_INVALID", `The brand file ${path} is not valid: ${problem}`, {
484
+ hint: 'See "Preview your game in another brand" in the theming and branding guide.'
485
+ });
486
+ }
487
+ function describe(error) {
488
+ const at = error.instancePath || "(the top level)";
489
+ if (error.keyword === "additionalProperties") {
490
+ const extra = error.params.additionalProperty;
491
+ return `${at} has a field it does not take: "${extra}"`;
492
+ }
493
+ if (error.keyword === "required") {
494
+ const missing = error.params.missingProperty;
495
+ return `${at} is missing "${missing}"`;
496
+ }
497
+ return `${at} ${error.message ?? "is not valid"}`;
498
+ }
499
+ var validate = createAjv().compile(BRAND_FILE_SCHEMA);
500
+ function checkPath(file, root, value, at) {
501
+ if (value.startsWith("data:")) return;
502
+ if (/^[a-z][a-z0-9+.-]*:/i.test(value) || value.startsWith("//")) {
503
+ throw invalid(
504
+ file,
505
+ `${at} is a URL. A surface may load images and fonts only from its own origin or as data: URLs, so name a file beside the brand file instead`
506
+ );
507
+ }
508
+ if (isAbsolute2(value)) {
509
+ throw invalid(file, `${at} must be relative to the brand file, not absolute`);
510
+ }
511
+ const resolved = resolve(root, normalize(value));
512
+ if (!resolved.startsWith(root + sep)) {
513
+ throw invalid(file, `${at} reaches outside the brand file's directory`);
514
+ }
515
+ if (!existsSync(resolved)) {
516
+ throw invalid(file, `${at} names ${value}, which does not exist`);
517
+ }
518
+ }
519
+ function readBrandFile(path, id, defaults) {
520
+ const file = resolve(path);
521
+ if (!existsSync(file)) {
522
+ throw new CliError("FILE_NOT_FOUND", `No brand file at ${path}`);
523
+ }
524
+ let parsed;
525
+ try {
526
+ parsed = JSON.parse(readFileSync(file, "utf8"));
527
+ } catch (error) {
528
+ throw invalid(path, `it is not JSON (${error instanceof Error ? error.message : error})`);
529
+ }
530
+ if (!validate(parsed)) {
531
+ throw invalid(path, (validate.errors ?? []).map(describe).join("; "));
532
+ }
533
+ const data = parsed;
534
+ const root = dirname(file);
535
+ if (data.logo?.onLight) checkPath(path, root, data.logo.onLight, "/logo/onLight");
536
+ if (data.logo?.onDark) checkPath(path, root, data.logo.onDark, "/logo/onDark");
537
+ if (data.loader?.onLight) checkPath(path, root, data.loader.onLight, "/loader/onLight");
538
+ if (data.loader?.onDark) checkPath(path, root, data.loader.onDark, "/loader/onDark");
539
+ const icon = typeof data.icon === "string" ? { onLight: data.icon, onDark: data.icon } : data.icon;
540
+ if (typeof data.icon === "string") checkPath(path, root, data.icon, "/icon");
541
+ else {
542
+ if (icon?.onLight) checkPath(path, root, icon.onLight, "/icon/onLight");
543
+ if (icon?.onDark) checkPath(path, root, icon.onDark, "/icon/onDark");
544
+ }
545
+ for (const slot of ["heading", "body"]) {
546
+ data.fonts?.[slot]?.sources.forEach(
547
+ (source, index2) => checkPath(path, root, source.url, `/fonts/${slot}/sources/${index2}/url`)
548
+ );
549
+ }
550
+ return {
551
+ id,
552
+ name: data.name,
553
+ root,
554
+ light: modeOf(data.light, defaults.light),
555
+ dark: modeOf(data.dark, defaults.dark),
556
+ ...data.loader && (data.loader.onLight || data.loader.onDark) ? { loader: data.loader } : {},
557
+ brand: {
558
+ name: data.name,
559
+ ...data.logo && (data.logo.onLight || data.logo.onDark) ? { logo: data.logo } : {},
560
+ ...icon && (icon.onLight || icon.onDark) ? { icon } : {},
561
+ ...data.fonts && (data.fonts.heading || data.fonts.body) ? { fonts: data.fonts } : {}
562
+ }
563
+ };
564
+ }
565
+ function modeOf(file, defaults) {
566
+ const mode = {
567
+ primary: file?.primary ?? defaults.primary,
568
+ secondary: file?.secondary ?? defaults.secondary,
569
+ success: file?.success ?? defaults.success,
570
+ error: file?.error ?? defaults.error,
571
+ warning: file?.warning ?? defaults.warning,
572
+ info: file?.info ?? defaults.info
573
+ };
574
+ for (const name of NEUTRALS) {
575
+ const value = file?.[name];
576
+ if (value !== void 0) mode[name] = value;
577
+ }
578
+ return mode;
579
+ }
580
+ function slug(name) {
581
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "brand";
582
+ }
583
+ function loadBrands(brandFiles = []) {
584
+ const directory = builtInBrandsDirectory();
585
+ const plain = {
586
+ id: PLAIN,
587
+ name: "Plain brand",
588
+ light: PLAIN_LIGHT,
589
+ dark: PLAIN_DARK,
590
+ brand: { name: "Plain brand" }
591
+ };
592
+ const seriousGaming = readBrandFile(
593
+ join2(directory, "serious-gaming", "brand.json"),
594
+ SERIOUS_GAMING,
595
+ plain
596
+ );
597
+ const awkward = readBrandFile(
598
+ join2(directory, "awkward", "brand.json"),
599
+ "awkward",
600
+ seriousGaming
601
+ );
602
+ const taken = /* @__PURE__ */ new Set([SERIOUS_GAMING, PLAIN, "awkward"]);
603
+ const passed = brandFiles.map((path) => {
604
+ const name = readBrandName(path);
605
+ let id = slug(name);
606
+ for (let n = 2; taken.has(id); n += 1) id = `${slug(name)}-${n}`;
607
+ taken.add(id);
608
+ return readBrandFile(path, id, seriousGaming);
609
+ });
610
+ return [...passed, seriousGaming, plain, awkward];
611
+ }
612
+ function readBrandName(path) {
613
+ try {
614
+ const parsed = JSON.parse(readFileSync(resolve(path), "utf8"));
615
+ return typeof parsed.name === "string" ? parsed.name : "brand";
616
+ } catch {
617
+ return "brand";
618
+ }
619
+ }
620
+ function served(assetOrigin, id, value) {
621
+ if (value.startsWith("data:")) return value;
622
+ const path = normalize(value).split(sep).map(encodeURIComponent).join("/");
623
+ return `${assetOrigin}/assets/brands/${encodeURIComponent(id)}/${path}`;
624
+ }
625
+ function summarise(brand, assetOrigin) {
626
+ const url = (value) => served(assetOrigin, brand.id, value);
627
+ const font = (value) => value && {
628
+ family: value.family,
629
+ sources: value.sources.map((source2) => ({ ...source2, url: url(source2.url) }))
630
+ };
631
+ const source = brand.brand;
632
+ const fonts = source.fonts && {
633
+ ...source.fonts.heading ? { heading: font(source.fonts.heading) } : {},
634
+ ...source.fonts.body ? { body: font(source.fonts.body) } : {}
635
+ };
636
+ const loader = brand.loader && {
637
+ ...brand.loader.onLight ? { onLight: url(brand.loader.onLight) } : {},
638
+ ...brand.loader.onDark ? { onDark: url(brand.loader.onDark) } : {}
639
+ };
640
+ return {
641
+ id: brand.id,
642
+ name: brand.name,
643
+ ...loader ? { loader } : {},
644
+ theme: {
645
+ light: brand.light,
646
+ dark: brand.dark,
647
+ brand: {
648
+ name: source.name,
649
+ ...source.logo ? {
650
+ logo: {
651
+ ...source.logo.onLight ? { onLight: url(source.logo.onLight) } : {},
652
+ ...source.logo.onDark ? { onDark: url(source.logo.onDark) } : {}
653
+ }
654
+ } : {},
655
+ ...source.icon ? {
656
+ icon: {
657
+ ...source.icon.onLight ? { onLight: url(source.icon.onLight) } : {},
658
+ ...source.icon.onDark ? { onDark: url(source.icon.onDark) } : {}
659
+ }
660
+ } : {},
661
+ ...fonts ? { fonts } : {}
662
+ }
663
+ }
664
+ };
665
+ }
666
+
667
+ // cli/dev/console-path.ts
668
+ import { existsSync as existsSync2 } from "fs";
669
+ import { join as join3, sep as sep2 } from "path";
670
+ function resolveConsolePath(dirname3, filename, fileExists = existsSync2) {
671
+ const fromSource = filename.includes(`${sep2}cli${sep2}dev${sep2}`) || filename.includes("/cli/dev/");
672
+ const path = fromSource ? join3(dirname3, "..", "..", "dist", "dev", "console") : join3(dirname3, "dev", "console");
673
+ return { path, built: fileExists(join3(path, "index.html")) };
674
+ }
675
+ var MISSING_CONSOLE_MESSAGE = "The dev console has not been built yet. Run `pnpm build` in sdk-tools, or `pnpm exec vite build cli/dev/console` to build just the console.";
676
+
677
+ // cli/dev/package-watcher.ts
678
+ import { rmSync, watch as watchDirectory } from "fs";
679
+ import { mkdtemp, rm, writeFile } from "fs/promises";
680
+ import { tmpdir } from "os";
681
+ import { basename, join as join4, relative as relative2, sep as sep3 } from "path";
682
+ import { watch } from "chokidar";
683
+ var IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
684
+ "node_modules",
685
+ "dist",
686
+ ".seriousgaming-sdk",
687
+ ".git",
688
+ ".vite",
689
+ "coverage",
690
+ "test-results",
691
+ "playwright-report",
692
+ "testing"
693
+ ]);
694
+ var CODE_FILE = /\.(?:[cm]?[jt]sx?|json)$/;
695
+ var TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/;
696
+ function classifyChange(packagePath, path) {
697
+ const segments = relative2(packagePath, path).split(sep3);
698
+ if (segments.some((segment) => IGNORED_DIRECTORIES.has(segment))) return null;
699
+ const name = basename(path);
700
+ if (name === "seriousgaming.sdk.json" && segments.length === 1) return "manifest";
701
+ if (name.endsWith(".sdk.json")) return "bundles";
702
+ if (segments[0] === "guide" && name.endsWith(".md")) return "bundles";
703
+ if (TEST_FILE.test(name)) return null;
704
+ if (CODE_FILE.test(name)) return "logic";
705
+ return null;
706
+ }
707
+ function classifyDirectory(packagePath, path) {
708
+ const segments = relative2(packagePath, path).split(sep3);
709
+ return !segments.some((segment) => IGNORED_DIRECTORIES.has(segment));
710
+ }
711
+ async function untilWatchesDeliver(timeoutMs = 2e3) {
712
+ const directory = await mkdtemp(join4(tmpdir(), "sg-watch-"));
713
+ const removeOnExit = () => rmSync(directory, { recursive: true, force: true });
714
+ process.once("exit", removeOnExit);
715
+ const remove = () => {
716
+ process.off("exit", removeOnExit);
717
+ return rm(directory, { recursive: true, force: true });
718
+ };
719
+ let delivered = false;
720
+ let probe;
721
+ try {
722
+ probe = watchDirectory(directory, () => {
723
+ delivered = true;
724
+ });
725
+ } catch {
726
+ await remove();
727
+ return async () => {
728
+ };
729
+ }
730
+ probe.on("error", () => {
731
+ });
732
+ const deadline = Date.now() + timeoutMs;
733
+ for (let attempt = 0; !delivered && Date.now() < deadline; attempt++) {
734
+ await writeFile(join4(directory, "probe"), String(attempt));
735
+ await new Promise((resolve3) => setTimeout(resolve3, 25));
736
+ }
737
+ return async () => {
738
+ probe.close();
739
+ await remove();
740
+ };
741
+ }
742
+ async function watchPackage(packagePath, onChange, debounceMs = 150) {
743
+ const pending = /* @__PURE__ */ new Map();
744
+ const watcher = watch(packagePath, {
745
+ ignoreInitial: true,
746
+ ignored: (path) => relative2(packagePath, path).split(sep3).some((segment) => IGNORED_DIRECTORIES.has(segment))
747
+ });
748
+ const schedule = (change) => {
749
+ clearTimeout(pending.get(change));
750
+ pending.set(
751
+ change,
752
+ setTimeout(() => {
753
+ pending.delete(change);
754
+ onChange(change);
755
+ }, debounceMs)
756
+ );
757
+ };
758
+ watcher.on("all", (event, path) => {
759
+ if (event === "unlinkDir") return;
760
+ if (event === "addDir") {
761
+ if (classifyDirectory(packagePath, path)) schedule("bundles");
762
+ return;
763
+ }
764
+ const change = classifyChange(packagePath, path);
765
+ if (change) schedule(change);
766
+ });
767
+ await new Promise((resolve3) => watcher.once("ready", () => resolve3()));
768
+ const closeProbe = await untilWatchesDeliver();
769
+ return {
770
+ async close() {
771
+ for (const timer of pending.values()) clearTimeout(timer);
772
+ pending.clear();
773
+ await watcher.close();
774
+ await closeProbe();
775
+ }
776
+ };
777
+ }
778
+
779
+ // cli/dev/routes.ts
780
+ import { existsSync as existsSync3 } from "fs";
781
+ import { readFile as readFile2 } from "fs/promises";
782
+ import { isAbsolute as isAbsolute3, normalize as normalize2, resolve as resolve2, sep as sep4 } from "path";
783
+ import express from "express";
784
+
785
+ // cli/core/save-scenario.ts
786
+ var SaveScenarioError = class extends Error {
787
+ constructor(code, message) {
788
+ super(message);
789
+ this.code = code;
790
+ this.name = "SaveScenarioError";
791
+ }
792
+ code;
793
+ };
794
+ async function saveSessionScenario(session, packagePath, request) {
795
+ const draft = request.draft === true ? session.scenarioDraft(request.identifier) : null;
796
+ if (request.draft === true && draft === null) {
797
+ throw new SaveScenarioError(
798
+ "no-draft",
799
+ `No scenario editor is open on "${request.identifier}", so there is no draft to save`
800
+ );
801
+ }
802
+ const source = request.draft === true ? session.packageConfiguration()?.scenarios?.find(
803
+ (scenario) => scenario.definition.identifier === request.identifier
804
+ ) ?? null : session.activeScenario();
805
+ const schemas = settingsSchemas(session.packageConfiguration() ?? {});
806
+ const projection = session.project();
807
+ const settings = withoutLockedDefaults(draft ?? projection.settings, schemas);
808
+ const refusals = collectSettingsOverrideErrors(settings, schemas);
809
+ if (refusals.length > 0) {
810
+ throw new SaveScenarioError("denied", refusals.join("\n"));
811
+ }
812
+ const config = session.packageConfiguration();
813
+ if (config) {
814
+ const problems = await runScenarioGates({
815
+ packagePath,
816
+ config,
817
+ scenarioSettings: settings,
818
+ locale: projection.session.locale,
819
+ // Its files as a session on it would find them: a draft's in the
820
+ // scenario it was opened on and the blobs it can read, the
821
+ // session's in its scenario and every blob it holds (§6.12, §15.8).
822
+ files: {
823
+ scenarioRoot: source?.rootDirectory ?? null,
824
+ blobs: request.draft === true ? "draft" : "all"
825
+ }
826
+ });
827
+ if (problems.length > 0) {
828
+ throw new SaveScenarioError("denied", describeScenarioProblems(problems).join("\n"));
829
+ }
830
+ }
831
+ const result = await createPackageScenario({
832
+ packagePath,
833
+ settings,
834
+ activeScenarioRootDirectory: source?.rootDirectory ?? null,
835
+ identifier: request.identifier,
836
+ ...request.name === void 0 ? {} : { name: request.name },
837
+ // A name with no locale is in the game's first, as the
838
+ // package's own name is.
839
+ nameLocale: session.packageConfiguration()?.game?.definition.supportedLocales?.[0] ?? "en",
840
+ ...source ? { source: source.definition.identifier } : {},
841
+ ...request.overwrite === void 0 ? {} : { overwrite: request.overwrite }
842
+ });
843
+ await session.reloadScenarios();
844
+ if (draft) session.scenarioDraftSaved(request.identifier);
845
+ return { identifier: result.identifier };
846
+ }
847
+
848
+ // cli/dev/surfaces.ts
849
+ var SURFACE_PREFIX = {
850
+ game: "/user-interfaces",
851
+ session: "/session-user-interfaces",
852
+ setup: "/setup-user-interfaces",
853
+ "scenario-editor": "/scenario-editor-user-interfaces",
854
+ "waiting-room": "/waiting-room-user-interfaces",
855
+ presentation: "/presentation-user-interfaces"
856
+ };
857
+ function toSurface(kind, bundle, hidden) {
858
+ if (!bundle) return null;
859
+ const {
860
+ identifier,
861
+ reads,
862
+ writes,
863
+ endpoints,
864
+ crossTeamReads,
865
+ crossTeamParticipants,
866
+ settings,
867
+ configures
868
+ } = bundle.definition;
869
+ const visible = (ids) => (ids ?? []).filter((id) => !hidden.has(id));
870
+ return {
871
+ kind,
872
+ identifier,
873
+ src: `${SURFACE_PREFIX[kind]}/${encodeURIComponent(identifier)}/${bundle.ui?.entrypoint ?? "index.html"}`,
874
+ reads: visible(reads),
875
+ writes: visible(writes),
876
+ endpoints: endpoints ?? [],
877
+ crossTeamReads: visible(crossTeamReads),
878
+ crossTeamParticipants: crossTeamParticipants === true,
879
+ settings: (kind === "setup" || kind === "scenario-editor" ? configures : settings) ?? []
880
+ };
881
+ }
882
+ var SURFACE_SLOT = {
883
+ game: "ui",
884
+ session: "session",
885
+ setup: "setup",
886
+ "scenario-editor": "scenario_editor",
887
+ "waiting-room": "waiting_room",
888
+ presentation: "presentation"
889
+ };
890
+ function mountableSurfaces(config) {
891
+ if (!config) return [];
892
+ const hidden = new Set(
893
+ (config.capabilities ?? []).filter((capability) => capability.definition.scope === "private").map((capability) => capability.definition.identifier)
894
+ );
895
+ return [
896
+ toSurface("game", config.ui, hidden),
897
+ toSurface("session", config.session, hidden),
898
+ toSurface("waiting-room", config.waiting_room, hidden),
899
+ toSurface("setup", config.setup, hidden),
900
+ toSurface("scenario-editor", config.scenario_editor, hidden),
901
+ toSurface("presentation", config.presentation, hidden)
902
+ ].filter((surface) => surface !== null);
903
+ }
904
+
905
+ // cli/dev/view/batch.ts
906
+ function projectContext(context, surface) {
907
+ const declared = /* @__PURE__ */ new Set([...surface.reads, ...surface.writes]);
908
+ const projected = {};
909
+ for (const [capability, values] of Object.entries(context)) {
910
+ if (declared.has(capability)) projected[capability] = values;
911
+ }
912
+ return projected;
913
+ }
914
+ function settingsFor(state, surface, { withoutSession = false } = {}) {
915
+ const settings = withoutSession ? state.settingsWithoutSession : state.settings;
916
+ return Object.fromEntries(
917
+ surface.settings.filter((identifier) => identifier in settings).map((identifier) => [identifier, settings[identifier]])
918
+ );
919
+ }
920
+ function draftSettingsFor(state, surface, viewer) {
921
+ const scenarioId = viewer.scenario ?? null;
922
+ const draft = state.scenarioDrafts?.find((entry) => entry.scenarioId === scenarioId);
923
+ const settings = draft?.settings ?? {};
924
+ return Object.fromEntries(
925
+ surface.settings.filter((identifier) => identifier in settings).map((identifier) => [identifier, settings[identifier]])
926
+ );
927
+ }
928
+ function sessionKeyFor(state, surface, { sessionless = false } = {}) {
929
+ const outside = surface.kind === "scenario-editor" || surface.kind === "presentation" && sessionless;
930
+ return outside ? `outside-session:${state.game.identifier}` : state.session.sessionKey;
931
+ }
932
+ function themeMessages(theme) {
933
+ return [
934
+ { type: "setTheme", payload: theme.palette },
935
+ { type: "themePreferenceChanged", preference: theme.preference }
936
+ ];
937
+ }
938
+ function assetUrls(assetOrigin, editing) {
939
+ const scenarioAssets = editing === void 0 ? "scenario/" : editing.scenario === null ? "no-scenario/" : `scenarios/${encodeURIComponent(editing.scenario)}/`;
940
+ return {
941
+ blobPrefix: `${assetOrigin}/assets/blobs/`,
942
+ scenarioAssetPrefix: `${assetOrigin}/assets/${scenarioAssets}`,
943
+ sharedAssetPrefix: `${assetOrigin}/assets/shared/`,
944
+ assetAuthRedeemUrl: `${assetOrigin}/assets/auth/redeem`
945
+ };
946
+ }
947
+ function teamOf(state, teamIndex) {
948
+ if (teamIndex === void 0) return state.teams[0];
949
+ return state.teams.find((team) => team.index === teamIndex);
950
+ }
951
+ function teamList(state) {
952
+ return [...state.teams].sort((a, b) => a.index - b.index).map((team) => ({ teamId: team.teamId, index: team.index, name: team.name }));
953
+ }
954
+ var IDLE_TIMER = {
955
+ enabled: false,
956
+ paused: false,
957
+ nextTickAt: null,
958
+ intervalMs: null,
959
+ pausedAt: null,
960
+ pausedMs: 0,
961
+ extendedMs: 0,
962
+ scheduleStartedAt: null
963
+ };
964
+ function buildBatch(options) {
965
+ const { surface, state, theme, origin, assetOrigin } = options;
966
+ const common = [
967
+ { type: "setLocale", payload: { locale: state.session.locale } },
968
+ {
969
+ type: "setAssetUrls",
970
+ payload: assetUrls(
971
+ assetOrigin ?? origin,
972
+ surface.kind === "scenario-editor" ? { scenario: options.viewer.scenario ?? null } : void 0
973
+ )
974
+ },
975
+ ...theme ? themeMessages(theme) : []
976
+ ];
977
+ switch (surface.kind) {
978
+ case "game":
979
+ case "waiting-room":
980
+ return [...playerBatch(options), ...common];
981
+ case "session":
982
+ return [...sessionBatch(options), ...common];
983
+ // The two settings editors are sent the same batch (§12.3): neither is
984
+ // told which slot it fills, since each is its own bundle.
985
+ case "setup":
986
+ return [{ type: "setSettings", payload: settingsFor(state, surface) }, ...common];
987
+ case "scenario-editor":
988
+ return [
989
+ { type: "setSettings", payload: draftSettingsFor(state, surface, options.viewer) },
990
+ ...common
991
+ ];
992
+ case "presentation":
993
+ return [...presentationBatch(options), ...common];
994
+ }
995
+ return common;
996
+ }
997
+ function crossTeamData(state, surface, ownTeamIndex) {
998
+ const across = new Set(surface.crossTeamReads);
999
+ return [...state.teams].sort((a, b) => a.index - b.index).map((team) => ({
1000
+ teamId: team.teamId,
1001
+ index: team.index,
1002
+ name: team.name,
1003
+ context: team.index === ownTeamIndex ? projectContext(team.context, surface) : Object.fromEntries(
1004
+ Object.entries(team.context).filter(
1005
+ ([capability]) => across.has(capability)
1006
+ )
1007
+ )
1008
+ }));
1009
+ }
1010
+ function joinUrl(origin, teamIndex) {
1011
+ return `${origin}/team/${teamIndex + 1}/join?bare`;
1012
+ }
1013
+ function playerBatch({
1014
+ surface,
1015
+ state,
1016
+ viewer,
1017
+ origin,
1018
+ roundProcessing
1019
+ }) {
1020
+ const team = teamOf(state, viewer.teamIndex);
1021
+ const participant = viewer.observer ? void 0 : team?.participants.find((p) => p.id === viewer.participantId) ?? team?.participants[0];
1022
+ const messages = [
1023
+ {
1024
+ type: "stateChanged",
1025
+ payload: projectContext(team?.context ?? {}, surface),
1026
+ // §12.5: the head tick, so a review scrubber can be bounded and a
1027
+ // cache invalidated on undo.
1028
+ completedTicks: team?.completedTicks ?? state.session.completedTicks
1029
+ },
1030
+ { type: "setSettings", payload: settingsFor(state, surface) }
1031
+ ];
1032
+ if (participant) {
1033
+ messages.push({
1034
+ type: "setParticipant",
1035
+ payload: {
1036
+ id: participant.id,
1037
+ name: participant.name,
1038
+ index: participant.index,
1039
+ teamId: team?.teamId ?? "team-1"
1040
+ },
1041
+ // There are no accounts here, so every name is the participant's
1042
+ // own to change (§12.5).
1043
+ canRenameSelf: true
1044
+ });
1045
+ }
1046
+ messages.push(
1047
+ { type: "setViewerRole", role: viewer.observer ? "observer" : "participant" },
1048
+ { type: "setRunKind", runKind: state.session.runKind },
1049
+ { type: "setScenarioName", scenarioName: state.game.scenarioName },
1050
+ {
1051
+ type: "setOwnTeam",
1052
+ payload: team ? { teamId: team.teamId, index: team.index, name: team.name } : { teamId: "team-1", index: 0, name: "Team 1" }
1053
+ },
1054
+ {
1055
+ type: "setOwnTeamJoinLink",
1056
+ payload: team ? { joinUrl: joinUrl(origin, team.index) } : (
1057
+ // §12.3, as amended: a host with nothing to offer says so
1058
+ // rather than staying silent, so a surface rendering a join
1059
+ // panel shows nothing instead of waiting for a message that
1060
+ // never comes.
1061
+ null
1062
+ )
1063
+ },
1064
+ { type: "setParticipantList", participants: team?.participants ?? [] },
1065
+ { type: "setTeamList", payload: teamList(state) },
1066
+ { type: "setTimer", payload: team?.timer ?? IDLE_TIMER }
1067
+ );
1068
+ if (surface.kind === "game") {
1069
+ messages.push({ type: "setRoundProcessing", processing: roundProcessing === true });
1070
+ }
1071
+ if ((surface.kind === "game" || surface.kind === "waiting-room") && surface.crossTeamReads.length > 0 && state.session.mode === "shared-state") {
1072
+ messages.push({
1073
+ type: "setCrossTeamData",
1074
+ payload: crossTeamData(state, surface, team?.index)
1075
+ });
1076
+ }
1077
+ return messages;
1078
+ }
1079
+ function sessionBatch({
1080
+ surface,
1081
+ state,
1082
+ gameName,
1083
+ origin,
1084
+ overlays
1085
+ }) {
1086
+ return [
1087
+ {
1088
+ type: "setSessionMeta",
1089
+ payload: {
1090
+ sessionId: "dev-session",
1091
+ name: gameName,
1092
+ readOnly: false,
1093
+ waitingRoomOpen: state.session.waitingRoomOpen,
1094
+ joinPin: null,
1095
+ canSetLocale: true
1096
+ }
1097
+ },
1098
+ { type: "setSessionData", payload: sessionData(state, surface) },
1099
+ { type: "setSettings", payload: settingsFor(state, surface) },
1100
+ { type: "setTeamConfiguration", payload: teamConfiguration(state) },
1101
+ { type: "setTeamList", payload: teamList(state) },
1102
+ {
1103
+ type: "setParticipantList",
1104
+ participants: participantList(state)
1105
+ },
1106
+ { type: "setTeamLinks", payload: teamLinks(state, origin) },
1107
+ { type: "setWalkthroughLink", payload: walkthroughLink(origin) },
1108
+ { type: "setRunKind", runKind: state.session.runKind },
1109
+ { type: "setScenarioName", scenarioName: state.game.scenarioName },
1110
+ { type: "setAvailableOverlays", overlays: overlays ?? availableOverlays() }
1111
+ ];
1112
+ }
1113
+ function presentationBatch({
1114
+ surface,
1115
+ state,
1116
+ gameName,
1117
+ origin,
1118
+ sessionless
1119
+ }) {
1120
+ return [
1121
+ {
1122
+ type: "setPresentation",
1123
+ payload: {
1124
+ game: {
1125
+ name: state.game.name,
1126
+ // Without a session, as the scenario resolves it alone (§6.15.1).
1127
+ maxTicks: sessionless ? gameSettingsOf(state.settingsWithoutSession).maxTicks : state.session.maxTicks,
1128
+ mode: state.session.mode,
1129
+ scenarioName: state.game.scenarioName
1130
+ },
1131
+ session: sessionless ? null : {
1132
+ // The dev server runs one session; its id is the
1133
+ // one the session surface is told (above).
1134
+ id: "dev-session",
1135
+ name: gameName,
1136
+ completedTicks: Math.max(
1137
+ state.session.completedTicks,
1138
+ ...state.teams.map((team) => team.completedTicks)
1139
+ ),
1140
+ data: sessionData(state, surface),
1141
+ teams: teamList(state),
1142
+ participants: participantList(state),
1143
+ // A deck puts these on the projector, so no observe
1144
+ // URL: watching a team is the facilitator's tool.
1145
+ joinLinks: teamLinks(state, origin).map(({ teamId, joinUrl: joinUrl2 }) => ({
1146
+ teamId,
1147
+ joinUrl: joinUrl2
1148
+ })),
1149
+ joinPin: null
1150
+ }
1151
+ }
1152
+ },
1153
+ {
1154
+ type: "setSettings",
1155
+ payload: settingsFor(state, surface, { withoutSession: sessionless })
1156
+ }
1157
+ ];
1158
+ }
1159
+ function walkthroughLink(origin) {
1160
+ return { url: `${origin}/walkthrough` };
1161
+ }
1162
+ function availableOverlays(offered = {}) {
1163
+ return [
1164
+ ...offered.guide ? ["facilitator-guide"] : [],
1165
+ "print-sheets",
1166
+ ...offered.presentation ? ["presentation"] : []
1167
+ ];
1168
+ }
1169
+ function offersPresentationOverlay(config) {
1170
+ return config?.presentation !== void 0 && (config.requires ?? []).includes(PRESENTATION_OVERLAY);
1171
+ }
1172
+ var PRESENTATION_OVERLAY = "presentation-overlay";
1173
+ function participantList(state) {
1174
+ return state.teams.flatMap(
1175
+ (team) => team.participants.map((participant) => ({
1176
+ id: participant.id,
1177
+ name: participant.name,
1178
+ index: participant.index,
1179
+ connected: participant.connected,
1180
+ teamId: team.teamId
1181
+ }))
1182
+ );
1183
+ }
1184
+ function teamLinks(state, origin) {
1185
+ return [...state.teams].sort((a, b) => a.index - b.index).map((team) => ({
1186
+ teamId: team.teamId,
1187
+ joinUrl: joinUrl(origin, team.index),
1188
+ observeUrl: `${origin}/team/${team.index + 1}/observe`
1189
+ }));
1190
+ }
1191
+ function teamConfiguration(state) {
1192
+ return {
1193
+ mode: state.session.mode,
1194
+ ...state.session.teamBounds.min === void 0 ? {} : { min: state.session.teamBounds.min },
1195
+ max: state.session.teamBounds.max
1196
+ };
1197
+ }
1198
+ function sessionData(state, surface) {
1199
+ const teams = {};
1200
+ for (const team of state.teams) {
1201
+ const own = {};
1202
+ for (const [capability, values] of Object.entries(team.context)) {
1203
+ if (!(capability in state.shared)) own[capability] = values;
1204
+ }
1205
+ teams[team.teamId] = {
1206
+ context: projectContext(own, surface),
1207
+ completedTicks: team.completedTicks,
1208
+ timer: team.timer ?? IDLE_TIMER,
1209
+ // Monotonic per delivery. One session, one host, so the tick is a
1210
+ // sufficient clock; the wrapper only compares it with itself.
1211
+ revision: team.completedTicks
1212
+ };
1213
+ }
1214
+ return {
1215
+ // The dev server only ever sends snapshots, so the revision is a
1216
+ // baseline the wrapper never compares a delta against.
1217
+ shared: {
1218
+ context: projectContext(state.shared, surface),
1219
+ revision: state.session.completedTicks
1220
+ },
1221
+ teams
1222
+ };
1223
+ }
1224
+
1225
+ // cli/dev/routes.ts
1226
+ function runOf(req) {
1227
+ return req.query.run === "walkthrough" ? "walkthrough" : "session";
1228
+ }
1229
+ function registerRoutes(app, deps) {
1230
+ const { session, packagePath, runFor } = deps;
1231
+ app.get("/api/state", async (req, res) => {
1232
+ res.json((await runFor(runOf(req))).project());
1233
+ });
1234
+ app.get("/api/surfaces", (req, res) => {
1235
+ const origin = deps.assetOrigin(req.headers.host);
1236
+ res.json(
1237
+ mountableSurfaces(session.packageConfiguration()).map((mountable) => ({
1238
+ ...mountable,
1239
+ origin
1240
+ }))
1241
+ );
1242
+ });
1243
+ app.get("/api/session", async (req, res) => {
1244
+ const run = await runFor(runOf(req));
1245
+ res.json({
1246
+ instanceId: deps.instanceId,
1247
+ inSetup: run.inSetup,
1248
+ diagnostics: run.diagnostics(),
1249
+ sessionOverrides: run.sessionOverrides(),
1250
+ pending: run.pendingChanges(),
1251
+ warnings: deps.notices(run)
1252
+ });
1253
+ });
1254
+ app.post("/api/command", express.json({ limit: "20mb" }), async (req, res) => {
1255
+ const invalid2 = commandError(req.body);
1256
+ if (invalid2) {
1257
+ res.status(400).json({ error: invalid2 });
1258
+ return;
1259
+ }
1260
+ const command = req.body;
1261
+ try {
1262
+ if (rebuildsWalkthrough(command, runOf(req))) {
1263
+ res.json(await deps.settleWalkthroughReset(command));
1264
+ return;
1265
+ }
1266
+ const run = await runFor(runOf(req));
1267
+ const result = isQuery(command) ? await run.query(command) : await run.submit(command);
1268
+ if (command.type === "callEndpoint" && command.external && "type" in result && result.type === "endpoint") {
1269
+ const blobs = blobLinks(
1270
+ result.response,
1271
+ (blobId) => `${req.protocol}://${req.get("host")}/api/blobs/${encodeURIComponent(blobId)}`
1272
+ );
1273
+ res.json(Object.keys(blobs).length > 0 ? { ...result, blobs } : result);
1274
+ return;
1275
+ }
1276
+ res.json(result);
1277
+ } catch (error) {
1278
+ res.status(500).json({ error: errorMessage(error, "Command failed") });
1279
+ }
1280
+ });
1281
+ app.post("/api/walkthrough/reset", async (_req, res) => {
1282
+ try {
1283
+ res.json((await deps.resetWalkthrough()).project());
1284
+ } catch (error) {
1285
+ res.status(500).json({ error: errorMessage(error, "Walkthrough reset failed") });
1286
+ }
1287
+ });
1288
+ app.get("/api/scenarios", (_req, res) => {
1289
+ const config = session.packageConfiguration();
1290
+ res.json({
1291
+ activeScenarioId: session.activeScenario()?.definition.identifier ?? null,
1292
+ scenarios: (config?.scenarios ?? []).map((scenario) => ({
1293
+ id: scenario.definition.identifier,
1294
+ default: scenario.definition.default === true,
1295
+ locales: scenario.definition.locales ?? {}
1296
+ }))
1297
+ });
1298
+ });
1299
+ app.get("/api/brands", (req, res) => {
1300
+ const assetOrigin = deps.assetOrigin(req.headers.host);
1301
+ res.json({ brands: deps.brands().map((brand) => summarise(brand, assetOrigin)) });
1302
+ });
1303
+ app.get("/api/locales", (_req, res) => {
1304
+ const game = session.packageConfiguration()?.game;
1305
+ res.json({
1306
+ active: session.project().session.locale,
1307
+ supported: game?.definition.supportedLocales ?? ["en"],
1308
+ names: game?.definition.locales ?? {}
1309
+ });
1310
+ });
1311
+ app.post("/api/scenarios", express.json(), async (req, res) => {
1312
+ const body = req.body;
1313
+ if (typeof body?.identifier !== "string") {
1314
+ res.status(400).json({ error: "An identifier is required" });
1315
+ return;
1316
+ }
1317
+ try {
1318
+ const result = await saveSessionScenario(session, packagePath, {
1319
+ identifier: body.identifier,
1320
+ ...typeof body.name === "string" ? { name: body.name } : {},
1321
+ ...body.overwrite === void 0 ? {} : { overwrite: body.overwrite },
1322
+ ...body.draft === true ? { draft: true } : {}
1323
+ });
1324
+ res.json(result);
1325
+ } catch (error) {
1326
+ const code = error instanceof PackageScenarioError || error instanceof SaveScenarioError ? error.code : "error";
1327
+ res.status(code === "denied" ? 403 : 400).json({
1328
+ error: errorMessage(error, "Could not save"),
1329
+ code
1330
+ });
1331
+ }
1332
+ });
1333
+ app.delete("/api/scenarios/:identifier", async (req, res) => {
1334
+ const { identifier } = req.params;
1335
+ if (session.activeScenario()?.definition.identifier === identifier) {
1336
+ res.status(409).json({
1337
+ error: "This scenario is active. Switch to another one first.",
1338
+ code: "scenario-active"
1339
+ });
1340
+ return;
1341
+ }
1342
+ try {
1343
+ await deletePackageScenario(packagePath, identifier);
1344
+ await session.reloadScenarios();
1345
+ res.json({ identifier });
1346
+ } catch (error) {
1347
+ const code = error instanceof PackageScenarioError ? error.code : "error";
1348
+ res.status(400).json({ error: errorMessage(error, "Could not delete"), code });
1349
+ }
1350
+ });
1351
+ app.post("/api/blobs", express.raw({ type: () => true, limit: "20mb" }), async (req, res) => {
1352
+ const name = req.headers["x-blob-name"];
1353
+ const mimeType = req.headers["x-blob-mime"];
1354
+ if (typeof name !== "string" || typeof mimeType !== "string") {
1355
+ res.status(400).json({ error: "Missing x-blob-name or x-blob-mime headers" });
1356
+ return;
1357
+ }
1358
+ let fileName;
1359
+ try {
1360
+ fileName = decodeURIComponent(name);
1361
+ } catch {
1362
+ res.status(400).json({ error: "x-blob-name must be URI-encoded" });
1363
+ return;
1364
+ }
1365
+ if (!Buffer.isBuffer(req.body) || req.body.length === 0) {
1366
+ res.status(400).json({ error: "The upload has no bytes: send the file as the body" });
1367
+ return;
1368
+ }
1369
+ const requested = req.headers["x-blob-retention"];
1370
+ const retention = requested === "settings" || requested === "scenario" ? requested : "game";
1371
+ try {
1372
+ const blobId = await storeBlob(
1373
+ packagePath,
1374
+ req.body,
1375
+ fileName,
1376
+ mimeType,
1377
+ retention
1378
+ );
1379
+ res.json({ reference: `blob:${blobId}` });
1380
+ } catch (error) {
1381
+ res.status(500).json({ error: errorMessage(error, "Failed to store the blob") });
1382
+ }
1383
+ });
1384
+ registerAssetRoutes(app, deps, "/api");
1385
+ app.get("/api/guide", (_req, res) => {
1386
+ res.json({ guide: session.effectiveGuide() });
1387
+ });
1388
+ app.get("/api/overlays", (_req, res) => {
1389
+ res.json({
1390
+ overlays: availableOverlays({
1391
+ guide: session.effectiveGuide() !== null,
1392
+ presentation: offersPresentationOverlay(session.packageConfiguration())
1393
+ })
1394
+ });
1395
+ });
1396
+ app.get("/api/guide/content/:locale/:chapter", async (req, res) => {
1397
+ const guide = session.guide();
1398
+ if (!guide) {
1399
+ res.status(404).json({ error: "This package declares no facilitator guide" });
1400
+ return;
1401
+ }
1402
+ const root = isAbsolute3(guide.rootDirectory) ? guide.rootDirectory : resolve2(packagePath, guide.rootDirectory);
1403
+ const file = resolve2(
1404
+ root,
1405
+ "content",
1406
+ normalize2(req.params.locale),
1407
+ normalize2(req.params.chapter)
1408
+ );
1409
+ const contentRoot = resolve2(root, "content");
1410
+ if (!file.startsWith(contentRoot + sep4) || !existsSync3(file)) {
1411
+ res.status(404).json({ error: "Chapter not found" });
1412
+ return;
1413
+ }
1414
+ res.type("text/markdown").send(await readFile2(file, "utf-8"));
1415
+ });
1416
+ app.get("/api/guide/assets/*path", (req, res) => {
1417
+ const guide = session.guide();
1418
+ if (!guide) {
1419
+ res.status(404).send("This package declares no facilitator guide");
1420
+ return;
1421
+ }
1422
+ const root = isAbsolute3(guide.rootDirectory) ? guide.rootDirectory : resolve2(packagePath, guide.rootDirectory);
1423
+ serveAsset(req, res, resolve2(root, "assets"));
1424
+ });
1425
+ app.use("/api", (req, res) => {
1426
+ res.status(404).json({ error: `No such route: ${req.method} /api${req.path}` });
1427
+ });
1428
+ }
1429
+ var ASSET_PATHS = {
1430
+ "/api": {
1431
+ blob: "/api/blobs/:blobId",
1432
+ scenario: "/api/scenario/assets/*path",
1433
+ editedScenario: "/api/scenarios/:scenario/assets/*path",
1434
+ noScenario: "/api/no-scenario/assets/*path",
1435
+ shared: "/api/shared/assets/*path",
1436
+ redeem: "/api/asset-auth/redeem"
1437
+ },
1438
+ "/assets": {
1439
+ blob: "/assets/blobs/:blobId",
1440
+ scenario: "/assets/scenario/*path",
1441
+ editedScenario: "/assets/scenarios/:scenario/*path",
1442
+ noScenario: "/assets/no-scenario/*path",
1443
+ shared: "/assets/shared/*path",
1444
+ redeem: "/assets/auth/redeem"
1445
+ }
1446
+ };
1447
+ function registerAssetRoutes(app, deps, prefix) {
1448
+ const { session, packagePath } = deps;
1449
+ const paths = ASSET_PATHS[prefix];
1450
+ app.post(paths.redeem, express.json(), (req, res) => {
1451
+ const body = req.body;
1452
+ if (typeof body?.token !== "string") {
1453
+ res.status(400).json({ error: "token required" });
1454
+ return;
1455
+ }
1456
+ res.setHeader("Set-Cookie", `asset_auth=dev; Path=${prefix}; SameSite=Lax`);
1457
+ res.json({ ok: true });
1458
+ });
1459
+ app.get(paths.blob, async (req, res) => {
1460
+ let blob;
1461
+ try {
1462
+ blob = await readBlob(packagePath, req.params.blobId);
1463
+ } catch {
1464
+ res.status(404).send("Blob not found");
1465
+ return;
1466
+ }
1467
+ res.setHeader("Content-Type", blob.mimeType);
1468
+ res.setHeader("X-Asset-Name", encodeURIComponent(blob.name));
1469
+ res.setHeader("Access-Control-Expose-Headers", "X-Asset-Name");
1470
+ sendBytes(req, res, blob.data);
1471
+ });
1472
+ app.get(paths.scenario, (req, res) => {
1473
+ const scenario = session.activeScenario();
1474
+ if (!scenario) {
1475
+ res.status(404).send("No active scenario");
1476
+ return;
1477
+ }
1478
+ serveAsset(req, res, scenarioAssets(scenario));
1479
+ });
1480
+ app.get(paths.editedScenario, (req, res) => {
1481
+ const scenario = session.packageConfiguration()?.scenarios?.find((entry) => entry.definition.identifier === req.params.scenario);
1482
+ if (!scenario) {
1483
+ res.status(404).send("No such scenario");
1484
+ return;
1485
+ }
1486
+ serveAsset(req, res, scenarioAssets(scenario));
1487
+ });
1488
+ app.get(paths.noScenario, (_req, res) => {
1489
+ res.status(404).send("No scenario is being edited");
1490
+ });
1491
+ function scenarioAssets(scenario) {
1492
+ const root = isAbsolute3(scenario.rootDirectory) ? scenario.rootDirectory : resolve2(packagePath, scenario.rootDirectory);
1493
+ return resolve2(root, "assets");
1494
+ }
1495
+ app.get(paths.shared, (req, res) => {
1496
+ serveAsset(req, res, resolve2(packagePath, "shared-assets"));
1497
+ });
1498
+ }
1499
+ function registerBrandRoutes(app, brands) {
1500
+ app.get("/assets/brands/:brand/*path", (req, res) => {
1501
+ const brand = brands().find((candidate) => candidate.id === req.params.brand);
1502
+ if (!brand?.root) {
1503
+ res.status(404).send("No such brand");
1504
+ return;
1505
+ }
1506
+ serveAsset(req, res, brand.root);
1507
+ });
1508
+ }
1509
+ function serveAsset(req, res, root) {
1510
+ const raw = req.params.path;
1511
+ const assetPath = Array.isArray(raw) ? raw.join("/") : raw;
1512
+ if (!assetPath) {
1513
+ res.status(400).send("Asset path required");
1514
+ return;
1515
+ }
1516
+ const resolved = resolve2(root, normalize2(assetPath));
1517
+ if (resolved !== root && !resolved.startsWith(root + sep4)) {
1518
+ res.status(403).send("Forbidden");
1519
+ return;
1520
+ }
1521
+ if (!existsSync3(resolved)) {
1522
+ res.status(404).send("Asset not found");
1523
+ return;
1524
+ }
1525
+ res.setHeader("Content-Type", mediaTypeOf(resolved));
1526
+ res.setHeader("X-Asset-Name", encodeURIComponent(assetPath.split("/").pop() ?? assetPath));
1527
+ res.setHeader("Access-Control-Expose-Headers", "X-Asset-Name");
1528
+ res.sendFile(normalize2(assetPath), { root });
1529
+ }
1530
+ function sendBytes(req, res, data) {
1531
+ res.setHeader("Accept-Ranges", "bytes");
1532
+ const ranges = req.headers.range === void 0 ? void 0 : req.range(data.length);
1533
+ if (ranges === -1) {
1534
+ res.status(416).setHeader("Content-Range", `bytes */${data.length}`);
1535
+ res.end();
1536
+ return;
1537
+ }
1538
+ if (Array.isArray(ranges) && ranges.type === "bytes" && ranges.length === 1) {
1539
+ const [{ start, end }] = ranges;
1540
+ res.status(206).setHeader("Content-Range", `bytes ${start}-${end}/${data.length}`);
1541
+ res.send(data.subarray(start, end + 1));
1542
+ return;
1543
+ }
1544
+ res.send(data);
1545
+ }
1546
+
1547
+ // cli/dev/view/commands.ts
1548
+ var FRAME_COMMANDS = {
1549
+ game: /* @__PURE__ */ new Set(["updateData", "requestTick", "renameOwnTeam", "renameSelf"]),
1550
+ "waiting-room": /* @__PURE__ */ new Set(["updateData", "requestTick", "renameOwnTeam", "renameSelf"]),
1551
+ session: /* @__PURE__ */ new Set([
1552
+ "updateSessionData",
1553
+ "updateSharedData",
1554
+ "requestTick",
1555
+ "undoTick",
1556
+ "resetGame",
1557
+ "resetWalkthrough",
1558
+ "setWaitingRoom",
1559
+ "setLocale",
1560
+ "createTeam",
1561
+ "renameTeam",
1562
+ "renameParticipant",
1563
+ "moveParticipant",
1564
+ "deleteTeam",
1565
+ "pauseTimer",
1566
+ "resumeTimer",
1567
+ "extendTick"
1568
+ ]),
1569
+ setup: /* @__PURE__ */ new Set(["updateSettings", "requestPlay"]),
1570
+ // A scenario editor has no session to start (§6.5), so its requestPlay is
1571
+ // refused like any other message outside its set.
1572
+ "scenario-editor": /* @__PURE__ */ new Set(["updateSettings"]),
1573
+ // Read-only by construction (§6.15): there is nothing a deck may ask for.
1574
+ presentation: /* @__PURE__ */ new Set()
1575
+ };
1576
+ var NO_TEAM_ID = {
1577
+ setWaitingRoom: "The waiting room is session-wide, so setWaitingRoom takes no teamId",
1578
+ renameOwnTeam: "renameOwnTeam renames the caller's own team, which the host resolves; it takes no teamId",
1579
+ resetWalkthrough: "A walkthrough holds one team, so resetWalkthrough takes no teamId",
1580
+ setLocale: "The locale is the session's, so setLocale takes no teamId",
1581
+ renameSelf: "renameSelf renames the caller, whom the host resolves; it takes no teamId"
1582
+ };
1583
+ var FRAME_QUERIES = {
1584
+ game: /* @__PURE__ */ new Set(["callEndpoint", "getPastState", "getAllTeamsParticipants"]),
1585
+ "waiting-room": /* @__PURE__ */ new Set(["callEndpoint", "getPastState", "getAllTeamsParticipants"]),
1586
+ session: /* @__PURE__ */ new Set(["callEndpoint", "getPastState"]),
1587
+ setup: /* @__PURE__ */ new Set(["callEndpoint"]),
1588
+ "scenario-editor": /* @__PURE__ */ new Set(["callEndpoint"]),
1589
+ presentation: /* @__PURE__ */ new Set(["getPastState"])
1590
+ };
1591
+ function teamScope(viewer) {
1592
+ return viewer.teamIndex === void 0 ? {} : { teamIndex: viewer.teamIndex };
1593
+ }
1594
+ function actorOf(viewer) {
1595
+ return viewer.participantId === void 0 ? {} : {
1596
+ participantId: viewer.participantId,
1597
+ teamId: `team-${(viewer.teamIndex ?? 0) + 1}`
1598
+ };
1599
+ }
1600
+ function roleOf(viewer) {
1601
+ return viewer.role === void 0 ? {} : { viewerRole: viewer.role };
1602
+ }
1603
+ function viewerFields(viewer) {
1604
+ return { ...teamScope(viewer), ...actorOf(viewer), ...roleOf(viewer) };
1605
+ }
1606
+ function teamIndexOf(teamId) {
1607
+ const match = typeof teamId === "string" ? /^team-([1-9]\d*)$/.exec(teamId) : null;
1608
+ return match ? Number(match[1]) - 1 : -1;
1609
+ }
1610
+ function namedOr(message, fallback) {
1611
+ return message.teamId === void 0 ? fallback : { teamIndex: teamIndexOf(message.teamId) };
1612
+ }
1613
+ function isFrameRefusal(value) {
1614
+ return typeof value === "object" && value !== null && "refused" in value;
1615
+ }
1616
+ function commandFor(message, surface, viewer) {
1617
+ if (!FRAME_COMMANDS[surface.kind].has(message.type)) return null;
1618
+ if (message.teamId !== void 0 && message.type in NO_TEAM_ID) {
1619
+ return { refused: NO_TEAM_ID[message.type] };
1620
+ }
1621
+ if (message.type === "renameSelf" && message.participantId !== void 0) {
1622
+ return {
1623
+ refused: "renameSelf renames the caller, whom the host resolves; it takes no participantId"
1624
+ };
1625
+ }
1626
+ const scope = teamScope(viewer);
1627
+ const actor = actorOf(viewer);
1628
+ const role = roleOf(viewer);
1629
+ switch (message.type) {
1630
+ case "updateData":
1631
+ return {
1632
+ type: "updateContext",
1633
+ uiIdentifier: surface.identifier,
1634
+ payload: message.payload,
1635
+ ...message.deletes ? { deletes: message.deletes } : {},
1636
+ ...scope,
1637
+ ...actor,
1638
+ ...role
1639
+ };
1640
+ case "updateSessionData":
1641
+ return {
1642
+ type: "updateContext",
1643
+ payload: message.payload,
1644
+ teamIndex: teamIndexOf(message.teamId),
1645
+ sessionUiIdentifier: surface.identifier,
1646
+ ...message.deletes ? { deletes: message.deletes } : {}
1647
+ };
1648
+ case "updateSharedData":
1649
+ return {
1650
+ type: "updateSharedContext",
1651
+ uiIdentifier: surface.identifier,
1652
+ payload: message.payload,
1653
+ ...message.deletes ? { deletes: message.deletes } : {}
1654
+ };
1655
+ case "updateSettings":
1656
+ return surface.kind === "scenario-editor" ? {
1657
+ type: "updateScenarioDraft",
1658
+ scenarioId: viewer.scenario ?? null,
1659
+ payload: message.payload,
1660
+ uiIdentifier: surface.identifier
1661
+ } : {
1662
+ type: "updateSettings",
1663
+ payload: message.payload,
1664
+ uiIdentifier: surface.identifier
1665
+ };
1666
+ case "requestTick":
1667
+ return {
1668
+ type: "tick",
1669
+ ...namedOr(message, scope),
1670
+ ...surface.kind === "session" ? {} : { ...actor, ...role }
1671
+ };
1672
+ case "undoTick":
1673
+ return {
1674
+ type: "undo",
1675
+ ...namedOr(message, scope)
1676
+ };
1677
+ case "resetGame":
1678
+ return {
1679
+ type: "reset",
1680
+ ...namedOr(message, {})
1681
+ };
1682
+ case "setWaitingRoom":
1683
+ return { type: "setWaitingRoom", open: message.open === true };
1684
+ case "setLocale":
1685
+ return { type: "setLocale", locale: String(message.locale) };
1686
+ case "resetWalkthrough":
1687
+ return { type: "resetWalkthrough" };
1688
+ case "createTeam":
1689
+ return {
1690
+ type: "addTeam",
1691
+ ...typeof message.name === "string" ? { name: message.name } : {}
1692
+ };
1693
+ case "renameTeam":
1694
+ return {
1695
+ type: "renameTeam",
1696
+ teamId: String(message.teamId),
1697
+ name: String(message.name)
1698
+ };
1699
+ case "renameOwnTeam":
1700
+ return { type: "renameOwnTeam", name: String(message.name), ...actor };
1701
+ case "renameSelf":
1702
+ return { type: "renameSelf", name: String(message.name), ...actor };
1703
+ case "renameParticipant":
1704
+ return {
1705
+ type: "renameParticipant",
1706
+ participantId: String(message.participantId),
1707
+ name: String(message.name)
1708
+ };
1709
+ case "moveParticipant":
1710
+ return {
1711
+ type: "moveParticipant",
1712
+ participantId: String(message.participantId),
1713
+ teamId: String(message.teamId)
1714
+ };
1715
+ case "deleteTeam":
1716
+ return { type: "removeTeam", teamIndex: teamIndexOf(message.teamId) };
1717
+ case "requestPlay":
1718
+ return { type: "play" };
1719
+ case "pauseTimer":
1720
+ return {
1721
+ type: "pauseTimer",
1722
+ ...namedOr(message, scope)
1723
+ };
1724
+ case "resumeTimer":
1725
+ return {
1726
+ type: "resumeTimer",
1727
+ ...namedOr(message, scope)
1728
+ };
1729
+ case "extendTick":
1730
+ return {
1731
+ type: "extendTick",
1732
+ byMs: Number(message.byMs ?? 0),
1733
+ ...namedOr(message, scope)
1734
+ };
1735
+ default:
1736
+ return null;
1737
+ }
1738
+ }
1739
+ function queryFor(message, surface, viewer) {
1740
+ if (!FRAME_QUERIES[surface.kind].has(message.type)) return null;
1741
+ switch (message.type) {
1742
+ case "callEndpoint":
1743
+ return {
1744
+ type: "callEndpoint",
1745
+ endpointIdentifier: String(message.endpointIdentifier),
1746
+ request: message.request,
1747
+ uiIdentifier: surface.identifier,
1748
+ // §6.12's `caller` is only as good as what reaches the session.
1749
+ // This carried nothing, so every call from a player surface
1750
+ // arrived anonymous: read against whichever board the executor
1751
+ // last held, and stamped `role: 'facilitator'` (#566).
1752
+ ...viewerFields(viewer),
1753
+ // The editor's endpoints read its draft of the scenario it is
1754
+ // open on, not the session's settings (§6.12).
1755
+ ...surface.kind === "scenario-editor" ? { scenarioId: viewer.scenario ?? null } : {}
1756
+ };
1757
+ case "getPastState":
1758
+ return {
1759
+ type: "getPastState",
1760
+ query: message.query,
1761
+ uiIdentifier: surface.identifier,
1762
+ ...viewer.teamIndex === void 0 ? {} : { teamId: `team-${viewer.teamIndex + 1}` }
1763
+ };
1764
+ case "getAllTeamsParticipants":
1765
+ return { type: "getAllTeamsParticipants", uiIdentifier: surface.identifier };
1766
+ default:
1767
+ return null;
1768
+ }
1769
+ }
1770
+
1771
+ // cli/dev/view/viewer.ts
1772
+ function resolveViewer(state, route) {
1773
+ const base = {
1774
+ ...route.teamIndex === void 0 ? {} : { teamIndex: route.teamIndex },
1775
+ ...route.kind === "observer" ? { observer: true, role: "observer" } : {}
1776
+ };
1777
+ if (route.kind !== "player" || route.teamIndex === void 0) {
1778
+ return { kind: "viewer", viewer: base };
1779
+ }
1780
+ const team = state.teams.find((candidate) => candidate.index === route.teamIndex);
1781
+ if (!team) return { kind: "no-such-team", teamIndex: route.teamIndex };
1782
+ const slot = route.participant ?? 1;
1783
+ const participant = team.participants[slot - 1];
1784
+ if (!participant) {
1785
+ return {
1786
+ kind: "no-such-participant",
1787
+ teamIndex: route.teamIndex,
1788
+ slot,
1789
+ held: team.participants.length
1790
+ };
1791
+ }
1792
+ return {
1793
+ kind: "viewer",
1794
+ viewer: { ...base, participantId: participant.id, role: "participant" }
1795
+ };
1796
+ }
1797
+
1798
+ // cli/dev/view/view.ts
1799
+ var SURFACE_FOR = {
1800
+ console: "session",
1801
+ player: "game",
1802
+ observer: "game",
1803
+ "waiting-room": "waiting-room",
1804
+ setup: "setup",
1805
+ "scenario-editor": "scenario-editor",
1806
+ presentation: "presentation"
1807
+ };
1808
+ var VIEW_ROUTES = /* @__PURE__ */ new Set([
1809
+ "console",
1810
+ "player",
1811
+ "observer",
1812
+ "waiting-room",
1813
+ "join",
1814
+ "setup"
1815
+ ]);
1816
+ function isViewRoute(route) {
1817
+ return route.bare && VIEW_ROUTES.has(route.kind);
1818
+ }
1819
+ function resolveView(state, route, surfaces) {
1820
+ const configurable = surfaces.some((surface2) => surface2.kind === "setup");
1821
+ const inSetup = state.session.inSetup;
1822
+ const facilitator = route.kind === "console" || route.kind === "setup";
1823
+ if (inSetup && !facilitator) return { status: "configuring" };
1824
+ const effective = inSetup ? { ...route, kind: "setup" } : route;
1825
+ if (!inSetup && effective.kind === "setup") {
1826
+ return { status: "closed", configurable };
1827
+ }
1828
+ if (effective.kind === "join") {
1829
+ const team = state.teams.find((candidate) => candidate.index === effective.teamIndex);
1830
+ if (!team) return { status: "join", team: null };
1831
+ if (team.participants.length === 1) {
1832
+ return {
1833
+ status: "redirect",
1834
+ href: routeHref({
1835
+ kind: "player",
1836
+ teamIndex: team.index,
1837
+ participant: 1,
1838
+ bare: true,
1839
+ run: effective.run
1840
+ })
1841
+ };
1842
+ }
1843
+ return {
1844
+ status: "join",
1845
+ team: {
1846
+ index: team.index,
1847
+ name: team.name,
1848
+ participants: team.participants.map(({ id, name }) => ({ id, name }))
1849
+ }
1850
+ };
1851
+ }
1852
+ const resolution = resolveViewer(state, effective);
1853
+ if (resolution.kind === "no-such-team") {
1854
+ return { status: "no-such-team", teamIndex: resolution.teamIndex };
1855
+ }
1856
+ if (resolution.kind === "no-such-participant") {
1857
+ return {
1858
+ status: "no-such-participant",
1859
+ teamIndex: resolution.teamIndex,
1860
+ slot: resolution.slot,
1861
+ held: resolution.held
1862
+ };
1863
+ }
1864
+ const held = state.session.waitingRoomOpen && (effective.kind === "player" || effective.kind === "waiting-room");
1865
+ const kind = held ? "waiting-room" : SURFACE_FOR[effective.kind] ?? "session";
1866
+ const surface = surfaces.find((candidate) => candidate.kind === kind);
1867
+ if (!surface) return { status: "missing-surface", kind };
1868
+ return {
1869
+ status: "surface",
1870
+ surface,
1871
+ viewer: resolution.viewer,
1872
+ inSetup,
1873
+ sessionKey: sessionKeyFor(state, surface)
1874
+ };
1875
+ }
1876
+ function viewMessages(page, state, options) {
1877
+ if (page.status !== "surface") return [];
1878
+ return buildBatch({
1879
+ surface: page.surface,
1880
+ state,
1881
+ viewer: page.viewer,
1882
+ origin: options.origin,
1883
+ assetOrigin: options.assetOrigin,
1884
+ gameName: options.gameName,
1885
+ overlays: options.overlays,
1886
+ roundProcessing: options.roundProcessing
1887
+ });
1888
+ }
1889
+
1890
+ // cli/dev/shell.ts
1891
+ var LOOPBACK = "127.0.0.1";
1892
+ var REINITIALISING_CAUSES = /* @__PURE__ */ new Set([
1893
+ "reinitialise",
1894
+ "reconfigure",
1895
+ "reset",
1896
+ "selectScenario",
1897
+ REINITIALISED_ON_CHANGE
1898
+ ]);
1899
+ var CONSOLE_ROUTE = /^\/(?:$|team\/\d+(?:\/(?:player(?:\/\d+)?|observe|join|waiting-room))?\/?$|walkthrough\/?$|setup\/?$|scenario-editor\/?$|guide\/?$|print\/?$|presentation\/?$)/;
1900
+ var DELEGATED_FEATURES = [
1901
+ "clipboard-write",
1902
+ "autoplay",
1903
+ "screen-wake-lock",
1904
+ "fullscreen",
1905
+ "microphone",
1906
+ "camera",
1907
+ "geolocation",
1908
+ "picture-in-picture",
1909
+ "web-share",
1910
+ "gamepad",
1911
+ "window-management",
1912
+ "speaker-selection"
1913
+ ];
1914
+ function delegatedFeatures(assetOrigin) {
1915
+ return DELEGATED_FEATURES.map((feature) => `${feature}=(self "${assetOrigin}")`).join(", ");
1916
+ }
1917
+ var BUNDLE_ROUTE = /^\/(?:user-interfaces|setup-user-interfaces|scenario-editor-user-interfaces|session-user-interfaces|waiting-room-user-interfaces|presentation-user-interfaces)(?:\/|$)/;
1918
+ var DevShell = class {
1919
+ app = express2();
1920
+ /** The asset origin: bundles, and the files a frame reads (§16.4). */
1921
+ assetApp = express2();
1922
+ session;
1923
+ /**
1924
+ * The walkthrough run (§5.7), built the first time somebody opens one.
1925
+ *
1926
+ * Lazy because a second `Session` builds a second `GameExecutor`, which
1927
+ * loads the package again: a dev server nobody points at a walkthrough
1928
+ * should not pay for one. The URL is always there regardless, which is what
1929
+ * `/walkthrough` being addressable means.
1930
+ */
1931
+ walkthrough = null;
1932
+ /** Serialises concurrent first opens so they share one run, not two. */
1933
+ walkthroughStarting = null;
1934
+ /** The walkthrough's surface storage key, kept across a reset (§12.2). */
1935
+ walkthroughKey = null;
1936
+ /** Which run each socket is watching, so an event reaches only its own. */
1937
+ socketRuns = /* @__PURE__ */ new WeakMap();
1938
+ /** The participant an operator page says it is showing, where it shows one. */
1939
+ socketPresence = /* @__PURE__ */ new Map();
1940
+ options;
1941
+ brands;
1942
+ server = null;
1943
+ assetServer = null;
1944
+ sockets = null;
1945
+ /** One socket per viewer page, each carrying only what that page is owed. */
1946
+ viewSockets = null;
1947
+ views = /* @__PURE__ */ new Map();
1948
+ /** Teams processing a round, per run (§12.4.4); `-1` is the cohort. */
1949
+ processing = /* @__PURE__ */ new Map();
1950
+ vite = null;
1951
+ watcher = null;
1952
+ /** Why surfaces cannot be served, when Vite could not start. */
1953
+ viteFailure = null;
1954
+ /** Serialises the first requests for a surface so they share one Vite. */
1955
+ viteStarting = null;
1956
+ /** The hot-reload socket's own listener, when a public origin moves its client. */
1957
+ hmrServer = null;
1958
+ port;
1959
+ vitePort;
1960
+ assetPort;
1961
+ /** Written into the lock and answered by `/api/session`, so a reused port is not taken for this server. */
1962
+ instanceId = newInstanceId();
1963
+ /** Why the last edit could not be loaded, until an edit loads. */
1964
+ reloadFailure = null;
1965
+ /** Capabilities adopted live with their schema defaults, until Init next runs. */
1966
+ seeded = /* @__PURE__ */ new Set();
1967
+ /** The errors `sdk build` would refuse the package for, as it last stood on disk. */
1968
+ buildErrors = [];
1969
+ /** Which validation is the latest, so an older one finishing late is dropped. */
1970
+ validations = 0;
1971
+ /** Where an isolated server keeps blobs, and how to stop doing so. */
1972
+ isolatedBlobs = null;
1973
+ constructor(options) {
1974
+ this.options = options.isolated ? { ...options, anonymous: true, inMemory: true } : options;
1975
+ this.port = options.port ?? 3e3;
1976
+ this.vitePort = options.vitePort ?? this.port + 1;
1977
+ this.assetPort = options.assetPort ?? this.vitePort + 1;
1978
+ this.session = new Session(this.options);
1979
+ this.brands = loadBrands(this.options.brandFiles);
1980
+ }
1981
+ /**
1982
+ * The brands, read again so an edit to a brand file shows on the next
1983
+ * page load. One that has broken since keeps its last good reading, with
1984
+ * the reason logged: the server is already up, and a typo mid-edit is not
1985
+ * worth taking the page down for.
1986
+ */
1987
+ currentBrands() {
1988
+ try {
1989
+ this.brands = loadBrands(this.options.brandFiles);
1990
+ } catch (error) {
1991
+ console.warn(`Keeping the last good brands: ${errorMessage(error)}`);
1992
+ }
1993
+ return this.brands;
1994
+ }
1995
+ async start() {
1996
+ const built = this.options.builtSurfaces;
1997
+ if (built !== void 0 && !statSync(built, { throwIfNoEntry: false })?.isDirectory()) {
1998
+ throw new Error(`No built surfaces at ${built}: build them first`);
1999
+ }
2000
+ if (this.options.isolated) {
2001
+ const dir = await mkdtemp2(join5(tmpdir2(), "seriousgaming-dev-blobs-"));
2002
+ this.isolatedBlobs = { dir, restore: redirectBlobs(this.options.packagePath, dir) };
2003
+ }
2004
+ try {
2005
+ await this.listen();
2006
+ } catch (error) {
2007
+ await this.releaseIsolatedBlobs();
2008
+ throw error;
2009
+ }
2010
+ }
2011
+ async releaseIsolatedBlobs() {
2012
+ if (!this.isolatedBlobs) return;
2013
+ this.isolatedBlobs.restore();
2014
+ await rm2(this.isolatedBlobs.dir, { recursive: true, force: true });
2015
+ this.isolatedBlobs = null;
2016
+ }
2017
+ async listen() {
2018
+ await this.session.start();
2019
+ await this.validate();
2020
+ this.configure();
2021
+ this.configureAssets();
2022
+ this.server = createServer(this.app);
2023
+ this.attachSockets(this.server);
2024
+ this.port = await listenWithPortFallback(this.server, this.port, {
2025
+ ...this.bindHost,
2026
+ onPortInUse: (taken) => console.warn(`Port ${taken} is in use; trying the next one`)
2027
+ });
2028
+ this.vitePort = await findFreePort(this.options.vitePort ?? this.port + 1);
2029
+ this.assetServer = createServer(this.assetApp);
2030
+ this.assetPort = await listenWithPortFallback(
2031
+ this.assetServer,
2032
+ await findFreePort(this.options.assetPort ?? this.vitePort + 1),
2033
+ {
2034
+ ...this.bindHost,
2035
+ onPortInUse: (taken) => console.warn(`Asset port ${taken} is in use; trying the next one`)
2036
+ }
2037
+ );
2038
+ this.watcher = await watchPackage(
2039
+ this.options.packagePath,
2040
+ (change) => this.onPackageChange(change)
2041
+ );
2042
+ if (!this.options.anonymous) {
2043
+ await writeLockFile(this.options.packagePath, {
2044
+ port: this.port,
2045
+ instanceId: this.instanceId,
2046
+ background: this.options.background ?? false
2047
+ });
2048
+ }
2049
+ }
2050
+ async stop() {
2051
+ await this.watcher?.close();
2052
+ this.watcher = null;
2053
+ this.sockets?.clients.forEach((client) => client.close());
2054
+ this.sockets?.close();
2055
+ this.viewSockets?.clients.forEach((client) => client.close());
2056
+ this.viewSockets?.close();
2057
+ await this.viteStarting;
2058
+ await this.vite?.close();
2059
+ await Promise.all(
2060
+ [this.server, this.assetServer, this.hmrServer].map(
2061
+ (server) => new Promise((resolve3) => {
2062
+ if (!server) return resolve3();
2063
+ server.close(() => resolve3());
2064
+ })
2065
+ )
2066
+ );
2067
+ await this.session.stop();
2068
+ if (!this.options.anonymous) {
2069
+ await removeLockFile(this.options.packagePath, this.instanceId);
2070
+ }
2071
+ await this.releaseIsolatedBlobs();
2072
+ }
2073
+ /**
2074
+ * Pick up an edit. The manifest is one more file the package is resolved
2075
+ * from, so it reloads as a bundle does: what a running session can adopt
2076
+ * it adopts, and the rest waits for a re-initialisation (#640).
2077
+ */
2078
+ onPackageChange(change) {
2079
+ void this.validate().then(() => {
2080
+ if (this.watcher) this.applyChange(change);
2081
+ });
2082
+ }
2083
+ applyChange(change) {
2084
+ if (change === "logic") {
2085
+ for (const run of [this.session, this.walkthrough]) void run?.reloadLogic();
2086
+ logger.success("Logic changed; the next run uses it.");
2087
+ return;
2088
+ }
2089
+ void this.walkthrough?.reloadBundles();
2090
+ void this.session.reloadBundles().then((outcome) => {
2091
+ this.record(outcome);
2092
+ reportReload(outcome);
2093
+ });
2094
+ }
2095
+ /**
2096
+ * Run the static validation `sdk build --validate-only` runs, and say so
2097
+ * when its errors change.
2098
+ *
2099
+ * A package `build` refuses still runs here: the session checks at run
2100
+ * time what it cannot run correctly, and refusing play over the rest, an
2101
+ * unresolved read or a missing entrypoint, would stop an author part way
2102
+ * through an edit that spans several files. What it must not do is run
2103
+ * silently, so the errors are printed, kept as notices every CLI command
2104
+ * repeats, and shown on the console.
2105
+ */
2106
+ async validate() {
2107
+ const run = ++this.validations;
2108
+ let errors;
2109
+ try {
2110
+ const output = await validatePackage({
2111
+ config: "seriousgaming.sdk.json",
2112
+ workingDir: this.options.packagePath
2113
+ });
2114
+ errors = output.resources.flatMap((resource) => resource.diagnostics).filter((diagnostic) => diagnostic.severity === "error");
2115
+ } catch {
2116
+ return;
2117
+ }
2118
+ if (run !== this.validations) return;
2119
+ const changed = JSON.stringify(errors) !== JSON.stringify(this.buildErrors);
2120
+ const hadErrors = this.buildErrors.length > 0;
2121
+ this.buildErrors = errors;
2122
+ if (!changed) return;
2123
+ if (errors.length > 0) {
2124
+ logger.error(
2125
+ `\`sdk build\` would refuse this package: ${errors.length === 1 ? "one error" : `${errors.length} errors`}. The dev server runs it anyway, so it can be fixed while you watch.`
2126
+ );
2127
+ for (const error of errors) logger.error(` ${buildErrorLine(error)}`);
2128
+ } else if (hadErrors) {
2129
+ logger.success("The package passes `sdk build` validation again.");
2130
+ }
2131
+ }
2132
+ /** Keep what a reload could not apply, for the next command to be told. */
2133
+ record(outcome) {
2134
+ if (outcome.kind !== "failed") this.reloadFailure = null;
2135
+ if (outcome.kind === "reinitialised") this.seeded.clear();
2136
+ else for (const capability of outcome.added) this.seeded.add(capability);
2137
+ }
2138
+ /**
2139
+ * Everything this server could not apply live to `run`, as it stands now:
2140
+ * edits waiting for a re-initialisation, an edit that did not load, and
2141
+ * capabilities Init has not run for. Pending edits are the run's own; the
2142
+ * other two are about the package, so only the session reports them.
2143
+ */
2144
+ notices(run = this.session) {
2145
+ const notices = [];
2146
+ const pending = run.pendingChanges();
2147
+ if (hasPendingChanges(pending)) {
2148
+ notices.push({
2149
+ code: "SETTINGS_STALE",
2150
+ message: `${pendingHeadline(pending)}. ${describePendingChanges(pending)}`
2151
+ });
2152
+ }
2153
+ if (run !== this.session) return notices;
2154
+ if (this.reloadFailure !== null) {
2155
+ notices.push({ code: "RELOAD_FAILED", message: this.reloadFailure });
2156
+ }
2157
+ for (const capability of this.seeded) {
2158
+ notices.push({ code: "CAPABILITY_SEEDED", message: seededMessage(capability) });
2159
+ }
2160
+ for (const error of this.buildErrors) {
2161
+ notices.push({ code: error.code, message: buildErrorLine(error), build: true });
2162
+ }
2163
+ return notices;
2164
+ }
2165
+ /** Every interface with `lan`, loopback otherwise, as listen options. */
2166
+ get bindHost() {
2167
+ return this.options.lan ? {} : { host: LOOPBACK };
2168
+ }
2169
+ /** Whether other machines on the network can reach this server. */
2170
+ get reachableFromNetwork() {
2171
+ return this.options.lan === true;
2172
+ }
2173
+ /** Where the console is, once listening. */
2174
+ get url() {
2175
+ return `http://localhost:${this.port}`;
2176
+ }
2177
+ /** Where bundles are served from, once listening. */
2178
+ get assetUrl() {
2179
+ return `http://localhost:${this.assetPort}`;
2180
+ }
2181
+ /** Where people reach the console, when a proxy stands in front of it. */
2182
+ get publicUrl() {
2183
+ return this.options.publicUrl ?? null;
2184
+ }
2185
+ /** Where people's browsers load bundles from, when a proxy stands in front. */
2186
+ get publicAssetUrl() {
2187
+ return publicAssetOrigin(this.options, this.assetPort);
2188
+ }
2189
+ /**
2190
+ * The asset origin as a client that reached `host` must name it: the
2191
+ * public one where given, else the same host on the asset port. A browser
2192
+ * on another machine reached us by an address `localhost` would not
2193
+ * resolve to on its side.
2194
+ */
2195
+ assetOrigin(host) {
2196
+ const configured = this.publicAssetUrl;
2197
+ if (configured) return configured;
2198
+ const name = (host ?? "localhost").replace(/:\d+$/, "") || "localhost";
2199
+ return `http://${name}:${this.assetPort}`;
2200
+ }
2201
+ /** The console's own origin, as a client that reached `host` names it. */
2202
+ consoleOrigin(host) {
2203
+ return this.options.publicUrl ?? (host ? `http://${host}` : this.url);
2204
+ }
2205
+ /** Where a frame's hot-reload client connects, when a public origin decides it. */
2206
+ get publicHmrUrl() {
2207
+ return publicHmrOrigin(this.options, this.assetPort, this.vitePort);
2208
+ }
2209
+ /** What the bundle policy's `connect-src` admits for hot reload. */
2210
+ hmrSources(host) {
2211
+ return this.publicHmrUrl ?? hmrConnectSources(host, this.vitePort);
2212
+ }
2213
+ /** The session this shell wraps, for tests and for the CLI in-process path. */
2214
+ get runtime() {
2215
+ return this.session;
2216
+ }
2217
+ // -----------------------------------------------------------------------
2218
+ // HTTP
2219
+ // -----------------------------------------------------------------------
2220
+ /**
2221
+ * The walkthrough run, started on first use.
2222
+ *
2223
+ * One team and tick 0 are the walkthrough's shape (§5.7), not a default the
2224
+ * caller may vary, so they are fixed here rather than taken from options.
2225
+ */
2226
+ async walkthroughRun() {
2227
+ if (this.walkthrough) return this.walkthrough;
2228
+ this.walkthroughStarting ??= (async () => {
2229
+ const run = new Session({
2230
+ ...this.options,
2231
+ teams: 1,
2232
+ runKind: "walkthrough",
2233
+ // §12.2: the walkthrough's own key, never the session's, and
2234
+ // the same one across a reset, which a viewer sees as the same
2235
+ // run starting again.
2236
+ ...this.walkthroughKey === null ? {} : { sessionKey: this.walkthroughKey },
2237
+ locale: this.session.project().session.locale,
2238
+ scenarioId: this.session.project().game.scenarioId
2239
+ });
2240
+ await run.start();
2241
+ if (run.inSetup) {
2242
+ await run.submit({
2243
+ type: "updateSettings",
2244
+ payload: this.session.sessionOverrides()
2245
+ });
2246
+ await run.submit({ type: "play" });
2247
+ }
2248
+ this.walkthroughKey = run.project().session.sessionKey;
2249
+ run.subscribe((event) => {
2250
+ this.broadcast(event, "walkthrough");
2251
+ this.updateViews(event, "walkthrough");
2252
+ this.report(event);
2253
+ if (event.type === "state") this.syncPresence("walkthrough");
2254
+ });
2255
+ this.walkthrough = run;
2256
+ return run;
2257
+ })();
2258
+ try {
2259
+ return await this.walkthroughStarting;
2260
+ } finally {
2261
+ this.walkthroughStarting = null;
2262
+ }
2263
+ }
2264
+ /**
2265
+ * A command that rebuilds the walkthrough, as a settled mutation.
2266
+ *
2267
+ * The host owns it rather than a session, because it replaces the run a
2268
+ * session command would have been addressed to. A `resetWalkthrough` with
2269
+ * no walkthrough yet is denied rather than creating one (§12.5): opening
2270
+ * the link is what creates the run, and a reset has nothing to rewind.
2271
+ */
2272
+ async settleWalkthroughReset(command) {
2273
+ if (command.type === "resetWalkthrough" && !this.walkthrough && !this.walkthroughStarting) {
2274
+ return {
2275
+ ok: false,
2276
+ outcome: { kind: "denied", message: "There is no walkthrough to reset yet" }
2277
+ };
2278
+ }
2279
+ await this.resetWalkthrough();
2280
+ return { ok: true };
2281
+ }
2282
+ /** The run a request or socket named, started if it is the walkthrough. */
2283
+ runFor(run) {
2284
+ return run === "walkthrough" ? this.walkthroughRun() : Promise.resolve(this.session);
2285
+ }
2286
+ /**
2287
+ * Throw the walkthrough away and start a fresh one.
2288
+ *
2289
+ * A walkthrough always begins at tick 0 (§5.7), so replacing the run *is*
2290
+ * the reset: there is no earlier state to rewind to and nothing to unpick.
2291
+ */
2292
+ async resetWalkthrough() {
2293
+ const previous = this.walkthrough;
2294
+ this.walkthrough = null;
2295
+ await previous?.stop();
2296
+ const run = await this.walkthroughRun();
2297
+ const event = { type: "state", state: run.project(), cause: "reset" };
2298
+ this.broadcast(event, "walkthrough");
2299
+ this.updateViews(event, "walkthrough");
2300
+ return run;
2301
+ }
2302
+ configure() {
2303
+ registerRoutes(this.app, {
2304
+ session: this.session,
2305
+ runFor: (run) => this.runFor(run),
2306
+ resetWalkthrough: () => this.resetWalkthrough(),
2307
+ settleWalkthroughReset: (command) => this.settleWalkthroughReset(command),
2308
+ packagePath: this.options.packagePath,
2309
+ vitePort: () => this.vitePort,
2310
+ assetOrigin: (host) => this.assetOrigin(host),
2311
+ instanceId: this.instanceId,
2312
+ notices: (run) => this.notices(run),
2313
+ brands: () => this.currentBrands()
2314
+ });
2315
+ const filename = fileURLToPath2(import.meta.url);
2316
+ const console_ = resolveConsolePath(dirname2(filename), filename);
2317
+ if (!console_.built) {
2318
+ console.warn(`
2319
+ ${MISSING_CONSOLE_MESSAGE}
2320
+ `);
2321
+ }
2322
+ this.app.use((req, res, next) => {
2323
+ if (!CONSOLE_ROUTE.test(req.path)) return next();
2324
+ if (!console_.built) {
2325
+ res.status(503).type("text/plain").send(MISSING_CONSOLE_MESSAGE);
2326
+ return;
2327
+ }
2328
+ res.setHeader(
2329
+ "Permissions-Policy",
2330
+ delegatedFeatures(this.assetOrigin(req.headers.host))
2331
+ );
2332
+ res.sendFile("index.html", { root: console_.path });
2333
+ });
2334
+ this.app.use(express2.static(console_.path));
2335
+ }
2336
+ /**
2337
+ * The asset origin: game bundles, through Vite, and the files a frame
2338
+ * reads, all under the bundle policy and nothing under `/api`.
2339
+ */
2340
+ configureAssets() {
2341
+ this.assetApp.use((req, res, next) => {
2342
+ applyBundlePolicy(res, this.hmrSources(req.headers.host));
2343
+ next();
2344
+ });
2345
+ registerAssetRoutes(
2346
+ this.assetApp,
2347
+ { session: this.session, packagePath: this.options.packagePath },
2348
+ "/assets"
2349
+ );
2350
+ registerBrandRoutes(this.assetApp, () => this.brands);
2351
+ if (this.options.builtSurfaces !== void 0) {
2352
+ this.serveBuiltSurfaces(this.options.builtSurfaces);
2353
+ return;
2354
+ }
2355
+ this.assetApp.use(async (req, res, next) => {
2356
+ const vite = await this.ensureVite();
2357
+ if (vite) {
2358
+ vite.middlewares(req, res, next);
2359
+ return;
2360
+ }
2361
+ if (this.viteFailure && BUNDLE_ROUTE.test(req.path)) {
2362
+ res.status(503).type("text/plain").send(
2363
+ `Game surfaces cannot be served: ${this.viteFailure}
2364
+ Install the package's dependencies and restart.`
2365
+ );
2366
+ return;
2367
+ }
2368
+ next();
2369
+ });
2370
+ this.assetApp.use((req, res) => {
2371
+ res.status(404).type("text/plain").send(`Not found: ${req.path}`);
2372
+ });
2373
+ }
2374
+ /**
2375
+ * Each surface from its built directory, which `sdk build` gives relative
2376
+ * asset paths, so the document and everything it loads resolve under the
2377
+ * route the console already mounts it at.
2378
+ */
2379
+ serveBuiltSurfaces(directory) {
2380
+ for (const kind of Object.keys(SURFACE_PREFIX)) {
2381
+ const slot = SURFACE_SLOT[kind];
2382
+ this.assetApp.use(
2383
+ `${SURFACE_PREFIX[kind]}/${slot}`,
2384
+ express2.static(join5(directory, slot), { index: false })
2385
+ );
2386
+ }
2387
+ this.assetApp.use((req, res) => {
2388
+ const missing = BUNDLE_ROUTE.test(req.path) ? `${req.path} is not in the built surfaces at ${directory}. Build them again after adding a surface.` : `Not found: ${req.path}`;
2389
+ res.status(404).type("text/plain").send(missing);
2390
+ });
2391
+ }
2392
+ /**
2393
+ * Vite, started the first time something asks for a surface (#320).
2394
+ *
2395
+ * Not at start-up: a session a CLI command started in the background, and
2396
+ * most of the servers the test suites start, never serve a surface, and a
2397
+ * Vite server each was both the start-up cost and most of the exposure to
2398
+ * rolldown's native crash.
2399
+ */
2400
+ ensureVite() {
2401
+ if (this.vite) return Promise.resolve(this.vite);
2402
+ if (this.viteFailure) return Promise.resolve(null);
2403
+ this.viteStarting ??= this.createVite().then(
2404
+ (vite) => {
2405
+ this.vite = vite;
2406
+ return vite;
2407
+ },
2408
+ (error) => {
2409
+ this.viteFailure = errorMessage(error, "Vite could not start");
2410
+ console.warn(
2411
+ `
2412
+ Game surfaces cannot be served: ${this.viteFailure}
2413
+ The session is running, so the CLI and the state API work as usual.
2414
+ Install the package's dependencies to serve its surfaces.
2415
+ `
2416
+ );
2417
+ return null;
2418
+ }
2419
+ );
2420
+ return this.viteStarting;
2421
+ }
2422
+ async createVite() {
2423
+ const server = await this.viteServerOptions();
2424
+ return createViteServer({
2425
+ root: this.options.packagePath,
2426
+ appType: "custom",
2427
+ plugins: [
2428
+ react(),
2429
+ seriousgamingUiPlugin({
2430
+ // Read on each request rather than once, so a surface
2431
+ // added while the server runs is served without a restart.
2432
+ surfaces: () => {
2433
+ const config = this.session.packageConfiguration();
2434
+ return {
2435
+ userInterfaces: config?.ui ? [config.ui] : [],
2436
+ setups: config?.setup ? [config.setup] : [],
2437
+ scenarioEditors: config?.scenario_editor ? [config.scenario_editor] : [],
2438
+ sessionUserInterfaces: config?.session ? [config.session] : [],
2439
+ waitingRoomUserInterfaces: config?.waiting_room ? [config.waiting_room] : [],
2440
+ presentations: config?.presentation ? [config.presentation] : []
2441
+ };
2442
+ },
2443
+ workingDir: this.options.packagePath
2444
+ })
2445
+ ],
2446
+ server,
2447
+ logLevel: "error"
2448
+ });
2449
+ }
2450
+ /**
2451
+ * Vite's server options: its own hot-reload socket on the Vite port, as
2452
+ * before, unless a public origin says where the client connects.
2453
+ *
2454
+ * Vite takes one `host` for both where its socket listens and where its
2455
+ * client connects, and a public hostname is no address to listen on. So
2456
+ * behind a proxy the socket's listener is opened here, on the Vite port
2457
+ * as usual, and Vite only attaches to it.
2458
+ */
2459
+ async viteServerOptions() {
2460
+ const hmr = this.publicHmrUrl;
2461
+ const overlay = this.options.errorOverlay === false ? { overlay: false } : {};
2462
+ if (!hmr) {
2463
+ return {
2464
+ middlewareMode: true,
2465
+ hmr: { port: this.vitePort, ...this.bindHost, ...overlay }
2466
+ };
2467
+ }
2468
+ const listener = createServer((_req, res) => {
2469
+ res.writeHead(426, { "Content-Type": "text/plain" }).end("Upgrade Required");
2470
+ });
2471
+ await new Promise((resolve3, reject) => {
2472
+ listener.once("error", reject);
2473
+ listener.listen(this.vitePort, this.bindHost.host, () => {
2474
+ listener.off("error", reject);
2475
+ resolve3();
2476
+ });
2477
+ });
2478
+ this.hmrServer = listener;
2479
+ return {
2480
+ middlewareMode: true,
2481
+ ...this.options.errorOverlay === false ? { hmr: overlay } : {},
2482
+ ws: { server: listener, ...hmrClientTarget(hmr) },
2483
+ // Vite refuses a request whose `Host` it does not recognise, and a
2484
+ // proxy that passes its own on would otherwise be refused it.
2485
+ allowedHosts: publicHostnames([this.options.publicUrl, this.publicAssetUrl, hmr])
2486
+ };
2487
+ }
2488
+ // -----------------------------------------------------------------------
2489
+ // WebSocket
2490
+ // -----------------------------------------------------------------------
2491
+ attachSockets(server) {
2492
+ this.sockets = new WebSocketServer({ noServer: true });
2493
+ this.viewSockets = new WebSocketServer({ noServer: true });
2494
+ server.on("upgrade", (request, socket, head) => {
2495
+ const path = (request.url ?? "").split("?")[0];
2496
+ const target = path === "/ws" ? this.sockets : path === "/ws/view" ? this.viewSockets : null;
2497
+ if (!target) {
2498
+ socket.destroy();
2499
+ return;
2500
+ }
2501
+ target.handleUpgrade(
2502
+ request,
2503
+ socket,
2504
+ head,
2505
+ (client) => target.emit("connection", client, request)
2506
+ );
2507
+ });
2508
+ this.session.subscribe((event) => {
2509
+ this.broadcast(event, "session");
2510
+ this.updateViews(event, "session");
2511
+ this.report(event);
2512
+ if (event.type === "error" && event.source === "reload") {
2513
+ this.reloadFailure = event.message;
2514
+ }
2515
+ if (event.type === "state") {
2516
+ if (REINITIALISING_CAUSES.has(event.cause)) {
2517
+ this.seeded.clear();
2518
+ this.reloadFailure = null;
2519
+ }
2520
+ this.syncPresence("session");
2521
+ }
2522
+ });
2523
+ this.viewSockets.on("connection", (socket, request) => {
2524
+ const params = new URLSearchParams(request.url?.split("?")[1] ?? "");
2525
+ const location = new URL(params.get("page") ?? "/", "http://view.invalid");
2526
+ const route = parseRoute(location.pathname, location.search);
2527
+ if (!isViewRoute(route)) {
2528
+ socket.close(4e3, "Not a viewer page");
2529
+ return;
2530
+ }
2531
+ this.views.set(socket, { route, host: request.headers.host });
2532
+ void this.sendView(socket).then(() => this.syncPresence(route.run));
2533
+ socket.on("message", (raw) => void this.receiveView(socket, raw));
2534
+ socket.on("close", () => {
2535
+ this.views.delete(socket);
2536
+ this.syncPresence(route.run);
2537
+ });
2538
+ });
2539
+ this.sockets.on("connection", (socket, request) => {
2540
+ const run = runFromUrl(request.url);
2541
+ this.socketRuns.set(socket, run);
2542
+ void this.runFor(run).then((session) => {
2543
+ send(socket, { type: "state", state: session.project(), cause: "connected" });
2544
+ });
2545
+ socket.on("message", (raw) => void this.receive(socket, raw));
2546
+ socket.on("close", () => {
2547
+ if (this.socketPresence.delete(socket)) this.syncPresence(run);
2548
+ });
2549
+ });
2550
+ }
2551
+ async receive(socket, raw) {
2552
+ let envelope;
2553
+ try {
2554
+ envelope = JSON.parse(raw.toString());
2555
+ } catch {
2556
+ return;
2557
+ }
2558
+ if ("presence" in envelope) {
2559
+ if (typeof envelope.presence === "string") {
2560
+ this.socketPresence.set(socket, envelope.presence);
2561
+ } else {
2562
+ this.socketPresence.delete(socket);
2563
+ }
2564
+ this.syncPresence(this.socketRuns.get(socket) ?? "session");
2565
+ return;
2566
+ }
2567
+ const { requestId, command } = envelope;
2568
+ if (!command?.type) return;
2569
+ try {
2570
+ const run = this.socketRuns.get(socket) ?? "session";
2571
+ const result = rebuildsWalkthrough(command, run) ? await this.settleWalkthroughReset(command) : isQuery(command) ? await (await this.runFor(run)).query(command) : await (await this.runFor(run)).submit(command);
2572
+ if (requestId) send(socket, { type: "result", requestId, result });
2573
+ } catch (error) {
2574
+ if (requestId) {
2575
+ send(socket, {
2576
+ type: "result",
2577
+ requestId,
2578
+ result: {
2579
+ ok: false,
2580
+ outcome: { kind: "error", message: errorMessage(error, "Command failed") }
2581
+ }
2582
+ });
2583
+ }
2584
+ }
2585
+ }
2586
+ // -----------------------------------------------------------------------
2587
+ // Viewer pages
2588
+ // -----------------------------------------------------------------------
2589
+ /** What one viewer page is owed, now. */
2590
+ viewOf(session, view, state = session.project()) {
2591
+ const origin = this.assetOrigin(view.host);
2592
+ const surfaces = mountableSurfaces(session.packageConfiguration()).map(
2593
+ (surface) => ({ ...surface, origin })
2594
+ );
2595
+ let route = view.route;
2596
+ if (view.participantId !== void 0 && route.kind === "player") {
2597
+ const team = state.teams.find(
2598
+ (candidate) => candidate.participants.some((p) => p.id === view.participantId)
2599
+ );
2600
+ if (team) {
2601
+ route = {
2602
+ ...route,
2603
+ teamIndex: team.index,
2604
+ participant: team.participants.findIndex((p) => p.id === view.participantId) + 1
2605
+ };
2606
+ }
2607
+ }
2608
+ const page = resolveView(state, route, surfaces);
2609
+ if (page.status === "surface" && view.participantId === void 0) {
2610
+ view.participantId = page.viewer.participantId;
2611
+ }
2612
+ const processing = this.processing.get(view.route.run) ?? /* @__PURE__ */ new Set();
2613
+ const roundProcessing = page.status === "surface" && (processing.has(-1) || page.viewer.teamIndex !== void 0 && processing.has(page.viewer.teamIndex));
2614
+ const messages = viewMessages(page, state, {
2615
+ origin: this.consoleOrigin(view.host),
2616
+ assetOrigin: origin,
2617
+ gameName: state.game.name,
2618
+ overlays: availableOverlays({
2619
+ guide: session.effectiveGuide() !== null,
2620
+ presentation: offersPresentationOverlay(session.packageConfiguration())
2621
+ }),
2622
+ roundProcessing
2623
+ });
2624
+ return { page, messages };
2625
+ }
2626
+ /**
2627
+ * Send a viewer its page, unless it is exactly what the page already has.
2628
+ *
2629
+ * Most events change nothing a given page is owed: a write by one team, a
2630
+ * round another team is processing, a tick's start and end on a page that
2631
+ * shows neither. Re-sending the whole batch each time was most of the
2632
+ * traffic, and every byte of it was discarded by the frame.
2633
+ */
2634
+ async sendView(socket, session, state) {
2635
+ const view = this.views.get(socket);
2636
+ if (!view) return;
2637
+ const run = session ?? await this.runFor(view.route.run);
2638
+ const payload = JSON.stringify({ type: "view", ...this.viewOf(run, view, state) });
2639
+ if (payload === view.lastSent || socket.readyState !== 1) return;
2640
+ view.lastSent = payload;
2641
+ socket.send(payload);
2642
+ }
2643
+ /**
2644
+ * Pass a session event on to the viewer pages it concerns, and no further.
2645
+ *
2646
+ * A viewer is never sent an operator error, a refusal meant for another
2647
+ * team, or a round another team is processing (§12.4.4, §15).
2648
+ */
2649
+ /**
2650
+ * Tell a run who has a surface open (§13.2).
2651
+ *
2652
+ * A participant is connected while any page bound to them is: a viewer page
2653
+ * the server resolved to them, or an operator page that said it shows them.
2654
+ * Only a run that exists is told, since asking for the walkthrough is what
2655
+ * builds it.
2656
+ */
2657
+ syncPresence(run) {
2658
+ const session = run === "walkthrough" ? this.walkthrough : this.session;
2659
+ if (!session) return;
2660
+ const state = session.project();
2661
+ const present = /* @__PURE__ */ new Set();
2662
+ for (const view of this.views.values()) {
2663
+ if (view.route.run !== run) continue;
2664
+ const { page } = this.viewOf(session, view, state);
2665
+ if (page.status === "surface" && page.viewer.role === "participant") {
2666
+ if (page.viewer.participantId) present.add(page.viewer.participantId);
2667
+ }
2668
+ }
2669
+ for (const [socket, participantId] of this.socketPresence) {
2670
+ if ((this.socketRuns.get(socket) ?? "session") === run) present.add(participantId);
2671
+ }
2672
+ session.syncPresence(present);
2673
+ }
2674
+ updateViews(event, run) {
2675
+ if (event.type === "round-processing") {
2676
+ const teams = this.processing.get(run) ?? /* @__PURE__ */ new Set();
2677
+ const key = event.teamIndex ?? -1;
2678
+ if (event.processing) teams.add(key);
2679
+ else teams.delete(key);
2680
+ this.processing.set(run, teams);
2681
+ }
2682
+ const viewers = [...this.views].filter(([, view]) => view.route.run === run);
2683
+ if (viewers.length === 0) return;
2684
+ void this.runFor(run).then((session) => {
2685
+ const state = session.project();
2686
+ for (const [socket, view] of viewers) {
2687
+ if (event.type === "state" || event.type === "round-processing") {
2688
+ void this.sendView(socket, session, state);
2689
+ continue;
2690
+ }
2691
+ const { page } = this.viewOf(session, view, state);
2692
+ if (page.status !== "surface") continue;
2693
+ const kind = page.surface.kind;
2694
+ if (event.type === "validation-rejected" && (kind === "game" || kind === "waiting-room") && (event.teamIndex === void 0 || event.teamIndex === page.viewer.teamIndex)) {
2695
+ send(socket, { type: "validation-rejected", rejections: event.rejections });
2696
+ }
2697
+ if (event.type === "error" && event.source.startsWith("hook:") && kind === "session") {
2698
+ send(socket, {
2699
+ type: "hookFailed",
2700
+ payload: {
2701
+ signal: event.source.slice("hook:".length),
2702
+ teamId: event.teamId ?? "",
2703
+ message: event.message
2704
+ }
2705
+ });
2706
+ }
2707
+ }
2708
+ });
2709
+ }
2710
+ /**
2711
+ * Act on a frame's request from a viewer page.
2712
+ *
2713
+ * The page forwards what its frame sent, unmapped, and the host maps it
2714
+ * against its own resolution of who the page is for, so no page can name
2715
+ * somebody else, another surface, or a command its surface may not send.
2716
+ */
2717
+ async receiveView(socket, raw) {
2718
+ let envelope;
2719
+ try {
2720
+ envelope = JSON.parse(raw.toString());
2721
+ } catch {
2722
+ return;
2723
+ }
2724
+ const { requestId, message } = envelope;
2725
+ const view = this.views.get(socket);
2726
+ if (!view || typeof message?.type !== "string") return;
2727
+ const frameMessage = message;
2728
+ let result = null;
2729
+ try {
2730
+ const session = await this.runFor(view.route.run);
2731
+ const { page } = this.viewOf(session, view);
2732
+ if (page.status === "surface") {
2733
+ const command = queryFor(frameMessage, page.surface, page.viewer) ?? commandFor(frameMessage, page.surface, page.viewer);
2734
+ if (isFrameRefusal(command)) {
2735
+ result = { ok: false, outcome: { kind: "denied", message: command.refused } };
2736
+ } else if (command) {
2737
+ result = rebuildsWalkthrough(command, view.route.run) ? await this.settleWalkthroughReset(command) : isQuery(command) ? await session.query(command) : await session.submit(command);
2738
+ }
2739
+ }
2740
+ } catch (error) {
2741
+ result = {
2742
+ ok: false,
2743
+ outcome: { kind: "error", message: errorMessage(error, "Command failed") }
2744
+ };
2745
+ }
2746
+ if (requestId) send(socket, { type: "result", requestId, result });
2747
+ }
2748
+ broadcast(event, run) {
2749
+ let payload = null;
2750
+ this.sockets?.clients.forEach((client) => {
2751
+ if ((this.socketRuns.get(client) ?? "session") !== run) return;
2752
+ if (client.readyState !== 1) return;
2753
+ payload ??= JSON.stringify(event);
2754
+ client.send(payload);
2755
+ });
2756
+ }
2757
+ /**
2758
+ * Say what went wrong where the author is actually looking.
2759
+ *
2760
+ * Session errors used to reach the WebSocket and nothing else, so a refused
2761
+ * tick left the console's drawer badge as the only sign: the clock did not
2762
+ * move, the browser console was clean, and the message naming the cause sat
2763
+ * behind a keystroke nobody had a reason to press. An undeclared write cost
2764
+ * a reported hour of bisection for a one-line fix, and the message that
2765
+ * would have ended it in a minute already existed.
2766
+ */
2767
+ report(event) {
2768
+ if (event.type !== "error") return;
2769
+ logger.error(
2770
+ `${event.source}: ${event.message}${event.teamId ? ` (${event.teamId})` : ""}`
2771
+ );
2772
+ }
2773
+ };
2774
+ function reportReload(outcome) {
2775
+ switch (outcome.kind) {
2776
+ case "failed":
2777
+ return;
2778
+ case "reinitialised":
2779
+ if (hasPendingChanges(outcome.pending)) {
2780
+ logger.success(
2781
+ `${describePendingChanges(outcome.pending)}. Re-initialised the session at tick 0 to apply it.`
2782
+ );
2783
+ }
2784
+ for (const capability of outcome.added) {
2785
+ logger.success(
2786
+ `Capability "${capability}" added. Re-initialised the session at tick 0 so Init runs for it.`
2787
+ );
2788
+ }
2789
+ if (!hasPendingChanges(outcome.pending) && outcome.added.length === 0) {
2790
+ logger.success("Package changed; re-initialised the session at tick 0.");
2791
+ }
2792
+ return;
2793
+ case "pending":
2794
+ logger.warn(
2795
+ `${pendingHeadline(outcome.pending)}. ${describePendingChanges(outcome.pending)}.
2796
+ ` + PENDING_CHANGES_HINT
2797
+ );
2798
+ break;
2799
+ case "live":
2800
+ logger.success("Package changed; the session uses it from here.");
2801
+ break;
2802
+ }
2803
+ for (const capability of outcome.added) logger.warn(seededMessage(capability));
2804
+ }
2805
+ function buildErrorLine(error) {
2806
+ const at = diagnosticLocation(error);
2807
+ return `Build error ${error.code}${at === void 0 ? "" : ` at ${at}`}: ${error.message}`;
2808
+ }
2809
+ function seededMessage(capability) {
2810
+ return `Capability "${capability}" added with its schema defaults; Init has not run for it. Run \`sdk init\` to start from Init`;
2811
+ }
2812
+ function runFromUrl(url) {
2813
+ const query = url?.split("?")[1];
2814
+ return new URLSearchParams(query ?? "").get("run") === "walkthrough" ? "walkthrough" : "session";
2815
+ }
2816
+ function send(socket, message) {
2817
+ if (socket.readyState !== 1) return;
2818
+ socket.send(JSON.stringify(message));
2819
+ }
2820
+ function applyBundlePolicy(res, hmr) {
2821
+ res.setHeader(
2822
+ "Content-Security-Policy",
2823
+ [
2824
+ `default-src 'self'`,
2825
+ `connect-src 'self' ${hmr}`,
2826
+ `img-src 'self' data:`,
2827
+ `media-src 'self' blob: data:`,
2828
+ `font-src 'self' data:`,
2829
+ `style-src 'self' 'unsafe-inline'`,
2830
+ `script-src 'self' 'unsafe-inline'`,
2831
+ `frame-src 'self' https://www.youtube.com https://www.youtube-nocookie.com`,
2832
+ `form-action 'self'`,
2833
+ `frame-ancestors *`
2834
+ ].join("; ")
2835
+ );
2836
+ res.setHeader("X-Content-Type-Options", "nosniff");
2837
+ }
2838
+ function hmrConnectSources(host, vitePort) {
2839
+ const name = (host ?? "localhost").split(":")[0] || "localhost";
2840
+ const names = /* @__PURE__ */ new Set([name, "localhost", "127.0.0.1"]);
2841
+ return [...names].flatMap((entry) => [`ws://${entry}:${vitePort}`, `wss://${entry}:${vitePort}`]).join(" ");
2842
+ }
2843
+
2844
+ export {
2845
+ parseRoute,
2846
+ DevShell
2847
+ };