@seriousgaming/sdk-tools 1.2.0 → 1.4.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 (50) hide show
  1. package/dist/cli.js +3582 -2834
  2. package/dist/client.js +1145 -543
  3. package/dist/core/participant-registry.d.ts +6 -0
  4. package/dist/core/session-host.d.ts +4 -2
  5. package/dist/core/session-roster.d.ts +4 -1
  6. package/dist/core/settings-locks.d.ts +27 -2
  7. package/dist/dev/console/assets/{index-BNLEVOQA.js → index-BvB-LFQZ.js} +47 -47
  8. package/dist/dev/console/index.html +1 -1
  9. package/dist/dev/routes.d.ts +4 -0
  10. package/dist/dev/view/batch.d.ts +24 -10
  11. package/dist/dev/view/view.d.ts +2 -1
  12. package/dist/docs/api/index.md +2 -2
  13. package/dist/docs/api/sdk-commands.md +4 -0
  14. package/dist/docs/api/sdk-e2e.md +4 -0
  15. package/dist/docs/api/sdk-tools-client.md +5 -0
  16. package/dist/docs/api/sdk-ui-testing.md +1 -0
  17. package/dist/docs/api/sdk-ui.md +33 -1
  18. package/dist/docs/api/sdk.md +82 -3
  19. package/dist/docs/changelog.md +41 -0
  20. package/dist/docs/concepts/terminology.md +1 -1
  21. package/dist/docs/guides/capabilities.md +2 -0
  22. package/dist/docs/guides/endpoints.md +2 -2
  23. package/dist/docs/guides/engine-testing.md +1 -1
  24. package/dist/docs/guides/file-handling.md +113 -21
  25. package/dist/docs/guides/llm-integration.md +1 -1
  26. package/dist/docs/guides/presentation.md +23 -9
  27. package/dist/docs/guides/scenario-editor.md +1 -1
  28. package/dist/docs/guides/scenarios.md +9 -1
  29. package/dist/docs/guides/session.md +47 -8
  30. package/dist/docs/guides/settings.md +62 -2
  31. package/dist/docs/guides/testing.md +9 -0
  32. package/dist/docs/guides/ui.md +33 -0
  33. package/dist/docs/guides/upgrading.md +11 -0
  34. package/dist/docs/guides/validators.md +62 -4
  35. package/dist/docs/guides/waiting-room.md +2 -0
  36. package/dist/docs/recipes/upload-and-display-files.md +7 -7
  37. package/dist/docs/recipes/validate-scenarios.md +4 -1
  38. package/dist/execution/endpoint-runner.d.ts +6 -0
  39. package/dist/execution/logic-calls.d.ts +7 -2
  40. package/dist/execution/scenario-gates.d.ts +21 -1
  41. package/dist/guide/settings.d.ts +1 -1
  42. package/dist/host/protocol.d.ts +27 -2
  43. package/dist/host.js +64 -2
  44. package/dist/runtime/manifest-version.d.ts +1 -1
  45. package/dist/runtime.js +9 -2
  46. package/dist/storage/asset-resolver.d.ts +24 -1
  47. package/dist/storage/blob-store.d.ts +7 -0
  48. package/dist/utils/local-refs.d.ts +40 -0
  49. package/dist/utils/schema-members.d.ts +19 -0
  50. package/package.json +3 -3
package/dist/client.js CHANGED
@@ -259,6 +259,7 @@ var COMMAND_FIELDS = {
259
259
  removeTeam: { teamIndex: "number" },
260
260
  renameTeam: { teamId: "string", name: "string" },
261
261
  renameOwnTeam: { name: "string", "participantId?": "string", "teamId?": "string" },
262
+ renameSelf: { name: "string", "participantId?": "string", "teamId?": "string" },
262
263
  addParticipant: { teamId: "string", "name?": "string" },
263
264
  renameParticipant: { participantId: "string", name: "string" },
264
265
  moveParticipant: { participantId: "string", teamId: "string" },
@@ -2700,7 +2701,11 @@ function gameOverrideRefusal(overrides) {
2700
2701
  // cli/runtime/manifest-version.ts
2701
2702
  var SUPPORTED_FEATURES = [
2702
2703
  // A validator's `Scenario` gate (§15.8).
2703
- "scenario-validation"
2704
+ "scenario-validation",
2705
+ // The presentation as a host overlay a session surface may open (§6.4).
2706
+ "presentation-overlay",
2707
+ // File reads in a validator's `Scenario` gate (§15.8).
2708
+ "scenario-files"
2704
2709
  ];
2705
2710
  function unsupportedFeatures(manifest) {
2706
2711
  return (manifest.requires ?? []).filter((feature) => !SUPPORTED_FEATURES.includes(feature));
@@ -3141,8 +3146,11 @@ function createAjv(fileValues = "resolved") {
3141
3146
  const ajv4 = new Ajv({
3142
3147
  allErrors: true,
3143
3148
  // Report all errors, not just the first one
3144
- verbose: true
3149
+ verbose: true,
3145
3150
  // Include schema and data in errors
3151
+ // A game schema may write a keyword beside a `$ref` with no `type` of
3152
+ // its own (§6), which strictTypes would log as a warning on every compile.
3153
+ strictTypes: false
3146
3154
  });
3147
3155
  ajv4.addKeyword({ keyword: "tsType", schemaType: "string" });
3148
3156
  ajv4.addKeyword({
@@ -3250,25 +3258,263 @@ function typesOf(schema2) {
3250
3258
 
3251
3259
  // cli/core/settings-locks.ts
3252
3260
  import { isDeepStrictEqual } from "util";
3253
- function lockedPaths(schema2) {
3261
+
3262
+ // ../sdk/lib/build/callbacks.js
3263
+ var UndeclaredApiUseError = class extends Error {
3264
+ resourceIdentifier;
3265
+ api;
3266
+ constructor(resourceIdentifier, api) {
3267
+ super(`Resource "${resourceIdentifier}" attempted to call callback "${api}" but did not declare it in its bundle's "uses" array. Add "${api}" to the bundle's uses to allow this call.`);
3268
+ this.name = "UndeclaredApiUseError";
3269
+ this.resourceIdentifier = resourceIdentifier;
3270
+ this.api = api;
3271
+ }
3272
+ };
3273
+
3274
+ // ../sdk/lib/build/tick-validation.js
3275
+ var MAX_EFFECTIVE_TICK_INTERVAL_MS = 7 * 24 * 60 * 60 * 1e3;
3276
+
3277
+ // ../sdk/lib/build/setting-path.js
3278
+ var NOT_PLAIN = /[.[\]"\s]/u;
3279
+ function isPlainKey(key) {
3280
+ return key !== "" && !NOT_PLAIN.test(key);
3281
+ }
3282
+ function settingPath(identifier, ...keys) {
3283
+ let path3 = isPlainKey(identifier) ? identifier : `[${JSON.stringify(identifier)}]`;
3284
+ for (const key of keys) {
3285
+ const step = String(key);
3286
+ path3 += isPlainKey(step) ? `.${step}` : `[${JSON.stringify(step)}]`;
3287
+ }
3288
+ return path3;
3289
+ }
3290
+ function parseSettingPath(path3) {
3291
+ const steps = [];
3292
+ let at = 0;
3293
+ while (at < path3.length) {
3294
+ if (path3[at] === "[") {
3295
+ const end2 = closingQuote(path3, at + 1);
3296
+ if (end2 === void 0 || path3[end2 + 1] !== "]")
3297
+ return void 0;
3298
+ let key2;
3299
+ try {
3300
+ key2 = JSON.parse(path3.slice(at + 1, end2 + 1));
3301
+ } catch {
3302
+ return void 0;
3303
+ }
3304
+ if (typeof key2 !== "string")
3305
+ return void 0;
3306
+ steps.push(key2);
3307
+ at = end2 + 2;
3308
+ continue;
3309
+ }
3310
+ if (steps.length > 0) {
3311
+ if (path3[at] !== ".")
3312
+ return void 0;
3313
+ at += 1;
3314
+ }
3315
+ let end = at;
3316
+ while (end < path3.length && path3[end] !== "." && path3[end] !== "[")
3317
+ end += 1;
3318
+ const key = path3.slice(at, end);
3319
+ if (!isPlainKey(key))
3320
+ return void 0;
3321
+ steps.push(key);
3322
+ at = end;
3323
+ }
3324
+ const [identifier, ...keys] = steps;
3325
+ return identifier === void 0 ? void 0 : { identifier, keys };
3326
+ }
3327
+ function closingQuote(path3, start) {
3328
+ if (path3[start] !== '"')
3329
+ return void 0;
3330
+ for (let at = start + 1; at < path3.length; at += 1) {
3331
+ if (path3[at] === "\\")
3332
+ at += 1;
3333
+ else if (path3[at] === '"')
3334
+ return at;
3335
+ }
3336
+ return void 0;
3337
+ }
3338
+
3339
+ // ../sdk/lib/build/validators.js
3340
+ var SCENARIO_GATE_READ_LIMIT_BYTES = 10 * 1024 * 1024;
3341
+ var ScenarioAssetTooLargeError = class _ScenarioAssetTooLargeError extends Error {
3342
+ /** The reference the gate asked to read. */
3343
+ reference;
3344
+ /** The file's size in bytes. */
3345
+ size;
3346
+ /** The cap it exceeds: {@link SCENARIO_GATE_READ_LIMIT_BYTES}. */
3347
+ limit;
3348
+ constructor(reference, size) {
3349
+ super(`Cannot read "${reference}" in a Scenario gate: it is ${size} bytes, over the ${SCENARIO_GATE_READ_LIMIT_BYTES}-byte (10 MB) limit on a gate's reads. Call describeAsset to check that it is there or how large it is.`);
3350
+ this.name = "ScenarioAssetTooLargeError";
3351
+ this.reference = reference;
3352
+ this.size = size;
3353
+ this.limit = SCENARIO_GATE_READ_LIMIT_BYTES;
3354
+ Object.setPrototypeOf(this, _ScenarioAssetTooLargeError.prototype);
3355
+ }
3356
+ };
3357
+
3358
+ // cli/utils/local-refs.ts
3359
+ function isLocalRef(ref) {
3360
+ return ref === "#" || ref.startsWith("#/");
3361
+ }
3362
+ function resolveLocalRef(root2, ref) {
3363
+ if (!isLocalRef(ref)) return void 0;
3364
+ let current = root2;
3365
+ for (const token of ref === "#" ? [] : ref.slice(2).split("/")) {
3366
+ const key = decodeToken(token);
3367
+ if (current === null || typeof current !== "object") return void 0;
3368
+ if (Array.isArray(current)) {
3369
+ if (!/^\d+$/.test(key)) return void 0;
3370
+ current = current[Number(key)];
3371
+ } else {
3372
+ if (!Object.prototype.hasOwnProperty.call(current, key)) return void 0;
3373
+ current = current[key];
3374
+ }
3375
+ }
3376
+ return typeof current === "boolean" || current !== null && typeof current === "object" && !Array.isArray(current) ? current : void 0;
3377
+ }
3378
+ function decodeToken(token) {
3379
+ let decoded = token;
3380
+ try {
3381
+ decoded = decodeURIComponent(token);
3382
+ } catch {
3383
+ }
3384
+ return decoded.replace(/~1/g, "/").replace(/~0/g, "~");
3385
+ }
3386
+ function dereference(root2, schema2) {
3387
+ let current = schema2;
3388
+ const followed = /* @__PURE__ */ new Set();
3389
+ while (typeof current.$ref === "string") {
3390
+ const { $ref: ref, ...beside } = current;
3391
+ const target = followed.has(ref) ? void 0 : resolveLocalRef(root2, ref);
3392
+ followed.add(ref);
3393
+ if (target === void 0 || typeof target !== "object") return beside;
3394
+ current = { ...target, ...beside };
3395
+ }
3396
+ return current;
3397
+ }
3398
+ var SCHEMA_MAPS = ["properties", "patternProperties", "definitions", "$defs"];
3399
+ var SCHEMA_SLOTS = [
3400
+ "additionalProperties",
3401
+ "additionalItems",
3402
+ "contains",
3403
+ "propertyNames",
3404
+ "if",
3405
+ "then",
3406
+ "else",
3407
+ "not"
3408
+ ];
3409
+ var SCHEMA_LISTS = ["allOf", "anyOf", "oneOf"];
3410
+ function childSchemas(schema2) {
3411
+ const found = [];
3412
+ const push2 = (step, child) => {
3413
+ if (child !== null && typeof child === "object" && !Array.isArray(child)) {
3414
+ found.push({ step, schema: child });
3415
+ }
3416
+ };
3417
+ for (const keyword of SCHEMA_MAPS) {
3418
+ const map3 = schema2[keyword];
3419
+ if (!map3 || typeof map3 !== "object") continue;
3420
+ for (const [key, child] of Object.entries(map3))
3421
+ push2(`${keyword}/${encodeToken(key)}`, child);
3422
+ }
3423
+ for (const keyword of SCHEMA_SLOTS) push2(keyword, schema2[keyword]);
3424
+ for (const keyword of SCHEMA_LISTS) {
3425
+ schema2[keyword]?.forEach((child, index3) => push2(`${keyword}/${index3}`, child));
3426
+ }
3427
+ if (Array.isArray(schema2.items)) {
3428
+ schema2.items.forEach((child, index3) => push2(`items/${index3}`, child));
3429
+ } else {
3430
+ push2("items", schema2.items);
3431
+ }
3432
+ return found;
3433
+ }
3434
+ function encodeToken(key) {
3435
+ return key.replace(/~/g, "~0").replace(/\//g, "~1");
3436
+ }
3437
+ function refProblems(schema2) {
3438
+ const problems = [];
3439
+ const visit2 = (node2, pointer) => {
3440
+ const ref = node2.$ref;
3441
+ if (typeof ref === "string") {
3442
+ if (!isLocalRef(ref)) problems.push({ pointer, ref, reason: "not-local" });
3443
+ else if (resolveLocalRef(schema2, ref) === void 0) {
3444
+ problems.push({ pointer, ref, reason: "unresolved" });
3445
+ }
3446
+ }
3447
+ for (const child of childSchemas(node2)) visit2(child.schema, `${pointer}/${child.step}`);
3448
+ };
3449
+ visit2(schema2, "");
3450
+ return problems;
3451
+ }
3452
+ function refProblemMessage(owner, keyword, problem) {
3453
+ const at = `${keyword}${problem.pointer}`;
3454
+ return problem.reason === "not-local" ? `${owner}: ${at} has "$ref": ${JSON.stringify(problem.ref)}, which is not a reference into the same schema. A reference may only name a part of the schema that holds it, such as "#/$defs/rule"` : `${owner}: ${at} has "$ref": ${JSON.stringify(problem.ref)}, which names nothing in the schema. Add it under $defs, or correct the reference`;
3455
+ }
3456
+
3457
+ // cli/core/settings-locks.ts
3458
+ function lockedPathsNamed(override, schema2) {
3254
3459
  const paths = [];
3255
- if (schema2) collect(schema2, [], paths);
3460
+ if (schema2) named(schema2, schema2, override, [], paths);
3256
3461
  return paths;
3257
3462
  }
3258
- function collect(schema2, at, paths) {
3463
+ function named(root2, declared, value, at, paths) {
3464
+ if (value === void 0) return;
3465
+ const schema2 = dereference(root2, declared);
3259
3466
  if (schema2.readOnly === true) {
3260
3467
  paths.push(at);
3261
3468
  return;
3262
3469
  }
3263
- for (const [key, property] of Object.entries(schema2.properties ?? {})) {
3264
- if (typeof property === "object") collect(property, [...at, key], paths);
3470
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return;
3471
+ for (const [key, member] of Object.entries(value)) {
3472
+ const property = schema2.properties?.[key];
3473
+ if (typeof property === "object") named(root2, property, member, [...at, key], paths);
3265
3474
  }
3266
3475
  }
3267
- function lockedPathsNamed(override, schema2) {
3268
- return lockedPaths(schema2).filter((path3) => valueAt(override, path3) !== void 0);
3476
+ function unenforceableLocks(schema2) {
3477
+ const found = [];
3478
+ const visited = /* @__PURE__ */ new Set();
3479
+ const walk3 = (declared, at, inside) => {
3480
+ const ref = declared.$ref;
3481
+ if (typeof ref === "string") {
3482
+ const key = `${inside ? "entry" : "named"}\0${ref}`;
3483
+ if (visited.has(key)) return;
3484
+ visited.add(key);
3485
+ }
3486
+ const node2 = dereference(schema2, declared);
3487
+ if (node2.readOnly === true) {
3488
+ if (inside) found.push({ path: at, ...inside });
3489
+ return;
3490
+ }
3491
+ for (const [key, property] of Object.entries(node2.properties ?? {})) {
3492
+ if (typeof property === "object") walk3(property, [...at, key], inside);
3493
+ }
3494
+ const entries = { container: at, kind: "map" };
3495
+ for (const [pattern, child] of Object.entries(node2.patternProperties ?? {})) {
3496
+ if (typeof child === "object") walk3(child, [...at, `/${pattern}/`], inside ?? entries);
3497
+ }
3498
+ if (typeof node2.additionalProperties === "object") {
3499
+ walk3(node2.additionalProperties, [...at, "*"], inside ?? entries);
3500
+ }
3501
+ const items = Array.isArray(node2.items) ? node2.items : node2.items ? [node2.items] : [];
3502
+ for (const item of items) {
3503
+ if (typeof item === "object") {
3504
+ walk3(item, [...at, "[]"], inside ?? { container: at, kind: "list" });
3505
+ }
3506
+ }
3507
+ };
3508
+ walk3(schema2, [], void 0);
3509
+ return found;
3510
+ }
3511
+ function unenforceableLockMessage(identifier, lock) {
3512
+ const where3 = lock.kind === "list" ? "a list's items" : "a map's entries";
3513
+ const container2 = lock.container.length > 0 ? lock.container.join(".") : "the top level";
3514
+ return `Settings "${identifier}" property "${lock.path.join(".")}" is readOnly inside ${where3}, which a scenario adds and removes, so there is no single value for the lock to keep. Lock the whole ${lock.kind} instead: put readOnly on "${container2}"`;
3269
3515
  }
3270
3516
  function lockedSettingName(identifier, path3) {
3271
- return [identifier, ...path3].join(".");
3517
+ return settingPath(identifier, ...path3);
3272
3518
  }
3273
3519
  function lockedSettingMessage(identifier, path3) {
3274
3520
  return `"${lockedSettingName(identifier, path3)}" is read-only: the game fixes it, so no scenario or session may change it`;
@@ -3278,7 +3524,7 @@ function withoutLockedDefaults(settings, schemas) {
3278
3524
  for (const [identifier, schema2] of Object.entries(schemas)) {
3279
3525
  if (!(identifier in result)) continue;
3280
3526
  const defaults = schemaDefaults(schema2);
3281
- for (const path3 of lockedPaths(schema2)) {
3527
+ for (const path3 of lockedPathsNamed(result[identifier], schema2)) {
3282
3528
  if (path3.length === 0) {
3283
3529
  if (isDeepStrictEqual(result[identifier], defaults)) delete result[identifier];
3284
3530
  continue;
@@ -4195,13 +4441,41 @@ function validateSettingsOverrides(overrides, schemas, sourceLabel) {
4195
4441
  ${errors.join("\n")}` } : { valid: true };
4196
4442
  }
4197
4443
  function validatePartialOverride(override, settingsSchema) {
4198
- const validator = settingsAjv.compile(closed(withoutRequired(settingsSchema)));
4444
+ let validator;
4445
+ try {
4446
+ validator = settingsAjv.compile(closed(withoutRequired(settingsSchema)));
4447
+ } catch (error) {
4448
+ return [
4449
+ {
4450
+ keyword: "compile",
4451
+ instancePath: "",
4452
+ schemaPath: "#",
4453
+ params: {},
4454
+ message: `cannot be checked: its settings schema does not compile (${error instanceof Error ? error.message : String(error)})`
4455
+ }
4456
+ ];
4457
+ }
4199
4458
  return validator(override) ? null : validator.errors ?? [];
4200
4459
  }
4201
4460
  var SCHEMA_MAP_KEYWORDS = ["properties", "patternProperties", "definitions", "$defs"];
4202
4461
  var SUBSCHEMA_KEYWORDS = ["additionalProperties", "then", "else"];
4203
4462
  var SCHEMA_LIST_KEYWORDS = ["allOf", "anyOf", "oneOf"];
4204
4463
  function withoutRequired(schema2) {
4464
+ const partial = partially(schema2);
4465
+ if (typeof schema2 !== "object" || typeof partial !== "object") return partial;
4466
+ for (const keyword of DEFINITION_KEYWORDS) {
4467
+ const defs = schema2[keyword];
4468
+ const copied = partial[keyword];
4469
+ if (!defs || typeof defs !== "object" || !copied || typeof copied !== "object") continue;
4470
+ for (const [name, def] of Object.entries(defs)) {
4471
+ copied[`${WHOLE}${name}`] = wholeRefs(def);
4472
+ }
4473
+ }
4474
+ return partial;
4475
+ }
4476
+ var DEFINITION_KEYWORDS = ["$defs", "definitions"];
4477
+ var WHOLE = "__whole__";
4478
+ function partially(schema2) {
4205
4479
  if (typeof schema2 !== "object" || schema2 === null) return schema2;
4206
4480
  const { required: _required, ...rest } = schema2;
4207
4481
  const copy = { ...rest };
@@ -4209,20 +4483,32 @@ function withoutRequired(schema2) {
4209
4483
  const map3 = rest[keyword];
4210
4484
  if (map3 && typeof map3 === "object") {
4211
4485
  copy[keyword] = Object.fromEntries(
4212
- Object.entries(map3).map(([key, value]) => [key, withoutRequired(value)])
4486
+ Object.entries(map3).map(([key, value]) => [key, partially(value)])
4213
4487
  );
4214
4488
  }
4215
4489
  }
4216
4490
  for (const keyword of SUBSCHEMA_KEYWORDS) {
4217
4491
  const sub = rest[keyword];
4218
- if (sub !== void 0) copy[keyword] = withoutRequired(sub);
4492
+ if (sub !== void 0) copy[keyword] = partially(sub);
4219
4493
  }
4220
4494
  for (const keyword of SCHEMA_LIST_KEYWORDS) {
4221
4495
  const list3 = rest[keyword];
4222
- if (Array.isArray(list3)) copy[keyword] = list3.map(withoutRequired);
4496
+ if (Array.isArray(list3)) copy[keyword] = list3.map(partially);
4223
4497
  }
4498
+ if (rest.items !== void 0) copy.items = wholeRefs(rest.items);
4224
4499
  return copy;
4225
4500
  }
4501
+ var DATA_KEYWORDS = /* @__PURE__ */ new Set(["default", "const", "enum", "examples"]);
4502
+ function wholeRefs(value) {
4503
+ if (Array.isArray(value)) return value.map(wholeRefs);
4504
+ if (value === null || typeof value !== "object") return value;
4505
+ return Object.fromEntries(
4506
+ Object.entries(value).map(([key, child]) => [
4507
+ key,
4508
+ key === "$ref" && typeof child === "string" ? child.replace(/^#\/(\$defs|definitions)\/(?=[^/]+$)/, `#/$1/${WHOLE}`) : DATA_KEYWORDS.has(key) ? child : wholeRefs(child)
4509
+ ])
4510
+ );
4511
+ }
4226
4512
  var COMBINATOR_KEYWORDS = ["allOf", "anyOf", "oneOf", "if", "not", "$ref"];
4227
4513
  function closed(schema2) {
4228
4514
  if (typeof schema2 !== "object" || schema2 === null) return schema2;
@@ -4824,12 +5110,12 @@ function assertRequiredFeaturesSupported(config, filePath) {
4824
5110
  function assertDeclaredServicesSupported(resources) {
4825
5111
  const missing = unsupportedServices(resources);
4826
5112
  if (missing.length === 0) return;
4827
- const named2 = missing.map(
5113
+ const named3 = missing.map(
4828
5114
  ({ service, resources: declaring }) => `"${service}" (declared by ${declaring.join(", ")})`
4829
5115
  ).join(", ");
4830
5116
  throw new CliError(
4831
5117
  "PACKAGE_INVALID",
4832
- `Invalid package: its resources declare ${named2} in \`uses\`, which this version of the SDK does not provide. Upgrade the SDK, or remove the service from \`uses\` if the resource does not call it.`
5118
+ `Invalid package: its resources declare ${named3} in \`uses\`, which this version of the SDK does not provide. Upgrade the SDK, or remove the service from \`uses\` if the resource does not call it.`
4833
5119
  );
4834
5120
  }
4835
5121
  function resolvePackage(config, configDir, game) {
@@ -6030,20 +6316,20 @@ function assertDeletesDeclared(label4, deletes, declaration, shared, target) {
6030
6316
  const reads = new Set(declaration.reads ?? []);
6031
6317
  for (const path3 of deletes) {
6032
6318
  const capId = deleteHead(path3);
6033
- const named2 = `${label4} deletes ${describeDeletePath(path3)}`;
6319
+ const named3 = `${label4} deletes ${describeDeletePath(path3)}`;
6034
6320
  if (target === "team" && shared.has(capId)) {
6035
6321
  throw new Error(
6036
- `${named2} under shared capability "${capId}". A shared capability has one value for the session, so only an aggregate result's "shared" or a session-scoped endpoint may change it.`
6322
+ `${named3} under shared capability "${capId}". A shared capability has one value for the session, so only an aggregate result's "shared" or a session-scoped endpoint may change it.`
6037
6323
  );
6038
6324
  }
6039
6325
  if (target === "shared" && !shared.has(capId)) {
6040
6326
  throw new Error(
6041
- `${named2} under "${capId}", which is not a shared-scope capability. Only shared capabilities may be deleted from a shared result.`
6327
+ `${named3} under "${capId}", which is not a shared-scope capability. Only shared capabilities may be deleted from a shared result.`
6042
6328
  );
6043
6329
  }
6044
6330
  if (!writes.has(capId)) {
6045
6331
  throw new Error(
6046
- reads.has(capId) ? `${named2} under capability "${capId}", but declares it only in reads. Add it to writes, or leave it alone.` : `${named2} under "${capId}", which it does not declare in writes.`
6332
+ reads.has(capId) ? `${named3} under capability "${capId}", but declares it only in reads. Add it to writes, or leave it alone.` : `${named3} under "${capId}", which it does not declare in writes.`
6047
6333
  );
6048
6334
  }
6049
6335
  }
@@ -6323,7 +6609,7 @@ function computeCapabilityDefaults(config) {
6323
6609
  // cli/storage/blob-store.ts
6324
6610
  import { randomUUID } from "crypto";
6325
6611
  import { existsSync as existsSync4 } from "fs";
6326
- import { mkdir as mkdir2, readdir as readdir2, readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
6612
+ import { mkdir as mkdir2, readdir as readdir2, readFile as readFile2, rm, stat, writeFile as writeFile2 } from "fs/promises";
6327
6613
  import { join as join3, resolve as resolve2 } from "path";
6328
6614
  var MAX_BLOB_SIZE = 20 * 1024 * 1024;
6329
6615
  var redirected = /* @__PURE__ */ new Map();
@@ -6373,6 +6659,18 @@ async function readBlob(packagePath, id) {
6373
6659
  const meta = JSON.parse(metaRaw);
6374
6660
  return { ...meta, data };
6375
6661
  }
6662
+ async function describeBlob(packagePath, id) {
6663
+ const dir = getBlobsDir(packagePath);
6664
+ try {
6665
+ const [metaRaw, bin] = await Promise.all([
6666
+ readFile2(metaPath(dir, id), "utf-8"),
6667
+ stat(binPath(dir, id))
6668
+ ]);
6669
+ return { ...JSON.parse(metaRaw), size: bin.size };
6670
+ } catch {
6671
+ return void 0;
6672
+ }
6673
+ }
6376
6674
  async function deleteBlobs(packagePath, retentions) {
6377
6675
  const dir = getBlobsDir(packagePath);
6378
6676
  let entries;
@@ -6397,19 +6695,62 @@ async function deleteBlobs(packagePath, retentions) {
6397
6695
  );
6398
6696
  }
6399
6697
 
6698
+ // cli/utils/schema-members.ts
6699
+ function memberSchemas(schema2, key) {
6700
+ const found = [];
6701
+ let declared = false;
6702
+ const named3 = schema2.properties?.[key];
6703
+ if (named3 !== void 0) {
6704
+ declared = true;
6705
+ if (typeof named3 === "object") found.push(named3);
6706
+ }
6707
+ for (const [pattern, child] of Object.entries(schema2.patternProperties ?? {})) {
6708
+ if (!matches2(pattern, key)) continue;
6709
+ declared = true;
6710
+ if (typeof child === "object") found.push(child);
6711
+ }
6712
+ if (!declared && typeof schema2.additionalProperties === "object") {
6713
+ found.push(schema2.additionalProperties);
6714
+ }
6715
+ return found;
6716
+ }
6717
+ function memberDeclarations(schema2) {
6718
+ const found = [];
6719
+ for (const [key, child] of Object.entries(schema2.properties ?? {})) {
6720
+ if (typeof child === "object") found.push({ step: key, schema: child });
6721
+ }
6722
+ for (const [pattern, child] of Object.entries(schema2.patternProperties ?? {})) {
6723
+ if (typeof child === "object") found.push({ step: `/${pattern}/`, schema: child });
6724
+ }
6725
+ if (typeof schema2.additionalProperties === "object") {
6726
+ found.push({ step: "*", schema: schema2.additionalProperties });
6727
+ }
6728
+ return found;
6729
+ }
6730
+ function matches2(pattern, key) {
6731
+ try {
6732
+ return new RegExp(pattern, "u").test(key);
6733
+ } catch {
6734
+ return false;
6735
+ }
6736
+ }
6737
+
6400
6738
  // cli/execution/blob-inputs.ts
6401
6739
  var MAX_INLINE_BYTES = 5 * 1024 * 1024;
6402
- function blobValues(schema2, value, path3 = []) {
6403
- if (!schema2 || typeof schema2 !== "object") return [];
6740
+ function blobValues(declared, value, path3 = [], root2 = declared) {
6741
+ if (!declared || typeof declared !== "object" || !root2) return [];
6742
+ const schema2 = dereference(root2, declared);
6404
6743
  const spec = schema2.blob;
6405
6744
  if (spec) return value === void 0 ? [] : [{ path: path3, spec, value }];
6406
6745
  if (Array.isArray(value) && schema2.items && !Array.isArray(schema2.items)) {
6407
6746
  const items = schema2.items;
6408
- return value.flatMap((item, at) => blobValues(items, item, [...path3, at]));
6747
+ return value.flatMap((item, at) => blobValues(items, item, [...path3, at], root2));
6409
6748
  }
6410
- if (value && typeof value === "object" && !Array.isArray(value) && schema2.properties) {
6411
- return Object.entries(schema2.properties).flatMap(
6412
- ([key, child]) => typeof child === "object" ? blobValues(child, value[key], [...path3, key]) : []
6749
+ if (value && typeof value === "object" && !Array.isArray(value)) {
6750
+ return Object.entries(value).flatMap(
6751
+ ([key, member]) => memberSchemas(schema2, key).flatMap(
6752
+ (child) => blobValues(child, member, [...path3, key], root2)
6753
+ )
6413
6754
  );
6414
6755
  }
6415
6756
  return [];
@@ -6524,7 +6865,7 @@ var ACTION_FIELDS = {
6524
6865
  addTeam: { "name?": "string" },
6525
6866
  setLocale: { locale: "string" }
6526
6867
  };
6527
- function matches2(value, kind2) {
6868
+ function matches3(value, kind2) {
6528
6869
  switch (kind2) {
6529
6870
  case "string":
6530
6871
  return typeof value === "string" && value.length > 0;
@@ -6562,7 +6903,7 @@ function readEndpointActions(identifier, declared, returned) {
6562
6903
  if (key.endsWith("?")) continue;
6563
6904
  throw new Error(`${label4} ("${type}") requires "${name}"`);
6564
6905
  }
6565
- if (!matches2(value, kind2)) {
6906
+ if (!matches3(value, kind2)) {
6566
6907
  throw new Error(`${label4} ("${type}") field "${name}" must be a ${kind2}`);
6567
6908
  }
6568
6909
  }
@@ -6919,7 +7260,7 @@ var EndpointRunner = class {
6919
7260
  const callbacks = calls.callbacksFor(
6920
7261
  endpoint.definition.identifier,
6921
7262
  endpoint.definition.uses,
6922
- scenarioScoped ? "scenario" : void 0
7263
+ scenarioScoped ? { scenarioRoot: args.scenarioRoot ?? null } : void 0
6923
7264
  );
6924
7265
  const scope = sessionScoped || scenarioScoped ? null : args.scopedTeamIndex ?? null;
6925
7266
  const label4 = exportName === "Handle" ? `Endpoint "${args.identifier}"` : `Endpoint "${args.identifier}" ${exportName}`;
@@ -7143,21 +7484,6 @@ async function runHookChain(host, signal, payload) {
7143
7484
  return structuredClone(host.board());
7144
7485
  }
7145
7486
 
7146
- // ../sdk/lib/build/callbacks.js
7147
- var UndeclaredApiUseError = class extends Error {
7148
- resourceIdentifier;
7149
- api;
7150
- constructor(resourceIdentifier, api) {
7151
- super(`Resource "${resourceIdentifier}" attempted to call callback "${api}" but did not declare it in its bundle's "uses" array. Add "${api}" to the bundle's uses to allow this call.`);
7152
- this.name = "UndeclaredApiUseError";
7153
- this.resourceIdentifier = resourceIdentifier;
7154
- this.api = api;
7155
- }
7156
- };
7157
-
7158
- // ../sdk/lib/build/tick-validation.js
7159
- var MAX_EFFECTIVE_TICK_INTERVAL_MS = 7 * 24 * 60 * 60 * 1e3;
7160
-
7161
7487
  // cli/runtime/guarded-callbacks.ts
7162
7488
  var API_USE_TO_CALLBACK = {
7163
7489
  generateText: "generateText",
@@ -7179,68 +7505,106 @@ function createGuardedCallbacks(callbacks, uses, resourceIdentifier) {
7179
7505
  }
7180
7506
 
7181
7507
  // cli/storage/asset-resolver.ts
7182
- import { readFile as readFile3 } from "fs/promises";
7508
+ import { readFile as readFile3, stat as stat2 } from "fs/promises";
7183
7509
  import { basename as basename2, isAbsolute as isAbsolute3, normalize, resolve as resolvePath, sep as sep4 } from "path";
7184
7510
  var ASSET_PREFIX = "asset:";
7185
7511
  var SHARED_PREFIX = "shared:";
7186
7512
  var BLOB_PREFIX = "blob:";
7187
- var EXTENSION_MIME_TYPES = {
7188
- pdf: "application/pdf",
7189
- json: "application/json",
7190
- txt: "text/plain",
7191
- md: "text/markdown",
7192
- html: "text/html",
7193
- htm: "text/html",
7513
+ var EXTENSION_MEDIA_TYPES = {
7514
+ aac: "audio/aac",
7515
+ avif: "image/avif",
7516
+ bmp: "image/bmp",
7194
7517
  css: "text/css",
7195
7518
  csv: "text/csv",
7196
- svg: "image/svg+xml",
7197
- png: "image/png",
7198
- jpg: "image/jpeg",
7199
- jpeg: "image/jpeg",
7519
+ doc: "application/msword",
7520
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
7521
+ flac: "audio/flac",
7200
7522
  gif: "image/gif",
7201
- webp: "image/webp",
7523
+ htm: "text/html",
7524
+ html: "text/html",
7202
7525
  ico: "image/x-icon",
7526
+ jpeg: "image/jpeg",
7527
+ jpg: "image/jpeg",
7528
+ js: "text/javascript",
7529
+ json: "application/json",
7530
+ m4a: "audio/mp4",
7531
+ m4v: "video/mp4",
7532
+ md: "text/markdown",
7533
+ mjs: "text/javascript",
7534
+ mov: "video/quicktime",
7203
7535
  mp3: "audio/mpeg",
7204
- wav: "audio/wav",
7536
+ mp4: "video/mp4",
7537
+ odp: "application/vnd.oasis.opendocument.presentation",
7538
+ ods: "application/vnd.oasis.opendocument.spreadsheet",
7539
+ odt: "application/vnd.oasis.opendocument.text",
7205
7540
  ogg: "audio/ogg",
7206
7541
  opus: "audio/ogg",
7207
- mp4: "video/mp4",
7542
+ otf: "font/otf",
7543
+ pdf: "application/pdf",
7544
+ png: "image/png",
7545
+ ppt: "application/vnd.ms-powerpoint",
7546
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
7547
+ rtf: "application/rtf",
7548
+ svg: "image/svg+xml",
7549
+ tif: "image/tiff",
7550
+ tiff: "image/tiff",
7551
+ ttf: "font/ttf",
7552
+ txt: "text/plain",
7553
+ vtt: "text/vtt",
7554
+ wav: "audio/wav",
7208
7555
  webm: "video/webm",
7556
+ webp: "image/webp",
7209
7557
  woff: "font/woff",
7210
- woff2: "font/woff2"
7558
+ woff2: "font/woff2",
7559
+ xls: "application/vnd.ms-excel",
7560
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
7561
+ xml: "application/xml",
7562
+ yaml: "application/yaml",
7563
+ yml: "application/yaml",
7564
+ zip: "application/zip"
7211
7565
  };
7212
- function mimeFromExtension(path3) {
7213
- const dot = path3.lastIndexOf(".");
7214
- if (dot < 0) return "application/octet-stream";
7215
- const ext = path3.slice(dot + 1).toLowerCase();
7216
- return EXTENSION_MIME_TYPES[ext] ?? "application/octet-stream";
7566
+ var UNLISTED_MEDIA_TYPE = "application/octet-stream";
7567
+ function mediaTypeOf(path3) {
7568
+ const name = path3.slice(Math.max(path3.lastIndexOf("/"), path3.lastIndexOf("\\")) + 1);
7569
+ const dot = name.lastIndexOf(".");
7570
+ if (dot < 0) return UNLISTED_MEDIA_TYPE;
7571
+ const ext = name.slice(dot + 1).toLowerCase();
7572
+ return Object.hasOwn(EXTENSION_MEDIA_TYPES, ext) ? EXTENSION_MEDIA_TYPES[ext] : UNLISTED_MEDIA_TYPE;
7217
7573
  }
7218
7574
  function isAssetReference(value) {
7219
7575
  return typeof value === "string" && (value.startsWith(ASSET_PREFIX) || value.startsWith(SHARED_PREFIX) || value.startsWith(BLOB_PREFIX));
7220
7576
  }
7221
- async function resolveAsset(scenarioRootDirectory, path3) {
7577
+ function scenarioAssetPath(scenarioRootDirectory, path3) {
7222
7578
  const assetsRoot = resolvePath(scenarioRootDirectory, "assets");
7223
7579
  const resolvedPath = resolvePath(assetsRoot, normalize(path3));
7224
7580
  if (!resolvedPath.startsWith(assetsRoot + sep4)) {
7225
7581
  throw new Error(`Asset path escapes scenario assets directory: ${path3}`);
7226
7582
  }
7583
+ return resolvedPath;
7584
+ }
7585
+ function sharedAssetPath(packagePath, path3) {
7586
+ const sharedRoot = resolvePath(packagePath, "shared-assets");
7587
+ const resolvedPath = resolvePath(sharedRoot, normalize(path3));
7588
+ if (!resolvedPath.startsWith(sharedRoot + sep4)) {
7589
+ throw new Error(`Asset path escapes shared-assets directory: ${path3}`);
7590
+ }
7591
+ return resolvedPath;
7592
+ }
7593
+ async function resolveAsset(scenarioRootDirectory, path3) {
7594
+ const resolvedPath = scenarioAssetPath(scenarioRootDirectory, path3);
7227
7595
  const data = await readFile3(resolvedPath);
7228
7596
  return {
7229
7597
  data,
7230
- mimeType: mimeFromExtension(resolvedPath),
7598
+ mimeType: mediaTypeOf(resolvedPath),
7231
7599
  name: basename2(resolvedPath)
7232
7600
  };
7233
7601
  }
7234
7602
  async function resolveSharedAsset(packagePath, path3) {
7235
- const sharedRoot = resolvePath(packagePath, "shared-assets");
7236
- const resolvedPath = resolvePath(sharedRoot, normalize(path3));
7237
- if (!resolvedPath.startsWith(sharedRoot + sep4)) {
7238
- throw new Error(`Asset path escapes shared-assets directory: ${path3}`);
7239
- }
7603
+ const resolvedPath = sharedAssetPath(packagePath, path3);
7240
7604
  const data = await readFile3(resolvedPath);
7241
7605
  return {
7242
7606
  data,
7243
- mimeType: mimeFromExtension(resolvedPath),
7607
+ mimeType: mediaTypeOf(resolvedPath),
7244
7608
  name: basename2(resolvedPath)
7245
7609
  };
7246
7610
  }
@@ -7266,6 +7630,30 @@ async function readAssetByReference(packagePath, scenarioRootDirectory, referenc
7266
7630
  `Invalid asset reference "${reference}": expected an "asset:", "shared:", or "blob:" prefix`
7267
7631
  );
7268
7632
  }
7633
+ async function describeAssetByReference(packagePath, scenarioRootDirectory, reference) {
7634
+ if (reference.startsWith(BLOB_PREFIX)) {
7635
+ const blob = await describeBlob(packagePath, reference.slice(BLOB_PREFIX.length));
7636
+ return blob && { mimeType: blob.mimeType, size: blob.size };
7637
+ }
7638
+ let path3;
7639
+ if (reference.startsWith(SHARED_PREFIX)) {
7640
+ path3 = sharedAssetPath(packagePath, reference.slice(SHARED_PREFIX.length));
7641
+ } else if (reference.startsWith(ASSET_PREFIX)) {
7642
+ if (!scenarioRootDirectory) return void 0;
7643
+ const root2 = isAbsolute3(scenarioRootDirectory) ? scenarioRootDirectory : resolvePath(packagePath, scenarioRootDirectory);
7644
+ path3 = scenarioAssetPath(root2, reference.slice(ASSET_PREFIX.length));
7645
+ } else {
7646
+ throw new Error(
7647
+ `Invalid asset reference "${reference}": expected an "asset:", "shared:", or "blob:" prefix`
7648
+ );
7649
+ }
7650
+ try {
7651
+ const file = await stat2(path3);
7652
+ return file.isFile() ? { mimeType: mediaTypeOf(path3), size: file.size } : void 0;
7653
+ } catch {
7654
+ return void 0;
7655
+ }
7656
+ }
7269
7657
 
7270
7658
  // cli/execution/executor-callbacks.ts
7271
7659
  function createExecutorCallbacks(deps) {
@@ -7308,6 +7696,16 @@ function createExecutorCallbacks(deps) {
7308
7696
  name: asset.name
7309
7697
  };
7310
7698
  },
7699
+ // Not `uses`-gated, like `readAsset`, and resolved exactly as it is,
7700
+ // so a file one finds is one the other reads (§10.3).
7701
+ describeAsset: async (reference) => {
7702
+ requireGame();
7703
+ return describeAssetByReference(
7704
+ deps.packagePath,
7705
+ deps.getActiveScenarioRoot(),
7706
+ reference
7707
+ );
7708
+ },
7311
7709
  extractText: async (reference) => {
7312
7710
  requireGame();
7313
7711
  const asset = await readAssetByReference(
@@ -7532,11 +7930,18 @@ var LogicCalls = class {
7532
7930
  * The callbacks a resource receives: the raw runtime callbacks, built
7533
7931
  * fresh so they read the live game, with every one its `uses` does not
7534
7932
  * declare replaced by a throwing stub.
7933
+ *
7934
+ * `onDraft` is a scenario-scoped call's: its files are the draft's, and
7935
+ * `asset:` resolves against the scenario being written, not the session's
7936
+ * (§6.5, §6.12, §16.2).
7535
7937
  */
7536
- callbacksFor(resourceIdentifier, uses, blobRetention) {
7938
+ callbacksFor(resourceIdentifier, uses, onDraft) {
7537
7939
  const raw = createExecutorCallbacks({
7538
7940
  ...this.options.callbacks,
7539
- ...blobRetention === void 0 ? {} : { blobRetention },
7941
+ ...onDraft === void 0 ? {} : {
7942
+ blobRetention: "scenario",
7943
+ getActiveScenarioRoot: () => onDraft.scenarioRoot
7944
+ },
7540
7945
  readPastState: this.pastStateReader,
7541
7946
  getScopedTeamIndexes: () => this.scopedTeamIndexes,
7542
7947
  getAllTeamIndexes: () => this.teamIndexesForHistory(),
@@ -21986,8 +22391,10 @@ function isUint8Array2(value) {
21986
22391
  // cli/guide/settings.ts
21987
22392
  var WHEN_ATTRIBUTES = ["setting", "is", "not"];
21988
22393
  function lookupSetting(settings, path3) {
21989
- const [identifier, ...keys] = path3.split(".");
21990
- if (!identifier || keys.length === 0 || !(identifier in settings)) return { found: false };
22394
+ const parsed = parseSettingPath(path3);
22395
+ if (!parsed || parsed.keys.length === 0) return { found: false };
22396
+ const { identifier, keys } = parsed;
22397
+ if (!Object.prototype.hasOwnProperty.call(settings, identifier)) return { found: false };
21991
22398
  let value = settings[identifier];
21992
22399
  for (const key of keys) {
21993
22400
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -22394,6 +22801,7 @@ function swallow() {
22394
22801
 
22395
22802
  // cli/core/participant-registry.ts
22396
22803
  import { EventEmitter } from "events";
22804
+ var MAX_PARTICIPANT_NAME_LENGTH = 60;
22397
22805
  var ParticipantRegistry = class extends EventEmitter {
22398
22806
  teams = /* @__PURE__ */ new Map();
22399
22807
  /**
@@ -22947,6 +23355,7 @@ var SessionEndpoints = class {
22947
23355
  request: command.request,
22948
23356
  settings: edited.settings,
22949
23357
  scenarioName: edited.scenarioName,
23358
+ scenarioRoot: edited.scenarioRoot,
22950
23359
  now: this.host.clock.now(),
22951
23360
  caller: {
22952
23361
  role: "author",
@@ -23663,6 +24072,16 @@ var SessionRoster = class {
23663
24072
  if (!teamId) throw new DeniedError("The caller is not on a team");
23664
24073
  return this.renameTeam(teamId, command.name);
23665
24074
  }
24075
+ renameSelf(command) {
24076
+ if (!command.participantId)
24077
+ throw new DeniedError("Only a participant can rename themselves");
24078
+ const trimmed = command.name.trim();
24079
+ if (!trimmed) throw new DeniedError("A name cannot be blank");
24080
+ if (trimmed.length > MAX_PARTICIPANT_NAME_LENGTH) {
24081
+ throw new DeniedError(`A name is at most ${MAX_PARTICIPANT_NAME_LENGTH} characters`);
24082
+ }
24083
+ return this.renameParticipant(command.participantId, trimmed);
24084
+ }
23666
24085
  async addParticipant(teamId, name) {
23667
24086
  if (!this.host.state.getTeamIndexes().some((i) => `team-${i + 1}` === teamId)) {
23668
24087
  throw new DeniedError(`Unknown team "${teamId}"`);
@@ -24359,36 +24778,45 @@ var SessionTimers = class {
24359
24778
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
24360
24779
 
24361
24780
  // cli/validation/file-settings.ts
24362
- function fileSettingValues(schema2, value, path3 = []) {
24363
- if (!schema2 || typeof schema2 !== "object") return [];
24781
+ function fileSettingValues(declared, value, path3 = [], root2 = declared) {
24782
+ if (!declared || typeof declared !== "object" || !root2) return [];
24783
+ const schema2 = dereference(root2, declared);
24364
24784
  const spec = schema2.blob;
24365
24785
  if (spec) return value === void 0 ? [] : [{ path: path3, spec, value }];
24366
24786
  if (Array.isArray(value) && schema2.items && !Array.isArray(schema2.items)) {
24367
24787
  const items = schema2.items;
24368
- return value.flatMap((item, at) => fileSettingValues(items, item, [...path3, String(at)]));
24788
+ return value.flatMap(
24789
+ (item, at) => fileSettingValues(items, item, [...path3, String(at)], root2)
24790
+ );
24369
24791
  }
24370
- if (value && typeof value === "object" && !Array.isArray(value) && schema2.properties) {
24371
- return Object.entries(schema2.properties).flatMap(
24372
- ([key, child]) => typeof child === "object" ? fileSettingValues(child, value[key], [...path3, key]) : []
24792
+ if (value && typeof value === "object" && !Array.isArray(value)) {
24793
+ return Object.entries(value).flatMap(
24794
+ ([key, member]) => memberSchemas(schema2, key).flatMap(
24795
+ (child) => fileSettingValues(child, member, [...path3, key], root2)
24796
+ )
24373
24797
  );
24374
24798
  }
24375
24799
  return [];
24376
24800
  }
24377
- function fileSettingDeclarations(schema2, path3 = []) {
24801
+ function fileSettingDeclarations(root2, declared = root2, path3 = [], followed = /* @__PURE__ */ new Set()) {
24802
+ if (typeof declared.$ref === "string") {
24803
+ if (followed.has(declared.$ref)) return [];
24804
+ followed.add(declared.$ref);
24805
+ }
24806
+ const schema2 = dereference(root2, declared);
24378
24807
  const found = [];
24379
24808
  if ("blob" in schema2) found.push({ path: path3, schema: schema2 });
24380
- for (const [key, child] of Object.entries(schema2.properties ?? {})) {
24381
- if (typeof child === "object")
24382
- found.push(...fileSettingDeclarations(child, [...path3, key]));
24809
+ for (const { step, schema: child } of memberDeclarations(schema2)) {
24810
+ found.push(...fileSettingDeclarations(root2, child, [...path3, step], followed));
24383
24811
  }
24384
24812
  if (schema2.items && !Array.isArray(schema2.items) && typeof schema2.items === "object") {
24385
- found.push(...fileSettingDeclarations(schema2.items, [...path3, "[]"]));
24813
+ found.push(...fileSettingDeclarations(root2, schema2.items, [...path3, "[]"], followed));
24386
24814
  }
24387
24815
  return found;
24388
24816
  }
24389
24817
  var MEDIA_TYPE = /^[^/\s]+\/[^/\s]+$/;
24390
24818
  function where2(identifier, path3) {
24391
- return [identifier, ...path3].join(".");
24819
+ return settingPath(identifier, ...path3);
24392
24820
  }
24393
24821
  function fileSettingDeclarationErrors(identifier, settingsSchema) {
24394
24822
  const errors = [];
@@ -24419,12 +24847,17 @@ function fileSettingDeclarationErrors(identifier, settingsSchema) {
24419
24847
  }
24420
24848
  for (const [key, property] of Object.entries(settingsSchema.properties ?? {})) {
24421
24849
  if (typeof property !== "object" || !("default" in property)) continue;
24422
- for (const { path: path3, value } of fileSettingValues(property, property.default, [key])) {
24850
+ for (const { path: path3, value } of fileSettingValues(
24851
+ property,
24852
+ property.default,
24853
+ [],
24854
+ settingsSchema
24855
+ )) {
24423
24856
  if (typeof value !== "string" || value === "" || value.startsWith("shared:")) {
24424
24857
  continue;
24425
24858
  }
24426
24859
  errors.push(
24427
- `Settings "${identifier}" property "${path3.join(".")}" holds a file and defaults to ${JSON.stringify(value)}. A default resolves with no scenario active, so it must be empty for no file or a \`shared:\` reference`
24860
+ `Settings "${identifier}" property "${settingPath(key, ...path3)}" holds a file and defaults to ${JSON.stringify(value)}. A default resolves with no scenario active, so it must be empty for no file or a \`shared:\` reference`
24428
24861
  );
24429
24862
  }
24430
24863
  }
@@ -24452,13 +24885,13 @@ async function packageFileSettingErrors(owner, settings, schemas, resolve12, ski
24452
24885
  }
24453
24886
  return errors;
24454
24887
  }
24455
- async function fileSettingWriteErrors(overrides, schemas, describeBlob, options = {}) {
24888
+ async function fileSettingWriteErrors(overrides, schemas, describeBlob2, options = {}) {
24456
24889
  const errors = [];
24457
24890
  for (const [identifier, value] of Object.entries(overrides)) {
24458
24891
  for (const file of fileSettingValues(schemas[identifier], value)) {
24459
24892
  if (typeof file.value !== "string" || !file.value.startsWith("blob:")) continue;
24460
24893
  const setting = `Setting ${where2(identifier, file.path)}`;
24461
- const found = await describeBlob(file.value);
24894
+ const found = await describeBlob2(file.value);
24462
24895
  if (!found) {
24463
24896
  errors.push(
24464
24897
  `${setting} names ${file.value}, which is not a stored blob. Upload the file first and use the reference it returns`
@@ -24533,13 +24966,13 @@ async function updateSharedContext(host, command) {
24533
24966
  const declared = new Set(
24534
24967
  surface && "writes" in surface.definition ? surface.definition.writes ?? [] : []
24535
24968
  );
24536
- const named2 = [...Object.keys(command.payload), ...(command.deletes ?? []).map(deleteHead)];
24969
+ const named3 = [...Object.keys(command.payload), ...(command.deletes ?? []).map(deleteHead)];
24537
24970
  const declaredByPackage = new Set(
24538
24971
  (executor.getConfig()?.capabilities ?? []).map(
24539
24972
  (capability) => capability.definition.identifier
24540
24973
  )
24541
24974
  );
24542
- for (const capability of named2) {
24975
+ for (const capability of named3) {
24543
24976
  if (!shared.has(capability)) {
24544
24977
  if (declaredByPackage.has(capability)) {
24545
24978
  throw new DeniedError(
@@ -24636,11 +25069,11 @@ function refuseUndeclaredTeamWrite(host, uiIdentifier, payload, deletes) {
24636
25069
  const capabilities = new Set(
24637
25070
  (host.executor.getConfig()?.capabilities ?? []).map((cap) => cap.definition.identifier)
24638
25071
  );
24639
- const named2 = [
25072
+ const named3 = [
24640
25073
  ...Object.keys(payload),
24641
25074
  ...(deletes ?? []).map((path3) => (typeof path3 === "string" ? path3.split(".") : path3)[0])
24642
25075
  ];
24643
- for (const key of named2) {
25076
+ for (const key of named3) {
24644
25077
  if (key === void 0 || !capabilities.has(key)) {
24645
25078
  throw new DeniedError(
24646
25079
  `"${key}" is not a capability of this game, so "${uiIdentifier}" cannot write it`
@@ -25090,6 +25523,7 @@ var PLAY_STAGE = /* @__PURE__ */ new Set([
25090
25523
  "renameParticipant",
25091
25524
  "moveParticipant",
25092
25525
  "renameOwnTeam",
25526
+ "renameSelf",
25093
25527
  "extendTick"
25094
25528
  ]);
25095
25529
  var STALE_BLOCKED = /* @__PURE__ */ new Set([
@@ -25214,19 +25648,11 @@ var Session = class {
25214
25648
  applyPendingChanges: () => this.applyPendingChanges(),
25215
25649
  clearBlobs: (retentions) => this.clearBlobs(retentions),
25216
25650
  describeBlob: async (reference) => {
25217
- try {
25218
- const blob = await readBlob(
25219
- this.options.packagePath,
25220
- reference.slice("blob:".length)
25221
- );
25222
- return {
25223
- mimeType: blob.mimeType,
25224
- size: blob.data.length,
25225
- retention: blob.retention
25226
- };
25227
- } catch {
25228
- return void 0;
25229
- }
25651
+ const blob = await describeBlob(
25652
+ this.options.packagePath,
25653
+ reference.slice("blob:".length)
25654
+ );
25655
+ return blob && { mimeType: blob.mimeType, size: blob.size, retention: blob.retention };
25230
25656
  },
25231
25657
  enqueue: (work) => this.enqueue(work),
25232
25658
  apply: (command) => this.apply(command),
@@ -25744,6 +26170,8 @@ var Session = class {
25744
26170
  return this.roster.renameTeam(command.teamId, command.name);
25745
26171
  case "renameOwnTeam":
25746
26172
  return this.roster.renameOwnTeam(command);
26173
+ case "renameSelf":
26174
+ return this.roster.renameSelf(command);
25747
26175
  case "addParticipant":
25748
26176
  return this.roster.addParticipant(command.teamId, command.name);
25749
26177
  case "renameParticipant":
@@ -25916,6 +26344,12 @@ var Session = class {
25916
26344
  await deleteBlobs(this.options.packagePath, retentions);
25917
26345
  }
25918
26346
  setLocale(locale) {
26347
+ const supported = this.packageConfiguration()?.game?.definition.supportedLocales;
26348
+ if (supported?.length && !supported.includes(locale)) {
26349
+ throw new DeniedError(
26350
+ `"${locale}" is not one of this game's locales (${supported.join(", ")})`
26351
+ );
26352
+ }
25919
26353
  this.locale = locale;
25920
26354
  this.executor.setLocale(locale);
25921
26355
  return void 0;
@@ -26050,11 +26484,11 @@ var Session = class {
26050
26484
  if (scenarioId !== null && !this.declaredScenarioIds().has(scenarioId)) {
26051
26485
  throw new DeniedError(`This package declares no scenario "${scenarioId}" to edit`);
26052
26486
  }
26487
+ const scenario = this.executor.getConfig()?.scenarios?.find((entry) => entry.definition.identifier === scenarioId);
26053
26488
  return {
26054
26489
  settings: this.scenarioDraft(scenarioId) ?? this.executor.resolveScenarioDraft(scenarioId, null),
26055
- scenarioName: this.executor.scenarioNameOf(
26056
- this.executor.getConfig()?.scenarios?.find((scenario) => scenario.definition.identifier === scenarioId)
26057
- )
26490
+ scenarioName: this.executor.scenarioNameOf(scenario),
26491
+ scenarioRoot: scenario?.rootDirectory ?? null
26058
26492
  };
26059
26493
  }
26060
26494
  /**
@@ -26751,6 +27185,7 @@ import { dirname as dirname6, resolve as resolve7 } from "path";
26751
27185
  import { existsSync as existsSync9 } from "fs";
26752
27186
  import { readFile as readFile6 } from "fs/promises";
26753
27187
  var SCENARIO_VALIDATION = "scenario-validation";
27188
+ var SCENARIO_FILES = "scenario-files";
26754
27189
  function hasScenarioGate(config) {
26755
27190
  return (config.validators ?? []).some((v) => v.definition.gates?.includes("scenario"));
26756
27191
  }
@@ -26763,6 +27198,7 @@ async function runScenarioGates(options) {
26763
27198
  });
26764
27199
  const resolved = resolveSettingsLayers(config, options.scenarioSettings, null);
26765
27200
  const locale = options.locale ?? config.game?.definition.supportedLocales?.[0] ?? "en";
27201
+ const readsFiles = (config.requires ?? []).includes(SCENARIO_FILES);
26766
27202
  const problems = [];
26767
27203
  for (const validator of config.validators ?? []) {
26768
27204
  if (!validator.definition.gates?.includes("scenario")) continue;
@@ -26789,7 +27225,11 @@ async function runScenarioGates(options) {
26789
27225
  const found = await withBound(
26790
27226
  gate({
26791
27227
  settings: structuredClone(pick(resolved)),
26792
- locale
27228
+ locale,
27229
+ callbacks: readsFiles ? scenarioCallbacks(
27230
+ options.packagePath,
27231
+ options.files ?? { scenarioRoot: null, blobs: "none" }
27232
+ ) : withoutScenarioFiles(identifier)
26793
27233
  }),
26794
27234
  options.boundMs ?? DEFAULT_LOGIC_EXECUTION_BOUND_MS
26795
27235
  );
@@ -26812,6 +27252,40 @@ async function runScenarioGates(options) {
26812
27252
  }
26813
27253
  return problems;
26814
27254
  }
27255
+ function scenarioCallbacks(packagePath, files) {
27256
+ const unreadable = async (reference) => {
27257
+ if (!reference.startsWith("blob:") || files.blobs === "all") return false;
27258
+ if (files.blobs === "none") return true;
27259
+ const blob = await describeBlob(packagePath, reference.slice("blob:".length));
27260
+ return blob !== void 0 && blob.retention !== "scenario";
27261
+ };
27262
+ return {
27263
+ readAsset: async (reference) => {
27264
+ if (await unreadable(reference)) {
27265
+ throw new Error(`Cannot read "${reference}": the scenario cannot name that file`);
27266
+ }
27267
+ const described = await describeAssetByReference(
27268
+ packagePath,
27269
+ files.scenarioRoot,
27270
+ reference
27271
+ );
27272
+ if (described && described.size > SCENARIO_GATE_READ_LIMIT_BYTES) {
27273
+ throw new ScenarioAssetTooLargeError(reference, described.size);
27274
+ }
27275
+ const asset = await readAssetByReference(packagePath, files.scenarioRoot, reference);
27276
+ return { data: new Uint8Array(asset.data), mimeType: asset.mimeType, name: asset.name };
27277
+ },
27278
+ describeAsset: async (reference) => await unreadable(reference) ? void 0 : describeAssetByReference(packagePath, files.scenarioRoot, reference)
27279
+ };
27280
+ }
27281
+ function withoutScenarioFiles(identifier) {
27282
+ const refuse = (callback) => async () => {
27283
+ throw new Error(
27284
+ `Validator "${identifier}" called ${callback} in its Scenario gate, which needs the "${SCENARIO_FILES}" feature, but requires does not list it. Add "${SCENARIO_FILES}" to requires in seriousgaming.sdk.json.`
27285
+ );
27286
+ };
27287
+ return { readAsset: refuse("readAsset"), describeAsset: refuse("describeAsset") };
27288
+ }
26815
27289
  async function withBound(run, boundMs) {
26816
27290
  let timer;
26817
27291
  try {
@@ -27028,26 +27502,28 @@ function typesOf2(schema2) {
27028
27502
  return schema2.type ? [schema2.type] : [];
27029
27503
  }
27030
27504
  function propertyAt(path3, context) {
27031
- const [identifier, ...keys] = path3.split(".");
27032
- if (!identifier || keys.length === 0) {
27505
+ const parsed = parseSettingPath(path3);
27506
+ if (!parsed || parsed.keys.length === 0) {
27033
27507
  return {
27034
27508
  error: `"${path3}" should be a settings identifier and a property, e.g. engine.weeks`
27035
27509
  };
27036
27510
  }
27511
+ const { identifier, keys } = parsed;
27037
27512
  if (!context.declared.includes(identifier)) {
27038
27513
  return {
27039
27514
  error: `"${path3}" reads settings "${identifier}", which the guide does not list in its settings`
27040
27515
  };
27041
27516
  }
27042
- let schema2 = context.schemas[identifier];
27517
+ const root2 = context.schemas[identifier];
27518
+ let schema2 = root2;
27043
27519
  for (const key of keys) {
27044
- const properties = typeof schema2 === "object" ? schema2.properties : void 0;
27520
+ const properties = typeof schema2 === "object" && root2 ? dereference(root2, schema2).properties : void 0;
27045
27521
  schema2 = properties?.[key];
27046
- if (typeof schema2 !== "object") {
27522
+ if (typeof schema2 !== "object" || !root2) {
27047
27523
  return { error: `"${path3}" names no property of settings "${identifier}"` };
27048
27524
  }
27049
27525
  }
27050
- return { schema: schema2 };
27526
+ return { schema: root2 ? dereference(root2, schema2) : schema2 };
27051
27527
  }
27052
27528
  function literalError(path3, literal, schema2) {
27053
27529
  const types = typesOf2(schema2);
@@ -27113,7 +27589,8 @@ function validateGuideSettings(chapters, context) {
27113
27589
  );
27114
27590
  continue;
27115
27591
  }
27116
- used.add(reference.path.split(".")[0]);
27592
+ const identifier = parseSettingPath(reference.path)?.identifier;
27593
+ if (identifier !== void 0) used.add(identifier);
27117
27594
  const property = propertyAt(reference.path, context);
27118
27595
  if ("error" in property) {
27119
27596
  errors.push(`${where3}: ${directive2} ${property.error}`);
@@ -27846,8 +28323,8 @@ function endpointSchemaErrors(endpoint) {
27846
28323
  `Endpoint "${identifier}" requestSchema ${path3 || "(root)"} declares \`blob\` but is not \`"type": "string"\`. A file field is a URI string: a blob: reference or a data: URI`
27847
28324
  );
27848
28325
  }
27849
- for (const [key, child] of Object.entries(node2.properties ?? {})) {
27850
- visit2(child, `${path3}/${key}`);
28326
+ for (const { step, schema: child } of memberDeclarations(node2)) {
28327
+ visit2(child, `${path3}/${step}`);
27851
28328
  }
27852
28329
  if (node2.items && !Array.isArray(node2.items)) visit2(node2.items, `${path3}/items`);
27853
28330
  };
@@ -27955,7 +28432,7 @@ function validateCapabilityScopes(game, engines, config) {
27955
28432
  }
27956
28433
  if (!isSharedState) {
27957
28434
  const referenced = /* @__PURE__ */ new Map();
27958
- const collect2 = (label4, definition3) => {
28435
+ const collect = (label4, definition3) => {
27959
28436
  for (const capabilityId of [
27960
28437
  ...definition3.reads ?? [],
27961
28438
  ...definition3.writes ?? []
@@ -27966,10 +28443,10 @@ function validateCapabilityScopes(game, engines, config) {
27966
28443
  }
27967
28444
  };
27968
28445
  for (const engine of engines) {
27969
- collect2("engine", engine.definition);
28446
+ collect("engine", engine.definition);
27970
28447
  }
27971
28448
  if (config.ui) {
27972
- collect2("user interface", config.ui.definition);
28449
+ collect("user interface", config.ui.definition);
27973
28450
  }
27974
28451
  for (const [capId, referencedBy] of referenced) {
27975
28452
  errors.push(
@@ -28357,16 +28834,16 @@ function validateSchemaDefaults(label4, definition3) {
28357
28834
  function descriptor(entry) {
28358
28835
  return entry;
28359
28836
  }
28360
- var named = (resource) => resource.definition.identifier;
28837
+ var named2 = (resource) => resource.definition.identifier;
28361
28838
  var writesOf = (resource) => resource.definition.writes ?? [];
28362
28839
  function slot(resource) {
28363
28840
  return resource ? [resource] : [];
28364
28841
  }
28365
28842
  function packageFiles(packagePath, scenarioRoot) {
28366
28843
  return async (reference) => {
28844
+ if (!reference.startsWith("shared:") && !reference.startsWith("asset:")) return void 0;
28367
28845
  try {
28368
- const asset = reference.startsWith("shared:") ? await resolveSharedAsset(packagePath, reference.slice("shared:".length)) : reference.startsWith("asset:") && scenarioRoot !== null ? await resolveAsset(scenarioRoot, reference.slice("asset:".length)) : void 0;
28369
- return asset && { mimeType: asset.mimeType, size: asset.data.length };
28846
+ return await describeAssetByReference(packagePath, scenarioRoot, reference);
28370
28847
  } catch {
28371
28848
  return void 0;
28372
28849
  }
@@ -28381,6 +28858,19 @@ function schemaDefaults2(type) {
28381
28858
  )
28382
28859
  });
28383
28860
  }
28861
+ function localRefs(type) {
28862
+ const label4 = getResourceMeta(type).label;
28863
+ const keyword = type === "capability" ? "variablesSchema" : "settingsSchema";
28864
+ return (resource) => {
28865
+ const schema2 = resource.definition[keyword];
28866
+ if (schema2 === null || typeof schema2 !== "object") return { errors: [] };
28867
+ return {
28868
+ errors: refProblems(schema2).map(
28869
+ (problem) => refProblemMessage(`${label4} "${resource.definition.identifier}"`, keyword, problem)
28870
+ )
28871
+ };
28872
+ };
28873
+ }
28384
28874
  function readsWritten(type) {
28385
28875
  const label4 = getResourceMeta(type).label;
28386
28876
  return (resource, context) => {
@@ -28431,12 +28921,13 @@ var VALIDATION_DESCRIPTORS = [
28431
28921
  descriptor({
28432
28922
  type: "capability",
28433
28923
  resources: (config) => config.capabilities ?? [],
28434
- identify: named,
28924
+ identify: named2,
28435
28925
  checks: [
28436
28926
  (capability, context) => ({
28437
28927
  errors: validateTsTypes([capability], context.workingDir)
28438
28928
  }),
28439
- schemaDefaults2("capability")
28929
+ schemaDefaults2("capability"),
28930
+ localRefs("capability")
28440
28931
  ]
28441
28932
  }),
28442
28933
  // The built-in `game` resource's defaults are the manifest's own values,
@@ -28446,12 +28937,19 @@ var VALIDATION_DESCRIPTORS = [
28446
28937
  resources: (config) => (config.settings ?? []).filter(
28447
28938
  (settings) => settings.definition.identifier !== GAME_SETTINGS
28448
28939
  ),
28449
- identify: named,
28940
+ identify: named2,
28450
28941
  checks: [
28451
28942
  schemaDefaults2("settings"),
28452
- // What a file setting expects, and the files its defaults name (§6.1a).
28943
+ localRefs("settings"),
28944
+ // A lock inside a list's items or a map's entries keeps nothing (§6.1a).
28453
28945
  (settings) => ({
28454
- errors: fileSettingDeclarationErrors(
28946
+ errors: unenforceableLocks(settings.definition.settingsSchema).map(
28947
+ (lock) => unenforceableLockMessage(settings.definition.identifier, lock)
28948
+ )
28949
+ }),
28950
+ // What a file setting expects, and the files its defaults name (§6.1a).
28951
+ (settings) => ({
28952
+ errors: fileSettingDeclarationErrors(
28455
28953
  settings.definition.identifier,
28456
28954
  settings.definition.settingsSchema
28457
28955
  )
@@ -28479,7 +28977,7 @@ var VALIDATION_DESCRIPTORS = [
28479
28977
  descriptor({
28480
28978
  type: "engine",
28481
28979
  resources: (config) => slot(config.engine),
28482
- identify: named,
28980
+ identify: named2,
28483
28981
  writer: writesOf,
28484
28982
  checks: [
28485
28983
  (engine, context) => validateEngine(engine, context.config),
@@ -28491,7 +28989,7 @@ var VALIDATION_DESCRIPTORS = [
28491
28989
  descriptor({
28492
28990
  type: "ui",
28493
28991
  resources: (config) => slot(config.ui),
28494
- identify: named,
28992
+ identify: named2,
28495
28993
  writer: writesOf,
28496
28994
  checks: [userInterfaceReferences, uiFiles, schemaDefaults2("ui"), readsWritten("ui")]
28497
28995
  }),
@@ -28499,19 +28997,19 @@ var VALIDATION_DESCRIPTORS = [
28499
28997
  descriptor({
28500
28998
  type: "setup",
28501
28999
  resources: (config) => slot(config.setup),
28502
- identify: named,
29000
+ identify: named2,
28503
29001
  checks: [uiFiles]
28504
29002
  }),
28505
29003
  descriptor({
28506
29004
  type: "scenario_editor",
28507
29005
  resources: (config) => slot(config.scenario_editor),
28508
- identify: named,
29006
+ identify: named2,
28509
29007
  checks: [uiFiles]
28510
29008
  }),
28511
29009
  descriptor({
28512
29010
  type: "tick_controller",
28513
29011
  resources: (config) => slot(config.tick_controller),
28514
- identify: named,
29012
+ identify: named2,
28515
29013
  checks: [
28516
29014
  (tc, context) => validateTickController(tc, context.config),
28517
29015
  schemaDefaults2("tick_controller"),
@@ -28521,7 +29019,7 @@ var VALIDATION_DESCRIPTORS = [
28521
29019
  descriptor({
28522
29020
  type: "hook",
28523
29021
  resources: (config) => config.hooks ?? [],
28524
- identify: named,
29022
+ identify: named2,
28525
29023
  writer: writesOf,
28526
29024
  checks: [
28527
29025
  (hook, context) => validateHook(hook, context.config),
@@ -28532,7 +29030,7 @@ var VALIDATION_DESCRIPTORS = [
28532
29030
  descriptor({
28533
29031
  type: "validator",
28534
29032
  resources: (config) => config.validators ?? [],
28535
- identify: named,
29033
+ identify: named2,
28536
29034
  checks: [
28537
29035
  (validator, context) => validateValidator(validator, context.config),
28538
29036
  schemaDefaults2("validator"),
@@ -28542,7 +29040,7 @@ var VALIDATION_DESCRIPTORS = [
28542
29040
  descriptor({
28543
29041
  type: "endpoint",
28544
29042
  resources: (config) => config.endpoints ?? [],
28545
- identify: named,
29043
+ identify: named2,
28546
29044
  checks: [
28547
29045
  (endpoint, context) => validateEndpoint(endpoint, context.config),
28548
29046
  (endpoint, context) => validateEndpointFiles(endpoint, context.workingDir),
@@ -28553,7 +29051,7 @@ var VALIDATION_DESCRIPTORS = [
28553
29051
  descriptor({
28554
29052
  type: "session",
28555
29053
  resources: (config) => slot(config.session),
28556
- identify: named,
29054
+ identify: named2,
28557
29055
  writer: writesOf,
28558
29056
  checks: [
28559
29057
  userInterfaceReferences,
@@ -28565,7 +29063,7 @@ var VALIDATION_DESCRIPTORS = [
28565
29063
  descriptor({
28566
29064
  type: "waiting_room",
28567
29065
  resources: (config) => slot(config.waiting_room),
28568
- identify: named,
29066
+ identify: named2,
28569
29067
  checks: [
28570
29068
  userInterfaceReferences,
28571
29069
  uiFiles,
@@ -28576,7 +29074,7 @@ var VALIDATION_DESCRIPTORS = [
28576
29074
  descriptor({
28577
29075
  type: "presentation",
28578
29076
  resources: (config) => slot(config.presentation),
28579
- identify: named,
29077
+ identify: named2,
28580
29078
  checks: [userInterfaceReferences, uiFiles]
28581
29079
  }),
28582
29080
  // Composition, settings, locales and roles. A game wires whatever its
@@ -28585,7 +29083,7 @@ var VALIDATION_DESCRIPTORS = [
28585
29083
  descriptor({
28586
29084
  type: "game",
28587
29085
  resources: (config) => slot(config.game),
28588
- identify: named,
29086
+ identify: named2,
28589
29087
  checks: [
28590
29088
  (game, context) => validateGame(game, context.config),
28591
29089
  // With no default, a session can run on no scenario at all, so the
@@ -28642,7 +29140,7 @@ var VALIDATION_DESCRIPTORS = [
28642
29140
  descriptor({
28643
29141
  type: "scenario",
28644
29142
  resources: (config) => config.scenarios ?? [],
28645
- identify: named,
29143
+ identify: named2,
28646
29144
  checks: [
28647
29145
  // The same check `ConfigResolver.assertLayeredSettingsValid` runs at
28648
29146
  // session start (#371). Without it the build was green on a
@@ -28687,11 +29185,17 @@ var VALIDATION_DESCRIPTORS = [
28687
29185
  // (§15.8).
28688
29186
  async (scenario, context) => {
28689
29187
  const identifier = scenario.definition.identifier;
29188
+ const packagePath = dirname6(context.configPath);
28690
29189
  return scenarioRefusals(
28691
29190
  await runScenarioGates({
28692
- packagePath: dirname6(context.configPath),
29191
+ packagePath,
28693
29192
  config: context.config,
28694
29193
  loader: context.logicLoader,
29194
+ // Its files as the package ships them (§15.8).
29195
+ files: {
29196
+ scenarioRoot: resolve7(packagePath, scenario.rootDirectory),
29197
+ blobs: "none"
29198
+ },
28695
29199
  scenarioSettings: scenario.definition.settings ?? {}
28696
29200
  }),
28697
29201
  `Scenario "${identifier}"`,
@@ -28706,7 +29210,7 @@ var VALIDATION_DESCRIPTORS = [
28706
29210
  descriptor({
28707
29211
  type: "guide",
28708
29212
  resources: (config) => slot(config.guide),
28709
- identify: named,
29213
+ identify: named2,
28710
29214
  checks: [
28711
29215
  (guide, context) => validateFacilitatorGuideContent({
28712
29216
  definition: guide.definition,
@@ -28744,7 +29248,7 @@ async function validateLoadedPackage(config, options) {
28744
29248
  configPath: options.configPath,
28745
29249
  workingDir: options.workingDir,
28746
29250
  writtenInPackage,
28747
- capabilityIds: new Set((config.capabilities ?? []).map(named)),
29251
+ capabilityIds: new Set((config.capabilities ?? []).map(named2)),
28748
29252
  logicLoader: new LogicLoader(dirname6(options.configPath), {
28749
29253
  transpile: Transpile,
28750
29254
  fs: { existsSync: existsSync13, readFile: readFile7 }
@@ -29576,7 +30080,14 @@ async function saveSessionScenario(session, packagePath, request) {
29576
30080
  packagePath,
29577
30081
  config,
29578
30082
  scenarioSettings: settings,
29579
- locale: projection.session.locale
30083
+ locale: projection.session.locale,
30084
+ // Its files as a session on it would find them: a draft's in the
30085
+ // scenario it was opened on and the blobs it can read, the
30086
+ // session's in its scenario and every blob it holds (§6.12, §15.8).
30087
+ files: {
30088
+ scenarioRoot: source?.rootDirectory ?? null,
30089
+ blobs: request.draft === true ? "draft" : "all"
30090
+ }
29580
30091
  });
29581
30092
  if (problems.length > 0) {
29582
30093
  throw new SaveScenarioError("denied", describeScenarioProblems(problems).join("\n"));
@@ -29666,98 +30177,418 @@ function mountableSurfaces(config) {
29666
30177
  ].filter((surface) => surface !== null);
29667
30178
  }
29668
30179
 
29669
- // cli/dev/routes.ts
29670
- function runOf(req) {
29671
- return req.query.run === "walkthrough" ? "walkthrough" : "session";
30180
+ // cli/dev/view/batch.ts
30181
+ function projectContext2(context, surface) {
30182
+ const declared = /* @__PURE__ */ new Set([...surface.reads, ...surface.writes]);
30183
+ const projected = {};
30184
+ for (const [capability, values] of Object.entries(context)) {
30185
+ if (declared.has(capability)) projected[capability] = values;
30186
+ }
30187
+ return projected;
29672
30188
  }
29673
- function registerRoutes(app, deps) {
29674
- const { session, packagePath, runFor } = deps;
29675
- app.get("/api/state", async (req, res) => {
29676
- res.json((await runFor(runOf(req))).project());
29677
- });
29678
- app.get("/api/surfaces", (req, res) => {
29679
- const origin = deps.assetOrigin(req.headers.host);
29680
- res.json(
29681
- mountableSurfaces(session.packageConfiguration()).map((mountable) => ({
29682
- ...mountable,
29683
- origin
29684
- }))
29685
- );
29686
- });
29687
- app.get("/api/session", async (req, res) => {
29688
- const run = await runFor(runOf(req));
29689
- res.json({
29690
- instanceId: deps.instanceId,
29691
- inSetup: run.inSetup,
29692
- diagnostics: run.diagnostics(),
29693
- sessionOverrides: run.sessionOverrides(),
29694
- pending: run.pendingChanges(),
29695
- warnings: deps.notices(run)
29696
- });
29697
- });
29698
- app.post("/api/command", express.json({ limit: "20mb" }), async (req, res) => {
29699
- const invalid2 = commandError(req.body);
29700
- if (invalid2) {
29701
- res.status(400).json({ error: invalid2 });
29702
- return;
29703
- }
29704
- const command = req.body;
29705
- try {
29706
- if (rebuildsWalkthrough(command, runOf(req))) {
29707
- res.json(await deps.settleWalkthroughReset(command));
29708
- return;
29709
- }
29710
- const run = await runFor(runOf(req));
29711
- const result = isQuery(command) ? await run.query(command) : await run.submit(command);
29712
- if (command.type === "callEndpoint" && command.external && "type" in result && result.type === "endpoint") {
29713
- const blobs = blobLinks(
29714
- result.response,
29715
- (blobId) => `${req.protocol}://${req.get("host")}/api/blobs/${encodeURIComponent(blobId)}`
29716
- );
29717
- res.json(Object.keys(blobs).length > 0 ? { ...result, blobs } : result);
29718
- return;
29719
- }
29720
- res.json(result);
29721
- } catch (error) {
29722
- res.status(500).json({ error: errorMessage(error, "Command failed") });
29723
- }
29724
- });
29725
- app.post("/api/walkthrough/reset", async (_req, res) => {
29726
- try {
29727
- res.json((await deps.resetWalkthrough()).project());
29728
- } catch (error) {
29729
- res.status(500).json({ error: errorMessage(error, "Walkthrough reset failed") });
29730
- }
29731
- });
29732
- app.get("/api/scenarios", (_req, res) => {
29733
- const config = session.packageConfiguration();
29734
- res.json({
29735
- activeScenarioId: session.activeScenario()?.definition.identifier ?? null,
29736
- scenarios: (config?.scenarios ?? []).map((scenario) => ({
29737
- id: scenario.definition.identifier,
29738
- default: scenario.definition.default === true,
29739
- locales: scenario.definition.locales ?? {}
29740
- }))
30189
+ function settingsFor(state2, surface, { withoutSession = false } = {}) {
30190
+ const settings = withoutSession ? state2.settingsWithoutSession : state2.settings;
30191
+ return Object.fromEntries(
30192
+ surface.settings.filter((identifier) => identifier in settings).map((identifier) => [identifier, settings[identifier]])
30193
+ );
30194
+ }
30195
+ function draftSettingsFor(state2, surface, viewer) {
30196
+ const scenarioId = viewer.scenario ?? null;
30197
+ const draft = state2.scenarioDrafts?.find((entry) => entry.scenarioId === scenarioId);
30198
+ const settings = draft?.settings ?? {};
30199
+ return Object.fromEntries(
30200
+ surface.settings.filter((identifier) => identifier in settings).map((identifier) => [identifier, settings[identifier]])
30201
+ );
30202
+ }
30203
+ function sessionKeyFor(state2, surface, { sessionless = false } = {}) {
30204
+ const outside = surface.kind === "scenario-editor" || surface.kind === "presentation" && sessionless;
30205
+ return outside ? `outside-session:${state2.game.identifier}` : state2.session.sessionKey;
30206
+ }
30207
+ function themeMessages(theme) {
30208
+ return [
30209
+ { type: "setTheme", payload: theme.palette },
30210
+ { type: "themePreferenceChanged", preference: theme.preference }
30211
+ ];
30212
+ }
30213
+ function assetUrls(assetOrigin, editing) {
30214
+ const scenarioAssets = editing === void 0 ? "scenario/" : editing.scenario === null ? "no-scenario/" : `scenarios/${encodeURIComponent(editing.scenario)}/`;
30215
+ return {
30216
+ blobPrefix: `${assetOrigin}/assets/blobs/`,
30217
+ scenarioAssetPrefix: `${assetOrigin}/assets/${scenarioAssets}`,
30218
+ sharedAssetPrefix: `${assetOrigin}/assets/shared/`,
30219
+ assetAuthRedeemUrl: `${assetOrigin}/assets/auth/redeem`
30220
+ };
30221
+ }
30222
+ function teamOf(state2, teamIndex) {
30223
+ if (teamIndex === void 0) return state2.teams[0];
30224
+ return state2.teams.find((team) => team.index === teamIndex);
30225
+ }
30226
+ function teamList(state2) {
30227
+ return [...state2.teams].sort((a, b) => a.index - b.index).map((team) => ({ teamId: team.teamId, index: team.index, name: team.name }));
30228
+ }
30229
+ var IDLE_TIMER2 = {
30230
+ enabled: false,
30231
+ paused: false,
30232
+ nextTickAt: null,
30233
+ intervalMs: null,
30234
+ pausedAt: null,
30235
+ pausedMs: 0,
30236
+ extendedMs: 0,
30237
+ scheduleStartedAt: null
30238
+ };
30239
+ function buildBatch(options) {
30240
+ const { surface, state: state2, theme, origin, assetOrigin } = options;
30241
+ const common = [
30242
+ { type: "setLocale", payload: { locale: state2.session.locale } },
30243
+ {
30244
+ type: "setAssetUrls",
30245
+ payload: assetUrls(
30246
+ assetOrigin ?? origin,
30247
+ surface.kind === "scenario-editor" ? { scenario: options.viewer.scenario ?? null } : void 0
30248
+ )
30249
+ },
30250
+ ...theme ? themeMessages(theme) : []
30251
+ ];
30252
+ switch (surface.kind) {
30253
+ case "game":
30254
+ case "waiting-room":
30255
+ return [...playerBatch(options), ...common];
30256
+ case "session":
30257
+ return [...sessionBatch(options), ...common];
30258
+ // The two settings editors are sent the same batch (§12.3): neither is
30259
+ // told which slot it fills, since each is its own bundle.
30260
+ case "setup":
30261
+ return [{ type: "setSettings", payload: settingsFor(state2, surface) }, ...common];
30262
+ case "scenario-editor":
30263
+ return [
30264
+ { type: "setSettings", payload: draftSettingsFor(state2, surface, options.viewer) },
30265
+ ...common
30266
+ ];
30267
+ case "presentation":
30268
+ return [...presentationBatch(options), ...common];
30269
+ }
30270
+ return common;
30271
+ }
30272
+ function crossTeamData(state2, surface, ownTeamIndex) {
30273
+ const across = new Set(surface.crossTeamReads);
30274
+ return [...state2.teams].sort((a, b) => a.index - b.index).map((team) => ({
30275
+ teamId: team.teamId,
30276
+ index: team.index,
30277
+ name: team.name,
30278
+ context: team.index === ownTeamIndex ? projectContext2(team.context, surface) : Object.fromEntries(
30279
+ Object.entries(team.context).filter(
30280
+ ([capability]) => across.has(capability)
30281
+ )
30282
+ )
30283
+ }));
30284
+ }
30285
+ function joinUrl(origin, teamIndex) {
30286
+ return `${origin}/team/${teamIndex + 1}/join?bare`;
30287
+ }
30288
+ function playerBatch({
30289
+ surface,
30290
+ state: state2,
30291
+ viewer,
30292
+ origin,
30293
+ roundProcessing
30294
+ }) {
30295
+ const team = teamOf(state2, viewer.teamIndex);
30296
+ const participant = viewer.observer ? void 0 : team?.participants.find((p) => p.id === viewer.participantId) ?? team?.participants[0];
30297
+ const messages2 = [
30298
+ {
30299
+ type: "stateChanged",
30300
+ payload: projectContext2(team?.context ?? {}, surface),
30301
+ // §12.5: the head tick, so a review scrubber can be bounded and a
30302
+ // cache invalidated on undo.
30303
+ completedTicks: team?.completedTicks ?? state2.session.completedTicks
30304
+ },
30305
+ { type: "setSettings", payload: settingsFor(state2, surface) }
30306
+ ];
30307
+ if (participant) {
30308
+ messages2.push({
30309
+ type: "setParticipant",
30310
+ payload: {
30311
+ id: participant.id,
30312
+ name: participant.name,
30313
+ index: participant.index,
30314
+ teamId: team?.teamId ?? "team-1"
30315
+ },
30316
+ // There are no accounts here, so every name is the participant's
30317
+ // own to change (§12.5).
30318
+ canRenameSelf: true
29741
30319
  });
29742
- });
29743
- app.get("/api/brands", (req, res) => {
29744
- const assetOrigin = deps.assetOrigin(req.headers.host);
29745
- res.json({ brands: deps.brands().map((brand) => summarise(brand, assetOrigin)) });
29746
- });
29747
- app.get("/api/locales", (_req, res) => {
29748
- const game = session.packageConfiguration()?.game;
29749
- res.json({
29750
- active: session.project().session.locale,
29751
- supported: game?.definition.supportedLocales ?? ["en"],
29752
- names: game?.definition.locales ?? {}
30320
+ }
30321
+ messages2.push(
30322
+ { type: "setViewerRole", role: viewer.observer ? "observer" : "participant" },
30323
+ { type: "setRunKind", runKind: state2.session.runKind },
30324
+ { type: "setScenarioName", scenarioName: state2.game.scenarioName },
30325
+ {
30326
+ type: "setOwnTeam",
30327
+ payload: team ? { teamId: team.teamId, index: team.index, name: team.name } : { teamId: "team-1", index: 0, name: "Team 1" }
30328
+ },
30329
+ {
30330
+ type: "setOwnTeamJoinLink",
30331
+ payload: team ? { joinUrl: joinUrl(origin, team.index) } : (
30332
+ // §12.3, as amended: a host with nothing to offer says so
30333
+ // rather than staying silent, so a surface rendering a join
30334
+ // panel shows nothing instead of waiting for a message that
30335
+ // never comes.
30336
+ null
30337
+ )
30338
+ },
30339
+ { type: "setParticipantList", participants: team?.participants ?? [] },
30340
+ { type: "setTeamList", payload: teamList(state2) },
30341
+ { type: "setTimer", payload: team?.timer ?? IDLE_TIMER2 }
30342
+ );
30343
+ if (surface.kind === "game") {
30344
+ messages2.push({ type: "setRoundProcessing", processing: roundProcessing === true });
30345
+ }
30346
+ if ((surface.kind === "game" || surface.kind === "waiting-room") && surface.crossTeamReads.length > 0 && state2.session.mode === "shared-state") {
30347
+ messages2.push({
30348
+ type: "setCrossTeamData",
30349
+ payload: crossTeamData(state2, surface, team?.index)
29753
30350
  });
29754
- });
29755
- app.post("/api/scenarios", express.json(), async (req, res) => {
29756
- const body = req.body;
29757
- if (typeof body?.identifier !== "string") {
29758
- res.status(400).json({ error: "An identifier is required" });
29759
- return;
29760
- }
30351
+ }
30352
+ return messages2;
30353
+ }
30354
+ function sessionBatch({
30355
+ surface,
30356
+ state: state2,
30357
+ gameName,
30358
+ origin,
30359
+ overlays
30360
+ }) {
30361
+ return [
30362
+ {
30363
+ type: "setSessionMeta",
30364
+ payload: {
30365
+ sessionId: "dev-session",
30366
+ name: gameName,
30367
+ readOnly: false,
30368
+ waitingRoomOpen: state2.session.waitingRoomOpen,
30369
+ joinPin: null,
30370
+ canSetLocale: true
30371
+ }
30372
+ },
30373
+ { type: "setSessionData", payload: sessionData(state2, surface) },
30374
+ { type: "setSettings", payload: settingsFor(state2, surface) },
30375
+ { type: "setTeamConfiguration", payload: teamConfiguration(state2) },
30376
+ { type: "setTeamList", payload: teamList(state2) },
30377
+ {
30378
+ type: "setParticipantList",
30379
+ participants: participantList(state2)
30380
+ },
30381
+ { type: "setTeamLinks", payload: teamLinks(state2, origin) },
30382
+ { type: "setWalkthroughLink", payload: walkthroughLink(origin) },
30383
+ { type: "setRunKind", runKind: state2.session.runKind },
30384
+ { type: "setScenarioName", scenarioName: state2.game.scenarioName },
30385
+ { type: "setAvailableOverlays", overlays: overlays ?? availableOverlays() }
30386
+ ];
30387
+ }
30388
+ function presentationBatch({
30389
+ surface,
30390
+ state: state2,
30391
+ gameName,
30392
+ origin,
30393
+ sessionless
30394
+ }) {
30395
+ return [
30396
+ {
30397
+ type: "setPresentation",
30398
+ payload: {
30399
+ game: {
30400
+ name: state2.game.name,
30401
+ // Without a session, as the scenario resolves it alone (§6.15.1).
30402
+ maxTicks: sessionless ? gameSettingsOf(state2.settingsWithoutSession).maxTicks : state2.session.maxTicks,
30403
+ mode: state2.session.mode,
30404
+ scenarioName: state2.game.scenarioName
30405
+ },
30406
+ session: sessionless ? null : {
30407
+ // The dev server runs one session; its id is the
30408
+ // one the session surface is told (above).
30409
+ id: "dev-session",
30410
+ name: gameName,
30411
+ completedTicks: Math.max(
30412
+ state2.session.completedTicks,
30413
+ ...state2.teams.map((team) => team.completedTicks)
30414
+ ),
30415
+ data: sessionData(state2, surface),
30416
+ teams: teamList(state2),
30417
+ participants: participantList(state2),
30418
+ // A deck puts these on the projector, so no observe
30419
+ // URL: watching a team is the facilitator's tool.
30420
+ joinLinks: teamLinks(state2, origin).map(({ teamId, joinUrl: joinUrl2 }) => ({
30421
+ teamId,
30422
+ joinUrl: joinUrl2
30423
+ })),
30424
+ joinPin: null
30425
+ }
30426
+ }
30427
+ },
30428
+ {
30429
+ type: "setSettings",
30430
+ payload: settingsFor(state2, surface, { withoutSession: sessionless })
30431
+ }
30432
+ ];
30433
+ }
30434
+ function walkthroughLink(origin) {
30435
+ return { url: `${origin}/walkthrough` };
30436
+ }
30437
+ function availableOverlays(offered = {}) {
30438
+ return [
30439
+ ...offered.guide ? ["facilitator-guide"] : [],
30440
+ "print-sheets",
30441
+ ...offered.presentation ? ["presentation"] : []
30442
+ ];
30443
+ }
30444
+ function offersPresentationOverlay(config) {
30445
+ return config?.presentation !== void 0 && (config.requires ?? []).includes(PRESENTATION_OVERLAY);
30446
+ }
30447
+ var PRESENTATION_OVERLAY = "presentation-overlay";
30448
+ function participantList(state2) {
30449
+ return state2.teams.flatMap(
30450
+ (team) => team.participants.map((participant) => ({
30451
+ id: participant.id,
30452
+ name: participant.name,
30453
+ index: participant.index,
30454
+ connected: participant.connected,
30455
+ teamId: team.teamId
30456
+ }))
30457
+ );
30458
+ }
30459
+ function teamLinks(state2, origin) {
30460
+ return [...state2.teams].sort((a, b) => a.index - b.index).map((team) => ({
30461
+ teamId: team.teamId,
30462
+ joinUrl: joinUrl(origin, team.index),
30463
+ observeUrl: `${origin}/team/${team.index + 1}/observe`
30464
+ }));
30465
+ }
30466
+ function teamConfiguration(state2) {
30467
+ return {
30468
+ mode: state2.session.mode,
30469
+ ...state2.session.teamBounds.min === void 0 ? {} : { min: state2.session.teamBounds.min },
30470
+ max: state2.session.teamBounds.max
30471
+ };
30472
+ }
30473
+ function sessionData(state2, surface) {
30474
+ const teams = {};
30475
+ for (const team of state2.teams) {
30476
+ const own5 = {};
30477
+ for (const [capability, values] of Object.entries(team.context)) {
30478
+ if (!(capability in state2.shared)) own5[capability] = values;
30479
+ }
30480
+ teams[team.teamId] = {
30481
+ context: projectContext2(own5, surface),
30482
+ completedTicks: team.completedTicks,
30483
+ timer: team.timer ?? IDLE_TIMER2,
30484
+ // Monotonic per delivery. One session, one host, so the tick is a
30485
+ // sufficient clock; the wrapper only compares it with itself.
30486
+ revision: team.completedTicks
30487
+ };
30488
+ }
30489
+ return {
30490
+ // The dev server only ever sends snapshots, so the revision is a
30491
+ // baseline the wrapper never compares a delta against.
30492
+ shared: {
30493
+ context: projectContext2(state2.shared, surface),
30494
+ revision: state2.session.completedTicks
30495
+ },
30496
+ teams
30497
+ };
30498
+ }
30499
+
30500
+ // cli/dev/routes.ts
30501
+ function runOf(req) {
30502
+ return req.query.run === "walkthrough" ? "walkthrough" : "session";
30503
+ }
30504
+ function registerRoutes(app, deps) {
30505
+ const { session, packagePath, runFor } = deps;
30506
+ app.get("/api/state", async (req, res) => {
30507
+ res.json((await runFor(runOf(req))).project());
30508
+ });
30509
+ app.get("/api/surfaces", (req, res) => {
30510
+ const origin = deps.assetOrigin(req.headers.host);
30511
+ res.json(
30512
+ mountableSurfaces(session.packageConfiguration()).map((mountable) => ({
30513
+ ...mountable,
30514
+ origin
30515
+ }))
30516
+ );
30517
+ });
30518
+ app.get("/api/session", async (req, res) => {
30519
+ const run = await runFor(runOf(req));
30520
+ res.json({
30521
+ instanceId: deps.instanceId,
30522
+ inSetup: run.inSetup,
30523
+ diagnostics: run.diagnostics(),
30524
+ sessionOverrides: run.sessionOverrides(),
30525
+ pending: run.pendingChanges(),
30526
+ warnings: deps.notices(run)
30527
+ });
30528
+ });
30529
+ app.post("/api/command", express.json({ limit: "20mb" }), async (req, res) => {
30530
+ const invalid2 = commandError(req.body);
30531
+ if (invalid2) {
30532
+ res.status(400).json({ error: invalid2 });
30533
+ return;
30534
+ }
30535
+ const command = req.body;
30536
+ try {
30537
+ if (rebuildsWalkthrough(command, runOf(req))) {
30538
+ res.json(await deps.settleWalkthroughReset(command));
30539
+ return;
30540
+ }
30541
+ const run = await runFor(runOf(req));
30542
+ const result = isQuery(command) ? await run.query(command) : await run.submit(command);
30543
+ if (command.type === "callEndpoint" && command.external && "type" in result && result.type === "endpoint") {
30544
+ const blobs = blobLinks(
30545
+ result.response,
30546
+ (blobId) => `${req.protocol}://${req.get("host")}/api/blobs/${encodeURIComponent(blobId)}`
30547
+ );
30548
+ res.json(Object.keys(blobs).length > 0 ? { ...result, blobs } : result);
30549
+ return;
30550
+ }
30551
+ res.json(result);
30552
+ } catch (error) {
30553
+ res.status(500).json({ error: errorMessage(error, "Command failed") });
30554
+ }
30555
+ });
30556
+ app.post("/api/walkthrough/reset", async (_req, res) => {
30557
+ try {
30558
+ res.json((await deps.resetWalkthrough()).project());
30559
+ } catch (error) {
30560
+ res.status(500).json({ error: errorMessage(error, "Walkthrough reset failed") });
30561
+ }
30562
+ });
30563
+ app.get("/api/scenarios", (_req, res) => {
30564
+ const config = session.packageConfiguration();
30565
+ res.json({
30566
+ activeScenarioId: session.activeScenario()?.definition.identifier ?? null,
30567
+ scenarios: (config?.scenarios ?? []).map((scenario) => ({
30568
+ id: scenario.definition.identifier,
30569
+ default: scenario.definition.default === true,
30570
+ locales: scenario.definition.locales ?? {}
30571
+ }))
30572
+ });
30573
+ });
30574
+ app.get("/api/brands", (req, res) => {
30575
+ const assetOrigin = deps.assetOrigin(req.headers.host);
30576
+ res.json({ brands: deps.brands().map((brand) => summarise(brand, assetOrigin)) });
30577
+ });
30578
+ app.get("/api/locales", (_req, res) => {
30579
+ const game = session.packageConfiguration()?.game;
30580
+ res.json({
30581
+ active: session.project().session.locale,
30582
+ supported: game?.definition.supportedLocales ?? ["en"],
30583
+ names: game?.definition.locales ?? {}
30584
+ });
30585
+ });
30586
+ app.post("/api/scenarios", express.json(), async (req, res) => {
30587
+ const body = req.body;
30588
+ if (typeof body?.identifier !== "string") {
30589
+ res.status(400).json({ error: "An identifier is required" });
30590
+ return;
30591
+ }
29761
30592
  try {
29762
30593
  const result = await saveSessionScenario(session, packagePath, {
29763
30594
  identifier: body.identifier,
@@ -29829,6 +30660,14 @@ function registerRoutes(app, deps) {
29829
30660
  app.get("/api/guide", (_req, res) => {
29830
30661
  res.json({ guide: session.effectiveGuide() });
29831
30662
  });
30663
+ app.get("/api/overlays", (_req, res) => {
30664
+ res.json({
30665
+ overlays: availableOverlays({
30666
+ guide: session.effectiveGuide() !== null,
30667
+ presentation: offersPresentationOverlay(session.packageConfiguration())
30668
+ })
30669
+ });
30670
+ });
29832
30671
  app.get("/api/guide/content/:locale/:chapter", async (req, res) => {
29833
30672
  const guide = session.guide();
29834
30673
  if (!guide) {
@@ -29866,12 +30705,16 @@ var ASSET_PATHS = {
29866
30705
  "/api": {
29867
30706
  blob: "/api/blobs/:blobId",
29868
30707
  scenario: "/api/scenario/assets/*path",
30708
+ editedScenario: "/api/scenarios/:scenario/assets/*path",
30709
+ noScenario: "/api/no-scenario/assets/*path",
29869
30710
  shared: "/api/shared/assets/*path",
29870
30711
  redeem: "/api/asset-auth/redeem"
29871
30712
  },
29872
30713
  "/assets": {
29873
30714
  blob: "/assets/blobs/:blobId",
29874
30715
  scenario: "/assets/scenario/*path",
30716
+ editedScenario: "/assets/scenarios/:scenario/*path",
30717
+ noScenario: "/assets/no-scenario/*path",
29875
30718
  shared: "/assets/shared/*path",
29876
30719
  redeem: "/assets/auth/redeem"
29877
30720
  }
@@ -29889,15 +30732,17 @@ function registerAssetRoutes(app, deps, prefix) {
29889
30732
  res.json({ ok: true });
29890
30733
  });
29891
30734
  app.get(paths.blob, async (req, res) => {
30735
+ let blob;
29892
30736
  try {
29893
- const blob = await readBlob(packagePath, req.params.blobId);
29894
- res.setHeader("Content-Type", blob.mimeType);
29895
- res.setHeader("X-Asset-Name", encodeURIComponent(blob.name));
29896
- res.setHeader("Access-Control-Expose-Headers", "X-Asset-Name");
29897
- res.send(blob.data);
30737
+ blob = await readBlob(packagePath, req.params.blobId);
29898
30738
  } catch {
29899
30739
  res.status(404).send("Blob not found");
30740
+ return;
29900
30741
  }
30742
+ res.setHeader("Content-Type", blob.mimeType);
30743
+ res.setHeader("X-Asset-Name", encodeURIComponent(blob.name));
30744
+ res.setHeader("Access-Control-Expose-Headers", "X-Asset-Name");
30745
+ sendBytes(req, res, blob.data);
29901
30746
  });
29902
30747
  app.get(paths.scenario, (req, res) => {
29903
30748
  const scenario = session.activeScenario();
@@ -29905,9 +30750,23 @@ function registerAssetRoutes(app, deps, prefix) {
29905
30750
  res.status(404).send("No active scenario");
29906
30751
  return;
29907
30752
  }
29908
- const root2 = isAbsolute11(scenario.rootDirectory) ? scenario.rootDirectory : resolve11(packagePath, scenario.rootDirectory);
29909
- serveAsset(req, res, resolve11(root2, "assets"));
30753
+ serveAsset(req, res, scenarioAssets(scenario));
30754
+ });
30755
+ app.get(paths.editedScenario, (req, res) => {
30756
+ const scenario = session.packageConfiguration()?.scenarios?.find((entry) => entry.definition.identifier === req.params.scenario);
30757
+ if (!scenario) {
30758
+ res.status(404).send("No such scenario");
30759
+ return;
30760
+ }
30761
+ serveAsset(req, res, scenarioAssets(scenario));
29910
30762
  });
30763
+ app.get(paths.noScenario, (_req, res) => {
30764
+ res.status(404).send("No scenario is being edited");
30765
+ });
30766
+ function scenarioAssets(scenario) {
30767
+ const root2 = isAbsolute11(scenario.rootDirectory) ? scenario.rootDirectory : resolve11(packagePath, scenario.rootDirectory);
30768
+ return resolve11(root2, "assets");
30769
+ }
29911
30770
  app.get(paths.shared, (req, res) => {
29912
30771
  serveAsset(req, res, resolve11(packagePath, "shared-assets"));
29913
30772
  });
@@ -29938,15 +30797,32 @@ function serveAsset(req, res, root2) {
29938
30797
  res.status(404).send("Asset not found");
29939
30798
  return;
29940
30799
  }
30800
+ res.setHeader("Content-Type", mediaTypeOf(resolved));
29941
30801
  res.setHeader("X-Asset-Name", encodeURIComponent(assetPath.split("/").pop() ?? assetPath));
29942
30802
  res.setHeader("Access-Control-Expose-Headers", "X-Asset-Name");
29943
30803
  res.sendFile(normalize3(assetPath), { root: root2 });
29944
30804
  }
30805
+ function sendBytes(req, res, data) {
30806
+ res.setHeader("Accept-Ranges", "bytes");
30807
+ const ranges = req.headers.range === void 0 ? void 0 : req.range(data.length);
30808
+ if (ranges === -1) {
30809
+ res.status(416).setHeader("Content-Range", `bytes */${data.length}`);
30810
+ res.end();
30811
+ return;
30812
+ }
30813
+ if (Array.isArray(ranges) && ranges.type === "bytes" && ranges.length === 1) {
30814
+ const [{ start, end }] = ranges;
30815
+ res.status(206).setHeader("Content-Range", `bytes ${start}-${end}/${data.length}`);
30816
+ res.send(data.subarray(start, end + 1));
30817
+ return;
30818
+ }
30819
+ res.send(data);
30820
+ }
29945
30821
 
29946
30822
  // cli/dev/view/commands.ts
29947
30823
  var FRAME_COMMANDS = {
29948
- game: /* @__PURE__ */ new Set(["updateData", "requestTick", "renameOwnTeam"]),
29949
- "waiting-room": /* @__PURE__ */ new Set(["updateData", "requestTick", "renameOwnTeam"]),
30824
+ game: /* @__PURE__ */ new Set(["updateData", "requestTick", "renameOwnTeam", "renameSelf"]),
30825
+ "waiting-room": /* @__PURE__ */ new Set(["updateData", "requestTick", "renameOwnTeam", "renameSelf"]),
29950
30826
  session: /* @__PURE__ */ new Set([
29951
30827
  "updateSessionData",
29952
30828
  "updateSharedData",
@@ -29955,6 +30831,7 @@ var FRAME_COMMANDS = {
29955
30831
  "resetGame",
29956
30832
  "resetWalkthrough",
29957
30833
  "setWaitingRoom",
30834
+ "setLocale",
29958
30835
  "createTeam",
29959
30836
  "renameTeam",
29960
30837
  "renameParticipant",
@@ -29974,7 +30851,9 @@ var FRAME_COMMANDS = {
29974
30851
  var NO_TEAM_ID = {
29975
30852
  setWaitingRoom: "The waiting room is session-wide, so setWaitingRoom takes no teamId",
29976
30853
  renameOwnTeam: "renameOwnTeam renames the caller's own team, which the host resolves; it takes no teamId",
29977
- resetWalkthrough: "A walkthrough holds one team, so resetWalkthrough takes no teamId"
30854
+ resetWalkthrough: "A walkthrough holds one team, so resetWalkthrough takes no teamId",
30855
+ setLocale: "The locale is the session's, so setLocale takes no teamId",
30856
+ renameSelf: "renameSelf renames the caller, whom the host resolves; it takes no teamId"
29978
30857
  };
29979
30858
  var FRAME_QUERIES = {
29980
30859
  game: /* @__PURE__ */ new Set(["callEndpoint", "getPastState", "getAllTeamsParticipants"]),
@@ -30014,6 +30893,11 @@ function commandFor(message, surface, viewer) {
30014
30893
  if (message.teamId !== void 0 && message.type in NO_TEAM_ID) {
30015
30894
  return { refused: NO_TEAM_ID[message.type] };
30016
30895
  }
30896
+ if (message.type === "renameSelf" && message.participantId !== void 0) {
30897
+ return {
30898
+ refused: "renameSelf renames the caller, whom the host resolves; it takes no participantId"
30899
+ };
30900
+ }
30017
30901
  const scope = teamScope(viewer);
30018
30902
  const actor = actorOf(viewer);
30019
30903
  const role = roleOf(viewer);
@@ -30072,6 +30956,8 @@ function commandFor(message, surface, viewer) {
30072
30956
  };
30073
30957
  case "setWaitingRoom":
30074
30958
  return { type: "setWaitingRoom", open: message.open === true };
30959
+ case "setLocale":
30960
+ return { type: "setLocale", locale: String(message.locale) };
30075
30961
  case "resetWalkthrough":
30076
30962
  return { type: "resetWalkthrough" };
30077
30963
  case "createTeam":
@@ -30087,6 +30973,8 @@ function commandFor(message, surface, viewer) {
30087
30973
  };
30088
30974
  case "renameOwnTeam":
30089
30975
  return { type: "renameOwnTeam", name: String(message.name), ...actor };
30976
+ case "renameSelf":
30977
+ return { type: "renameSelf", name: String(message.name), ...actor };
30090
30978
  case "renameParticipant":
30091
30979
  return {
30092
30980
  type: "renameParticipant",
@@ -30210,295 +31098,6 @@ function routeHref(route) {
30210
31098
  return search2 ? `${path3}?${search2}` : path3;
30211
31099
  }
30212
31100
 
30213
- // cli/dev/view/batch.ts
30214
- function projectContext2(context, surface) {
30215
- const declared = /* @__PURE__ */ new Set([...surface.reads, ...surface.writes]);
30216
- const projected = {};
30217
- for (const [capability, values] of Object.entries(context)) {
30218
- if (declared.has(capability)) projected[capability] = values;
30219
- }
30220
- return projected;
30221
- }
30222
- function settingsFor(state2, surface, { withoutSession = false } = {}) {
30223
- const settings = withoutSession ? state2.settingsWithoutSession : state2.settings;
30224
- return Object.fromEntries(
30225
- surface.settings.filter((identifier) => identifier in settings).map((identifier) => [identifier, settings[identifier]])
30226
- );
30227
- }
30228
- function draftSettingsFor(state2, surface, viewer) {
30229
- const scenarioId = viewer.scenario ?? null;
30230
- const draft = state2.scenarioDrafts?.find((entry) => entry.scenarioId === scenarioId);
30231
- const settings = draft?.settings ?? {};
30232
- return Object.fromEntries(
30233
- surface.settings.filter((identifier) => identifier in settings).map((identifier) => [identifier, settings[identifier]])
30234
- );
30235
- }
30236
- function sessionKeyFor(state2, surface, { sessionless = false } = {}) {
30237
- const outside = surface.kind === "scenario-editor" || surface.kind === "presentation" && sessionless;
30238
- return outside ? `outside-session:${state2.game.identifier}` : state2.session.sessionKey;
30239
- }
30240
- function themeMessages(theme) {
30241
- return [
30242
- { type: "setTheme", payload: theme.palette },
30243
- { type: "themePreferenceChanged", preference: theme.preference }
30244
- ];
30245
- }
30246
- function assetUrls(assetOrigin) {
30247
- return {
30248
- blobPrefix: `${assetOrigin}/assets/blobs/`,
30249
- scenarioAssetPrefix: `${assetOrigin}/assets/scenario/`,
30250
- sharedAssetPrefix: `${assetOrigin}/assets/shared/`,
30251
- assetAuthRedeemUrl: `${assetOrigin}/assets/auth/redeem`
30252
- };
30253
- }
30254
- function teamOf(state2, teamIndex) {
30255
- if (teamIndex === void 0) return state2.teams[0];
30256
- return state2.teams.find((team) => team.index === teamIndex);
30257
- }
30258
- function teamList(state2) {
30259
- return [...state2.teams].sort((a, b) => a.index - b.index).map((team) => ({ teamId: team.teamId, index: team.index, name: team.name }));
30260
- }
30261
- var IDLE_TIMER2 = {
30262
- enabled: false,
30263
- paused: false,
30264
- nextTickAt: null,
30265
- intervalMs: null,
30266
- pausedAt: null,
30267
- pausedMs: 0,
30268
- extendedMs: 0,
30269
- scheduleStartedAt: null
30270
- };
30271
- function buildBatch(options) {
30272
- const { surface, state: state2, theme, origin, assetOrigin } = options;
30273
- const common = [
30274
- { type: "setLocale", payload: { locale: state2.session.locale } },
30275
- { type: "setAssetUrls", payload: assetUrls(assetOrigin ?? origin) },
30276
- ...theme ? themeMessages(theme) : []
30277
- ];
30278
- switch (surface.kind) {
30279
- case "game":
30280
- case "waiting-room":
30281
- return [...playerBatch(options), ...common];
30282
- case "session":
30283
- return [...sessionBatch(options), ...common];
30284
- // The two settings editors are sent the same batch (§12.3): neither is
30285
- // told which slot it fills, since each is its own bundle.
30286
- case "setup":
30287
- return [{ type: "setSettings", payload: settingsFor(state2, surface) }, ...common];
30288
- case "scenario-editor":
30289
- return [
30290
- { type: "setSettings", payload: draftSettingsFor(state2, surface, options.viewer) },
30291
- ...common
30292
- ];
30293
- case "presentation":
30294
- return [...presentationBatch(options), ...common];
30295
- }
30296
- return common;
30297
- }
30298
- function crossTeamData(state2, surface, ownTeamIndex) {
30299
- const across = new Set(surface.crossTeamReads);
30300
- return [...state2.teams].sort((a, b) => a.index - b.index).map((team) => ({
30301
- teamId: team.teamId,
30302
- index: team.index,
30303
- name: team.name,
30304
- context: team.index === ownTeamIndex ? projectContext2(team.context, surface) : Object.fromEntries(
30305
- Object.entries(team.context).filter(
30306
- ([capability]) => across.has(capability)
30307
- )
30308
- )
30309
- }));
30310
- }
30311
- function joinUrl(origin, teamIndex) {
30312
- return `${origin}/team/${teamIndex + 1}/join?bare`;
30313
- }
30314
- function playerBatch({
30315
- surface,
30316
- state: state2,
30317
- viewer,
30318
- origin,
30319
- roundProcessing
30320
- }) {
30321
- const team = teamOf(state2, viewer.teamIndex);
30322
- const participant = viewer.observer ? void 0 : team?.participants.find((p) => p.id === viewer.participantId) ?? team?.participants[0];
30323
- const messages2 = [
30324
- {
30325
- type: "stateChanged",
30326
- payload: projectContext2(team?.context ?? {}, surface),
30327
- // §12.5: the head tick, so a review scrubber can be bounded and a
30328
- // cache invalidated on undo.
30329
- completedTicks: team?.completedTicks ?? state2.session.completedTicks
30330
- },
30331
- { type: "setSettings", payload: settingsFor(state2, surface) }
30332
- ];
30333
- if (participant) {
30334
- messages2.push({
30335
- type: "setParticipant",
30336
- payload: {
30337
- id: participant.id,
30338
- name: participant.name,
30339
- index: participant.index,
30340
- teamId: team?.teamId ?? "team-1"
30341
- }
30342
- });
30343
- }
30344
- messages2.push(
30345
- { type: "setViewerRole", role: viewer.observer ? "observer" : "participant" },
30346
- { type: "setRunKind", runKind: state2.session.runKind },
30347
- { type: "setScenarioName", scenarioName: state2.game.scenarioName },
30348
- {
30349
- type: "setOwnTeam",
30350
- payload: team ? { teamId: team.teamId, index: team.index, name: team.name } : { teamId: "team-1", index: 0, name: "Team 1" }
30351
- },
30352
- {
30353
- type: "setOwnTeamJoinLink",
30354
- payload: team ? { joinUrl: joinUrl(origin, team.index) } : (
30355
- // §12.3, as amended: a host with nothing to offer says so
30356
- // rather than staying silent, so a surface rendering a join
30357
- // panel shows nothing instead of waiting for a message that
30358
- // never comes.
30359
- null
30360
- )
30361
- },
30362
- { type: "setParticipantList", participants: team?.participants ?? [] },
30363
- { type: "setTeamList", payload: teamList(state2) },
30364
- { type: "setTimer", payload: team?.timer ?? IDLE_TIMER2 }
30365
- );
30366
- if (surface.kind === "game") {
30367
- messages2.push({ type: "setRoundProcessing", processing: roundProcessing === true });
30368
- }
30369
- if ((surface.kind === "game" || surface.kind === "waiting-room") && surface.crossTeamReads.length > 0 && state2.session.mode === "shared-state") {
30370
- messages2.push({
30371
- type: "setCrossTeamData",
30372
- payload: crossTeamData(state2, surface, team?.index)
30373
- });
30374
- }
30375
- return messages2;
30376
- }
30377
- function sessionBatch({
30378
- surface,
30379
- state: state2,
30380
- gameName,
30381
- origin,
30382
- hasGuide
30383
- }) {
30384
- return [
30385
- {
30386
- type: "setSessionMeta",
30387
- payload: {
30388
- sessionId: "dev-session",
30389
- name: gameName,
30390
- readOnly: false,
30391
- waitingRoomOpen: state2.session.waitingRoomOpen,
30392
- joinPin: null
30393
- }
30394
- },
30395
- { type: "setSessionData", payload: sessionData(state2, surface) },
30396
- { type: "setSettings", payload: settingsFor(state2, surface) },
30397
- { type: "setTeamConfiguration", payload: teamConfiguration(state2) },
30398
- { type: "setTeamList", payload: teamList(state2) },
30399
- {
30400
- type: "setParticipantList",
30401
- participants: state2.teams.flatMap(
30402
- (team) => team.participants.map((participant) => ({
30403
- id: participant.id,
30404
- name: participant.name,
30405
- index: participant.index,
30406
- connected: participant.connected,
30407
- teamId: team.teamId
30408
- }))
30409
- )
30410
- },
30411
- { type: "setTeamLinks", payload: teamLinks(state2, origin) },
30412
- { type: "setWalkthroughLink", payload: walkthroughLink(origin) },
30413
- { type: "setRunKind", runKind: state2.session.runKind },
30414
- { type: "setScenarioName", scenarioName: state2.game.scenarioName },
30415
- { type: "setAvailableOverlays", overlays: availableOverlays(hasGuide) }
30416
- ];
30417
- }
30418
- function presentationBatch({
30419
- surface,
30420
- state: state2,
30421
- gameName,
30422
- sessionless
30423
- }) {
30424
- return [
30425
- {
30426
- type: "setPresentation",
30427
- payload: {
30428
- game: {
30429
- name: state2.game.name,
30430
- // Without a session, as the scenario resolves it alone (§6.15.1).
30431
- maxTicks: sessionless ? gameSettingsOf(state2.settingsWithoutSession).maxTicks : state2.session.maxTicks,
30432
- mode: state2.session.mode,
30433
- scenarioName: state2.game.scenarioName
30434
- },
30435
- session: sessionless ? null : {
30436
- // The dev server runs one session; its id is the
30437
- // one the session surface is told (above).
30438
- id: "dev-session",
30439
- name: gameName,
30440
- completedTicks: Math.max(
30441
- state2.session.completedTicks,
30442
- ...state2.teams.map((team) => team.completedTicks)
30443
- ),
30444
- data: sessionData(state2, surface),
30445
- teams: teamList(state2)
30446
- }
30447
- }
30448
- },
30449
- {
30450
- type: "setSettings",
30451
- payload: settingsFor(state2, surface, { withoutSession: sessionless })
30452
- }
30453
- ];
30454
- }
30455
- function walkthroughLink(origin) {
30456
- return { url: `${origin}/walkthrough` };
30457
- }
30458
- function availableOverlays(hasGuide = false) {
30459
- return hasGuide ? ["facilitator-guide", "print-sheets"] : ["print-sheets"];
30460
- }
30461
- function teamLinks(state2, origin) {
30462
- return [...state2.teams].sort((a, b) => a.index - b.index).map((team) => ({
30463
- teamId: team.teamId,
30464
- joinUrl: joinUrl(origin, team.index),
30465
- observeUrl: `${origin}/team/${team.index + 1}/observe`
30466
- }));
30467
- }
30468
- function teamConfiguration(state2) {
30469
- return {
30470
- mode: state2.session.mode,
30471
- ...state2.session.teamBounds.min === void 0 ? {} : { min: state2.session.teamBounds.min },
30472
- max: state2.session.teamBounds.max
30473
- };
30474
- }
30475
- function sessionData(state2, surface) {
30476
- const teams = {};
30477
- for (const team of state2.teams) {
30478
- const own5 = {};
30479
- for (const [capability, values] of Object.entries(team.context)) {
30480
- if (!(capability in state2.shared)) own5[capability] = values;
30481
- }
30482
- teams[team.teamId] = {
30483
- context: projectContext2(own5, surface),
30484
- completedTicks: team.completedTicks,
30485
- timer: team.timer ?? IDLE_TIMER2,
30486
- // Monotonic per delivery. One session, one host, so the tick is a
30487
- // sufficient clock; the wrapper only compares it with itself.
30488
- revision: team.completedTicks
30489
- };
30490
- }
30491
- return {
30492
- // The dev server only ever sends snapshots, so the revision is a
30493
- // baseline the wrapper never compares a delta against.
30494
- shared: {
30495
- context: projectContext2(state2.shared, surface),
30496
- revision: state2.session.completedTicks
30497
- },
30498
- teams
30499
- };
30500
- }
30501
-
30502
31101
  // cli/dev/view/viewer.ts
30503
31102
  function resolveViewer(state2, route) {
30504
31103
  const base = {
@@ -30613,7 +31212,7 @@ function viewMessages(page, state2, options) {
30613
31212
  origin: options.origin,
30614
31213
  assetOrigin: options.assetOrigin,
30615
31214
  gameName: options.gameName,
30616
- hasGuide: options.hasGuide,
31215
+ overlays: options.overlays,
30617
31216
  roundProcessing: options.roundProcessing
30618
31217
  });
30619
31218
  }
@@ -31257,7 +31856,10 @@ Install the package's dependencies to serve its surfaces.
31257
31856
  origin: this.consoleOrigin(view.host),
31258
31857
  assetOrigin: origin,
31259
31858
  gameName: state2.game.name,
31260
- hasGuide: session.effectiveGuide() !== null,
31859
+ overlays: availableOverlays({
31860
+ guide: session.effectiveGuide() !== null,
31861
+ presentation: offersPresentationOverlay(session.packageConfiguration())
31862
+ }),
31261
31863
  roundProcessing
31262
31864
  });
31263
31865
  return { page, messages: messages2 };