@seriousgaming/sdk-tools 1.3.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 (36) hide show
  1. package/dist/cli.js +3216 -2538
  2. package/dist/client.js +693 -161
  3. package/dist/core/session-host.d.ts +4 -2
  4. package/dist/core/settings-locks.d.ts +27 -2
  5. package/dist/dev/console/assets/{index-DEV8N0na.js → index-BvB-LFQZ.js} +10 -10
  6. package/dist/dev/console/index.html +1 -1
  7. package/dist/dev/routes.d.ts +4 -0
  8. package/dist/dev/view/batch.d.ts +7 -1
  9. package/dist/docs/api/index.md +1 -1
  10. package/dist/docs/api/sdk-tools-client.md +1 -0
  11. package/dist/docs/api/sdk.md +79 -2
  12. package/dist/docs/changelog.md +25 -0
  13. package/dist/docs/concepts/terminology.md +1 -1
  14. package/dist/docs/guides/capabilities.md +2 -0
  15. package/dist/docs/guides/endpoints.md +2 -2
  16. package/dist/docs/guides/engine-testing.md +1 -1
  17. package/dist/docs/guides/file-handling.md +113 -21
  18. package/dist/docs/guides/llm-integration.md +1 -1
  19. package/dist/docs/guides/scenario-editor.md +1 -1
  20. package/dist/docs/guides/scenarios.md +9 -1
  21. package/dist/docs/guides/settings.md +62 -2
  22. package/dist/docs/guides/validators.md +62 -4
  23. package/dist/docs/recipes/upload-and-display-files.md +7 -7
  24. package/dist/docs/recipes/validate-scenarios.md +4 -1
  25. package/dist/execution/endpoint-runner.d.ts +6 -0
  26. package/dist/execution/logic-calls.d.ts +7 -2
  27. package/dist/execution/scenario-gates.d.ts +21 -1
  28. package/dist/guide/settings.d.ts +1 -1
  29. package/dist/host.js +64 -2
  30. package/dist/runtime/manifest-version.d.ts +1 -1
  31. package/dist/runtime.js +7 -2
  32. package/dist/storage/asset-resolver.d.ts +24 -1
  33. package/dist/storage/blob-store.d.ts +7 -0
  34. package/dist/utils/local-refs.d.ts +40 -0
  35. package/dist/utils/schema-members.d.ts +19 -0
  36. package/package.json +3 -3
package/dist/client.js CHANGED
@@ -2703,7 +2703,9 @@ var SUPPORTED_FEATURES = [
2703
2703
  // A validator's `Scenario` gate (§15.8).
2704
2704
  "scenario-validation",
2705
2705
  // The presentation as a host overlay a session surface may open (§6.4).
2706
- "presentation-overlay"
2706
+ "presentation-overlay",
2707
+ // File reads in a validator's `Scenario` gate (§15.8).
2708
+ "scenario-files"
2707
2709
  ];
2708
2710
  function unsupportedFeatures(manifest) {
2709
2711
  return (manifest.requires ?? []).filter((feature) => !SUPPORTED_FEATURES.includes(feature));
@@ -3144,8 +3146,11 @@ function createAjv(fileValues = "resolved") {
3144
3146
  const ajv4 = new Ajv({
3145
3147
  allErrors: true,
3146
3148
  // Report all errors, not just the first one
3147
- verbose: true
3149
+ verbose: true,
3148
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
3149
3154
  });
3150
3155
  ajv4.addKeyword({ keyword: "tsType", schemaType: "string" });
3151
3156
  ajv4.addKeyword({
@@ -3253,25 +3258,263 @@ function typesOf(schema2) {
3253
3258
 
3254
3259
  // cli/core/settings-locks.ts
3255
3260
  import { isDeepStrictEqual } from "util";
3256
- 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) {
3257
3459
  const paths = [];
3258
- if (schema2) collect(schema2, [], paths);
3460
+ if (schema2) named(schema2, schema2, override, [], paths);
3259
3461
  return paths;
3260
3462
  }
3261
- 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);
3262
3466
  if (schema2.readOnly === true) {
3263
3467
  paths.push(at);
3264
3468
  return;
3265
3469
  }
3266
- for (const [key, property] of Object.entries(schema2.properties ?? {})) {
3267
- 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);
3268
3474
  }
3269
3475
  }
3270
- function lockedPathsNamed(override, schema2) {
3271
- 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}"`;
3272
3515
  }
3273
3516
  function lockedSettingName(identifier, path3) {
3274
- return [identifier, ...path3].join(".");
3517
+ return settingPath(identifier, ...path3);
3275
3518
  }
3276
3519
  function lockedSettingMessage(identifier, path3) {
3277
3520
  return `"${lockedSettingName(identifier, path3)}" is read-only: the game fixes it, so no scenario or session may change it`;
@@ -3281,7 +3524,7 @@ function withoutLockedDefaults(settings, schemas) {
3281
3524
  for (const [identifier, schema2] of Object.entries(schemas)) {
3282
3525
  if (!(identifier in result)) continue;
3283
3526
  const defaults = schemaDefaults(schema2);
3284
- for (const path3 of lockedPaths(schema2)) {
3527
+ for (const path3 of lockedPathsNamed(result[identifier], schema2)) {
3285
3528
  if (path3.length === 0) {
3286
3529
  if (isDeepStrictEqual(result[identifier], defaults)) delete result[identifier];
3287
3530
  continue;
@@ -4198,13 +4441,41 @@ function validateSettingsOverrides(overrides, schemas, sourceLabel) {
4198
4441
  ${errors.join("\n")}` } : { valid: true };
4199
4442
  }
4200
4443
  function validatePartialOverride(override, settingsSchema) {
4201
- 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
+ }
4202
4458
  return validator(override) ? null : validator.errors ?? [];
4203
4459
  }
4204
4460
  var SCHEMA_MAP_KEYWORDS = ["properties", "patternProperties", "definitions", "$defs"];
4205
4461
  var SUBSCHEMA_KEYWORDS = ["additionalProperties", "then", "else"];
4206
4462
  var SCHEMA_LIST_KEYWORDS = ["allOf", "anyOf", "oneOf"];
4207
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) {
4208
4479
  if (typeof schema2 !== "object" || schema2 === null) return schema2;
4209
4480
  const { required: _required, ...rest } = schema2;
4210
4481
  const copy = { ...rest };
@@ -4212,20 +4483,32 @@ function withoutRequired(schema2) {
4212
4483
  const map3 = rest[keyword];
4213
4484
  if (map3 && typeof map3 === "object") {
4214
4485
  copy[keyword] = Object.fromEntries(
4215
- Object.entries(map3).map(([key, value]) => [key, withoutRequired(value)])
4486
+ Object.entries(map3).map(([key, value]) => [key, partially(value)])
4216
4487
  );
4217
4488
  }
4218
4489
  }
4219
4490
  for (const keyword of SUBSCHEMA_KEYWORDS) {
4220
4491
  const sub = rest[keyword];
4221
- if (sub !== void 0) copy[keyword] = withoutRequired(sub);
4492
+ if (sub !== void 0) copy[keyword] = partially(sub);
4222
4493
  }
4223
4494
  for (const keyword of SCHEMA_LIST_KEYWORDS) {
4224
4495
  const list3 = rest[keyword];
4225
- if (Array.isArray(list3)) copy[keyword] = list3.map(withoutRequired);
4496
+ if (Array.isArray(list3)) copy[keyword] = list3.map(partially);
4226
4497
  }
4498
+ if (rest.items !== void 0) copy.items = wholeRefs(rest.items);
4227
4499
  return copy;
4228
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
+ }
4229
4512
  var COMBINATOR_KEYWORDS = ["allOf", "anyOf", "oneOf", "if", "not", "$ref"];
4230
4513
  function closed(schema2) {
4231
4514
  if (typeof schema2 !== "object" || schema2 === null) return schema2;
@@ -4827,12 +5110,12 @@ function assertRequiredFeaturesSupported(config, filePath) {
4827
5110
  function assertDeclaredServicesSupported(resources) {
4828
5111
  const missing = unsupportedServices(resources);
4829
5112
  if (missing.length === 0) return;
4830
- const named2 = missing.map(
5113
+ const named3 = missing.map(
4831
5114
  ({ service, resources: declaring }) => `"${service}" (declared by ${declaring.join(", ")})`
4832
5115
  ).join(", ");
4833
5116
  throw new CliError(
4834
5117
  "PACKAGE_INVALID",
4835
- `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.`
4836
5119
  );
4837
5120
  }
4838
5121
  function resolvePackage(config, configDir, game) {
@@ -6033,20 +6316,20 @@ function assertDeletesDeclared(label4, deletes, declaration, shared, target) {
6033
6316
  const reads = new Set(declaration.reads ?? []);
6034
6317
  for (const path3 of deletes) {
6035
6318
  const capId = deleteHead(path3);
6036
- const named2 = `${label4} deletes ${describeDeletePath(path3)}`;
6319
+ const named3 = `${label4} deletes ${describeDeletePath(path3)}`;
6037
6320
  if (target === "team" && shared.has(capId)) {
6038
6321
  throw new Error(
6039
- `${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.`
6040
6323
  );
6041
6324
  }
6042
6325
  if (target === "shared" && !shared.has(capId)) {
6043
6326
  throw new Error(
6044
- `${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.`
6045
6328
  );
6046
6329
  }
6047
6330
  if (!writes.has(capId)) {
6048
6331
  throw new Error(
6049
- 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.`
6050
6333
  );
6051
6334
  }
6052
6335
  }
@@ -6326,7 +6609,7 @@ function computeCapabilityDefaults(config) {
6326
6609
  // cli/storage/blob-store.ts
6327
6610
  import { randomUUID } from "crypto";
6328
6611
  import { existsSync as existsSync4 } from "fs";
6329
- 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";
6330
6613
  import { join as join3, resolve as resolve2 } from "path";
6331
6614
  var MAX_BLOB_SIZE = 20 * 1024 * 1024;
6332
6615
  var redirected = /* @__PURE__ */ new Map();
@@ -6376,6 +6659,18 @@ async function readBlob(packagePath, id) {
6376
6659
  const meta = JSON.parse(metaRaw);
6377
6660
  return { ...meta, data };
6378
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
+ }
6379
6674
  async function deleteBlobs(packagePath, retentions) {
6380
6675
  const dir = getBlobsDir(packagePath);
6381
6676
  let entries;
@@ -6400,19 +6695,62 @@ async function deleteBlobs(packagePath, retentions) {
6400
6695
  );
6401
6696
  }
6402
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
+
6403
6738
  // cli/execution/blob-inputs.ts
6404
6739
  var MAX_INLINE_BYTES = 5 * 1024 * 1024;
6405
- function blobValues(schema2, value, path3 = []) {
6406
- 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);
6407
6743
  const spec = schema2.blob;
6408
6744
  if (spec) return value === void 0 ? [] : [{ path: path3, spec, value }];
6409
6745
  if (Array.isArray(value) && schema2.items && !Array.isArray(schema2.items)) {
6410
6746
  const items = schema2.items;
6411
- return value.flatMap((item, at) => blobValues(items, item, [...path3, at]));
6747
+ return value.flatMap((item, at) => blobValues(items, item, [...path3, at], root2));
6412
6748
  }
6413
- if (value && typeof value === "object" && !Array.isArray(value) && schema2.properties) {
6414
- return Object.entries(schema2.properties).flatMap(
6415
- ([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
+ )
6416
6754
  );
6417
6755
  }
6418
6756
  return [];
@@ -6527,7 +6865,7 @@ var ACTION_FIELDS = {
6527
6865
  addTeam: { "name?": "string" },
6528
6866
  setLocale: { locale: "string" }
6529
6867
  };
6530
- function matches2(value, kind2) {
6868
+ function matches3(value, kind2) {
6531
6869
  switch (kind2) {
6532
6870
  case "string":
6533
6871
  return typeof value === "string" && value.length > 0;
@@ -6565,7 +6903,7 @@ function readEndpointActions(identifier, declared, returned) {
6565
6903
  if (key.endsWith("?")) continue;
6566
6904
  throw new Error(`${label4} ("${type}") requires "${name}"`);
6567
6905
  }
6568
- if (!matches2(value, kind2)) {
6906
+ if (!matches3(value, kind2)) {
6569
6907
  throw new Error(`${label4} ("${type}") field "${name}" must be a ${kind2}`);
6570
6908
  }
6571
6909
  }
@@ -6922,7 +7260,7 @@ var EndpointRunner = class {
6922
7260
  const callbacks = calls.callbacksFor(
6923
7261
  endpoint.definition.identifier,
6924
7262
  endpoint.definition.uses,
6925
- scenarioScoped ? "scenario" : void 0
7263
+ scenarioScoped ? { scenarioRoot: args.scenarioRoot ?? null } : void 0
6926
7264
  );
6927
7265
  const scope = sessionScoped || scenarioScoped ? null : args.scopedTeamIndex ?? null;
6928
7266
  const label4 = exportName === "Handle" ? `Endpoint "${args.identifier}"` : `Endpoint "${args.identifier}" ${exportName}`;
@@ -7146,21 +7484,6 @@ async function runHookChain(host, signal, payload) {
7146
7484
  return structuredClone(host.board());
7147
7485
  }
7148
7486
 
7149
- // ../sdk/lib/build/callbacks.js
7150
- var UndeclaredApiUseError = class extends Error {
7151
- resourceIdentifier;
7152
- api;
7153
- constructor(resourceIdentifier, api) {
7154
- 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.`);
7155
- this.name = "UndeclaredApiUseError";
7156
- this.resourceIdentifier = resourceIdentifier;
7157
- this.api = api;
7158
- }
7159
- };
7160
-
7161
- // ../sdk/lib/build/tick-validation.js
7162
- var MAX_EFFECTIVE_TICK_INTERVAL_MS = 7 * 24 * 60 * 60 * 1e3;
7163
-
7164
7487
  // cli/runtime/guarded-callbacks.ts
7165
7488
  var API_USE_TO_CALLBACK = {
7166
7489
  generateText: "generateText",
@@ -7182,68 +7505,106 @@ function createGuardedCallbacks(callbacks, uses, resourceIdentifier) {
7182
7505
  }
7183
7506
 
7184
7507
  // cli/storage/asset-resolver.ts
7185
- import { readFile as readFile3 } from "fs/promises";
7508
+ import { readFile as readFile3, stat as stat2 } from "fs/promises";
7186
7509
  import { basename as basename2, isAbsolute as isAbsolute3, normalize, resolve as resolvePath, sep as sep4 } from "path";
7187
7510
  var ASSET_PREFIX = "asset:";
7188
7511
  var SHARED_PREFIX = "shared:";
7189
7512
  var BLOB_PREFIX = "blob:";
7190
- var EXTENSION_MIME_TYPES = {
7191
- pdf: "application/pdf",
7192
- json: "application/json",
7193
- txt: "text/plain",
7194
- md: "text/markdown",
7195
- html: "text/html",
7196
- htm: "text/html",
7513
+ var EXTENSION_MEDIA_TYPES = {
7514
+ aac: "audio/aac",
7515
+ avif: "image/avif",
7516
+ bmp: "image/bmp",
7197
7517
  css: "text/css",
7198
7518
  csv: "text/csv",
7199
- svg: "image/svg+xml",
7200
- png: "image/png",
7201
- jpg: "image/jpeg",
7202
- jpeg: "image/jpeg",
7519
+ doc: "application/msword",
7520
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
7521
+ flac: "audio/flac",
7203
7522
  gif: "image/gif",
7204
- webp: "image/webp",
7523
+ htm: "text/html",
7524
+ html: "text/html",
7205
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",
7206
7535
  mp3: "audio/mpeg",
7207
- 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",
7208
7540
  ogg: "audio/ogg",
7209
7541
  opus: "audio/ogg",
7210
- 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",
7211
7555
  webm: "video/webm",
7556
+ webp: "image/webp",
7212
7557
  woff: "font/woff",
7213
- 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"
7214
7565
  };
7215
- function mimeFromExtension(path3) {
7216
- const dot = path3.lastIndexOf(".");
7217
- if (dot < 0) return "application/octet-stream";
7218
- const ext = path3.slice(dot + 1).toLowerCase();
7219
- 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;
7220
7573
  }
7221
7574
  function isAssetReference(value) {
7222
7575
  return typeof value === "string" && (value.startsWith(ASSET_PREFIX) || value.startsWith(SHARED_PREFIX) || value.startsWith(BLOB_PREFIX));
7223
7576
  }
7224
- async function resolveAsset(scenarioRootDirectory, path3) {
7577
+ function scenarioAssetPath(scenarioRootDirectory, path3) {
7225
7578
  const assetsRoot = resolvePath(scenarioRootDirectory, "assets");
7226
7579
  const resolvedPath = resolvePath(assetsRoot, normalize(path3));
7227
7580
  if (!resolvedPath.startsWith(assetsRoot + sep4)) {
7228
7581
  throw new Error(`Asset path escapes scenario assets directory: ${path3}`);
7229
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);
7230
7595
  const data = await readFile3(resolvedPath);
7231
7596
  return {
7232
7597
  data,
7233
- mimeType: mimeFromExtension(resolvedPath),
7598
+ mimeType: mediaTypeOf(resolvedPath),
7234
7599
  name: basename2(resolvedPath)
7235
7600
  };
7236
7601
  }
7237
7602
  async function resolveSharedAsset(packagePath, path3) {
7238
- const sharedRoot = resolvePath(packagePath, "shared-assets");
7239
- const resolvedPath = resolvePath(sharedRoot, normalize(path3));
7240
- if (!resolvedPath.startsWith(sharedRoot + sep4)) {
7241
- throw new Error(`Asset path escapes shared-assets directory: ${path3}`);
7242
- }
7603
+ const resolvedPath = sharedAssetPath(packagePath, path3);
7243
7604
  const data = await readFile3(resolvedPath);
7244
7605
  return {
7245
7606
  data,
7246
- mimeType: mimeFromExtension(resolvedPath),
7607
+ mimeType: mediaTypeOf(resolvedPath),
7247
7608
  name: basename2(resolvedPath)
7248
7609
  };
7249
7610
  }
@@ -7269,6 +7630,30 @@ async function readAssetByReference(packagePath, scenarioRootDirectory, referenc
7269
7630
  `Invalid asset reference "${reference}": expected an "asset:", "shared:", or "blob:" prefix`
7270
7631
  );
7271
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
+ }
7272
7657
 
7273
7658
  // cli/execution/executor-callbacks.ts
7274
7659
  function createExecutorCallbacks(deps) {
@@ -7311,6 +7696,16 @@ function createExecutorCallbacks(deps) {
7311
7696
  name: asset.name
7312
7697
  };
7313
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
+ },
7314
7709
  extractText: async (reference) => {
7315
7710
  requireGame();
7316
7711
  const asset = await readAssetByReference(
@@ -7535,11 +7930,18 @@ var LogicCalls = class {
7535
7930
  * The callbacks a resource receives: the raw runtime callbacks, built
7536
7931
  * fresh so they read the live game, with every one its `uses` does not
7537
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).
7538
7937
  */
7539
- callbacksFor(resourceIdentifier, uses, blobRetention) {
7938
+ callbacksFor(resourceIdentifier, uses, onDraft) {
7540
7939
  const raw = createExecutorCallbacks({
7541
7940
  ...this.options.callbacks,
7542
- ...blobRetention === void 0 ? {} : { blobRetention },
7941
+ ...onDraft === void 0 ? {} : {
7942
+ blobRetention: "scenario",
7943
+ getActiveScenarioRoot: () => onDraft.scenarioRoot
7944
+ },
7543
7945
  readPastState: this.pastStateReader,
7544
7946
  getScopedTeamIndexes: () => this.scopedTeamIndexes,
7545
7947
  getAllTeamIndexes: () => this.teamIndexesForHistory(),
@@ -21989,8 +22391,10 @@ function isUint8Array2(value) {
21989
22391
  // cli/guide/settings.ts
21990
22392
  var WHEN_ATTRIBUTES = ["setting", "is", "not"];
21991
22393
  function lookupSetting(settings, path3) {
21992
- const [identifier, ...keys] = path3.split(".");
21993
- 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 };
21994
22398
  let value = settings[identifier];
21995
22399
  for (const key of keys) {
21996
22400
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -22951,6 +23355,7 @@ var SessionEndpoints = class {
22951
23355
  request: command.request,
22952
23356
  settings: edited.settings,
22953
23357
  scenarioName: edited.scenarioName,
23358
+ scenarioRoot: edited.scenarioRoot,
22954
23359
  now: this.host.clock.now(),
22955
23360
  caller: {
22956
23361
  role: "author",
@@ -24373,36 +24778,45 @@ var SessionTimers = class {
24373
24778
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
24374
24779
 
24375
24780
  // cli/validation/file-settings.ts
24376
- function fileSettingValues(schema2, value, path3 = []) {
24377
- 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);
24378
24784
  const spec = schema2.blob;
24379
24785
  if (spec) return value === void 0 ? [] : [{ path: path3, spec, value }];
24380
24786
  if (Array.isArray(value) && schema2.items && !Array.isArray(schema2.items)) {
24381
24787
  const items = schema2.items;
24382
- 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
+ );
24383
24791
  }
24384
- if (value && typeof value === "object" && !Array.isArray(value) && schema2.properties) {
24385
- return Object.entries(schema2.properties).flatMap(
24386
- ([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
+ )
24387
24797
  );
24388
24798
  }
24389
24799
  return [];
24390
24800
  }
24391
- 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);
24392
24807
  const found = [];
24393
24808
  if ("blob" in schema2) found.push({ path: path3, schema: schema2 });
24394
- for (const [key, child] of Object.entries(schema2.properties ?? {})) {
24395
- if (typeof child === "object")
24396
- found.push(...fileSettingDeclarations(child, [...path3, key]));
24809
+ for (const { step, schema: child } of memberDeclarations(schema2)) {
24810
+ found.push(...fileSettingDeclarations(root2, child, [...path3, step], followed));
24397
24811
  }
24398
24812
  if (schema2.items && !Array.isArray(schema2.items) && typeof schema2.items === "object") {
24399
- found.push(...fileSettingDeclarations(schema2.items, [...path3, "[]"]));
24813
+ found.push(...fileSettingDeclarations(root2, schema2.items, [...path3, "[]"], followed));
24400
24814
  }
24401
24815
  return found;
24402
24816
  }
24403
24817
  var MEDIA_TYPE = /^[^/\s]+\/[^/\s]+$/;
24404
24818
  function where2(identifier, path3) {
24405
- return [identifier, ...path3].join(".");
24819
+ return settingPath(identifier, ...path3);
24406
24820
  }
24407
24821
  function fileSettingDeclarationErrors(identifier, settingsSchema) {
24408
24822
  const errors = [];
@@ -24433,12 +24847,17 @@ function fileSettingDeclarationErrors(identifier, settingsSchema) {
24433
24847
  }
24434
24848
  for (const [key, property] of Object.entries(settingsSchema.properties ?? {})) {
24435
24849
  if (typeof property !== "object" || !("default" in property)) continue;
24436
- 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
+ )) {
24437
24856
  if (typeof value !== "string" || value === "" || value.startsWith("shared:")) {
24438
24857
  continue;
24439
24858
  }
24440
24859
  errors.push(
24441
- `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`
24442
24861
  );
24443
24862
  }
24444
24863
  }
@@ -24466,13 +24885,13 @@ async function packageFileSettingErrors(owner, settings, schemas, resolve12, ski
24466
24885
  }
24467
24886
  return errors;
24468
24887
  }
24469
- async function fileSettingWriteErrors(overrides, schemas, describeBlob, options = {}) {
24888
+ async function fileSettingWriteErrors(overrides, schemas, describeBlob2, options = {}) {
24470
24889
  const errors = [];
24471
24890
  for (const [identifier, value] of Object.entries(overrides)) {
24472
24891
  for (const file of fileSettingValues(schemas[identifier], value)) {
24473
24892
  if (typeof file.value !== "string" || !file.value.startsWith("blob:")) continue;
24474
24893
  const setting = `Setting ${where2(identifier, file.path)}`;
24475
- const found = await describeBlob(file.value);
24894
+ const found = await describeBlob2(file.value);
24476
24895
  if (!found) {
24477
24896
  errors.push(
24478
24897
  `${setting} names ${file.value}, which is not a stored blob. Upload the file first and use the reference it returns`
@@ -24547,13 +24966,13 @@ async function updateSharedContext(host, command) {
24547
24966
  const declared = new Set(
24548
24967
  surface && "writes" in surface.definition ? surface.definition.writes ?? [] : []
24549
24968
  );
24550
- const named2 = [...Object.keys(command.payload), ...(command.deletes ?? []).map(deleteHead)];
24969
+ const named3 = [...Object.keys(command.payload), ...(command.deletes ?? []).map(deleteHead)];
24551
24970
  const declaredByPackage = new Set(
24552
24971
  (executor.getConfig()?.capabilities ?? []).map(
24553
24972
  (capability) => capability.definition.identifier
24554
24973
  )
24555
24974
  );
24556
- for (const capability of named2) {
24975
+ for (const capability of named3) {
24557
24976
  if (!shared.has(capability)) {
24558
24977
  if (declaredByPackage.has(capability)) {
24559
24978
  throw new DeniedError(
@@ -24650,11 +25069,11 @@ function refuseUndeclaredTeamWrite(host, uiIdentifier, payload, deletes) {
24650
25069
  const capabilities = new Set(
24651
25070
  (host.executor.getConfig()?.capabilities ?? []).map((cap) => cap.definition.identifier)
24652
25071
  );
24653
- const named2 = [
25072
+ const named3 = [
24654
25073
  ...Object.keys(payload),
24655
25074
  ...(deletes ?? []).map((path3) => (typeof path3 === "string" ? path3.split(".") : path3)[0])
24656
25075
  ];
24657
- for (const key of named2) {
25076
+ for (const key of named3) {
24658
25077
  if (key === void 0 || !capabilities.has(key)) {
24659
25078
  throw new DeniedError(
24660
25079
  `"${key}" is not a capability of this game, so "${uiIdentifier}" cannot write it`
@@ -25229,19 +25648,11 @@ var Session = class {
25229
25648
  applyPendingChanges: () => this.applyPendingChanges(),
25230
25649
  clearBlobs: (retentions) => this.clearBlobs(retentions),
25231
25650
  describeBlob: async (reference) => {
25232
- try {
25233
- const blob = await readBlob(
25234
- this.options.packagePath,
25235
- reference.slice("blob:".length)
25236
- );
25237
- return {
25238
- mimeType: blob.mimeType,
25239
- size: blob.data.length,
25240
- retention: blob.retention
25241
- };
25242
- } catch {
25243
- return void 0;
25244
- }
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 };
25245
25656
  },
25246
25657
  enqueue: (work) => this.enqueue(work),
25247
25658
  apply: (command) => this.apply(command),
@@ -26073,11 +26484,11 @@ var Session = class {
26073
26484
  if (scenarioId !== null && !this.declaredScenarioIds().has(scenarioId)) {
26074
26485
  throw new DeniedError(`This package declares no scenario "${scenarioId}" to edit`);
26075
26486
  }
26487
+ const scenario = this.executor.getConfig()?.scenarios?.find((entry) => entry.definition.identifier === scenarioId);
26076
26488
  return {
26077
26489
  settings: this.scenarioDraft(scenarioId) ?? this.executor.resolveScenarioDraft(scenarioId, null),
26078
- scenarioName: this.executor.scenarioNameOf(
26079
- this.executor.getConfig()?.scenarios?.find((scenario) => scenario.definition.identifier === scenarioId)
26080
- )
26490
+ scenarioName: this.executor.scenarioNameOf(scenario),
26491
+ scenarioRoot: scenario?.rootDirectory ?? null
26081
26492
  };
26082
26493
  }
26083
26494
  /**
@@ -26774,6 +27185,7 @@ import { dirname as dirname6, resolve as resolve7 } from "path";
26774
27185
  import { existsSync as existsSync9 } from "fs";
26775
27186
  import { readFile as readFile6 } from "fs/promises";
26776
27187
  var SCENARIO_VALIDATION = "scenario-validation";
27188
+ var SCENARIO_FILES = "scenario-files";
26777
27189
  function hasScenarioGate(config) {
26778
27190
  return (config.validators ?? []).some((v) => v.definition.gates?.includes("scenario"));
26779
27191
  }
@@ -26786,6 +27198,7 @@ async function runScenarioGates(options) {
26786
27198
  });
26787
27199
  const resolved = resolveSettingsLayers(config, options.scenarioSettings, null);
26788
27200
  const locale = options.locale ?? config.game?.definition.supportedLocales?.[0] ?? "en";
27201
+ const readsFiles = (config.requires ?? []).includes(SCENARIO_FILES);
26789
27202
  const problems = [];
26790
27203
  for (const validator of config.validators ?? []) {
26791
27204
  if (!validator.definition.gates?.includes("scenario")) continue;
@@ -26812,7 +27225,11 @@ async function runScenarioGates(options) {
26812
27225
  const found = await withBound(
26813
27226
  gate({
26814
27227
  settings: structuredClone(pick(resolved)),
26815
- locale
27228
+ locale,
27229
+ callbacks: readsFiles ? scenarioCallbacks(
27230
+ options.packagePath,
27231
+ options.files ?? { scenarioRoot: null, blobs: "none" }
27232
+ ) : withoutScenarioFiles(identifier)
26816
27233
  }),
26817
27234
  options.boundMs ?? DEFAULT_LOGIC_EXECUTION_BOUND_MS
26818
27235
  );
@@ -26835,6 +27252,40 @@ async function runScenarioGates(options) {
26835
27252
  }
26836
27253
  return problems;
26837
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
+ }
26838
27289
  async function withBound(run, boundMs) {
26839
27290
  let timer;
26840
27291
  try {
@@ -27051,26 +27502,28 @@ function typesOf2(schema2) {
27051
27502
  return schema2.type ? [schema2.type] : [];
27052
27503
  }
27053
27504
  function propertyAt(path3, context) {
27054
- const [identifier, ...keys] = path3.split(".");
27055
- if (!identifier || keys.length === 0) {
27505
+ const parsed = parseSettingPath(path3);
27506
+ if (!parsed || parsed.keys.length === 0) {
27056
27507
  return {
27057
27508
  error: `"${path3}" should be a settings identifier and a property, e.g. engine.weeks`
27058
27509
  };
27059
27510
  }
27511
+ const { identifier, keys } = parsed;
27060
27512
  if (!context.declared.includes(identifier)) {
27061
27513
  return {
27062
27514
  error: `"${path3}" reads settings "${identifier}", which the guide does not list in its settings`
27063
27515
  };
27064
27516
  }
27065
- let schema2 = context.schemas[identifier];
27517
+ const root2 = context.schemas[identifier];
27518
+ let schema2 = root2;
27066
27519
  for (const key of keys) {
27067
- const properties = typeof schema2 === "object" ? schema2.properties : void 0;
27520
+ const properties = typeof schema2 === "object" && root2 ? dereference(root2, schema2).properties : void 0;
27068
27521
  schema2 = properties?.[key];
27069
- if (typeof schema2 !== "object") {
27522
+ if (typeof schema2 !== "object" || !root2) {
27070
27523
  return { error: `"${path3}" names no property of settings "${identifier}"` };
27071
27524
  }
27072
27525
  }
27073
- return { schema: schema2 };
27526
+ return { schema: root2 ? dereference(root2, schema2) : schema2 };
27074
27527
  }
27075
27528
  function literalError(path3, literal, schema2) {
27076
27529
  const types = typesOf2(schema2);
@@ -27136,7 +27589,8 @@ function validateGuideSettings(chapters, context) {
27136
27589
  );
27137
27590
  continue;
27138
27591
  }
27139
- used.add(reference.path.split(".")[0]);
27592
+ const identifier = parseSettingPath(reference.path)?.identifier;
27593
+ if (identifier !== void 0) used.add(identifier);
27140
27594
  const property = propertyAt(reference.path, context);
27141
27595
  if ("error" in property) {
27142
27596
  errors.push(`${where3}: ${directive2} ${property.error}`);
@@ -27869,8 +28323,8 @@ function endpointSchemaErrors(endpoint) {
27869
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`
27870
28324
  );
27871
28325
  }
27872
- for (const [key, child] of Object.entries(node2.properties ?? {})) {
27873
- visit2(child, `${path3}/${key}`);
28326
+ for (const { step, schema: child } of memberDeclarations(node2)) {
28327
+ visit2(child, `${path3}/${step}`);
27874
28328
  }
27875
28329
  if (node2.items && !Array.isArray(node2.items)) visit2(node2.items, `${path3}/items`);
27876
28330
  };
@@ -27978,7 +28432,7 @@ function validateCapabilityScopes(game, engines, config) {
27978
28432
  }
27979
28433
  if (!isSharedState) {
27980
28434
  const referenced = /* @__PURE__ */ new Map();
27981
- const collect2 = (label4, definition3) => {
28435
+ const collect = (label4, definition3) => {
27982
28436
  for (const capabilityId of [
27983
28437
  ...definition3.reads ?? [],
27984
28438
  ...definition3.writes ?? []
@@ -27989,10 +28443,10 @@ function validateCapabilityScopes(game, engines, config) {
27989
28443
  }
27990
28444
  };
27991
28445
  for (const engine of engines) {
27992
- collect2("engine", engine.definition);
28446
+ collect("engine", engine.definition);
27993
28447
  }
27994
28448
  if (config.ui) {
27995
- collect2("user interface", config.ui.definition);
28449
+ collect("user interface", config.ui.definition);
27996
28450
  }
27997
28451
  for (const [capId, referencedBy] of referenced) {
27998
28452
  errors.push(
@@ -28380,16 +28834,16 @@ function validateSchemaDefaults(label4, definition3) {
28380
28834
  function descriptor(entry) {
28381
28835
  return entry;
28382
28836
  }
28383
- var named = (resource) => resource.definition.identifier;
28837
+ var named2 = (resource) => resource.definition.identifier;
28384
28838
  var writesOf = (resource) => resource.definition.writes ?? [];
28385
28839
  function slot(resource) {
28386
28840
  return resource ? [resource] : [];
28387
28841
  }
28388
28842
  function packageFiles(packagePath, scenarioRoot) {
28389
28843
  return async (reference) => {
28844
+ if (!reference.startsWith("shared:") && !reference.startsWith("asset:")) return void 0;
28390
28845
  try {
28391
- 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;
28392
- return asset && { mimeType: asset.mimeType, size: asset.data.length };
28846
+ return await describeAssetByReference(packagePath, scenarioRoot, reference);
28393
28847
  } catch {
28394
28848
  return void 0;
28395
28849
  }
@@ -28404,6 +28858,19 @@ function schemaDefaults2(type) {
28404
28858
  )
28405
28859
  });
28406
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
+ }
28407
28874
  function readsWritten(type) {
28408
28875
  const label4 = getResourceMeta(type).label;
28409
28876
  return (resource, context) => {
@@ -28454,12 +28921,13 @@ var VALIDATION_DESCRIPTORS = [
28454
28921
  descriptor({
28455
28922
  type: "capability",
28456
28923
  resources: (config) => config.capabilities ?? [],
28457
- identify: named,
28924
+ identify: named2,
28458
28925
  checks: [
28459
28926
  (capability, context) => ({
28460
28927
  errors: validateTsTypes([capability], context.workingDir)
28461
28928
  }),
28462
- schemaDefaults2("capability")
28929
+ schemaDefaults2("capability"),
28930
+ localRefs("capability")
28463
28931
  ]
28464
28932
  }),
28465
28933
  // The built-in `game` resource's defaults are the manifest's own values,
@@ -28469,9 +28937,16 @@ var VALIDATION_DESCRIPTORS = [
28469
28937
  resources: (config) => (config.settings ?? []).filter(
28470
28938
  (settings) => settings.definition.identifier !== GAME_SETTINGS
28471
28939
  ),
28472
- identify: named,
28940
+ identify: named2,
28473
28941
  checks: [
28474
28942
  schemaDefaults2("settings"),
28943
+ localRefs("settings"),
28944
+ // A lock inside a list's items or a map's entries keeps nothing (§6.1a).
28945
+ (settings) => ({
28946
+ errors: unenforceableLocks(settings.definition.settingsSchema).map(
28947
+ (lock) => unenforceableLockMessage(settings.definition.identifier, lock)
28948
+ )
28949
+ }),
28475
28950
  // What a file setting expects, and the files its defaults name (§6.1a).
28476
28951
  (settings) => ({
28477
28952
  errors: fileSettingDeclarationErrors(
@@ -28502,7 +28977,7 @@ var VALIDATION_DESCRIPTORS = [
28502
28977
  descriptor({
28503
28978
  type: "engine",
28504
28979
  resources: (config) => slot(config.engine),
28505
- identify: named,
28980
+ identify: named2,
28506
28981
  writer: writesOf,
28507
28982
  checks: [
28508
28983
  (engine, context) => validateEngine(engine, context.config),
@@ -28514,7 +28989,7 @@ var VALIDATION_DESCRIPTORS = [
28514
28989
  descriptor({
28515
28990
  type: "ui",
28516
28991
  resources: (config) => slot(config.ui),
28517
- identify: named,
28992
+ identify: named2,
28518
28993
  writer: writesOf,
28519
28994
  checks: [userInterfaceReferences, uiFiles, schemaDefaults2("ui"), readsWritten("ui")]
28520
28995
  }),
@@ -28522,19 +28997,19 @@ var VALIDATION_DESCRIPTORS = [
28522
28997
  descriptor({
28523
28998
  type: "setup",
28524
28999
  resources: (config) => slot(config.setup),
28525
- identify: named,
29000
+ identify: named2,
28526
29001
  checks: [uiFiles]
28527
29002
  }),
28528
29003
  descriptor({
28529
29004
  type: "scenario_editor",
28530
29005
  resources: (config) => slot(config.scenario_editor),
28531
- identify: named,
29006
+ identify: named2,
28532
29007
  checks: [uiFiles]
28533
29008
  }),
28534
29009
  descriptor({
28535
29010
  type: "tick_controller",
28536
29011
  resources: (config) => slot(config.tick_controller),
28537
- identify: named,
29012
+ identify: named2,
28538
29013
  checks: [
28539
29014
  (tc, context) => validateTickController(tc, context.config),
28540
29015
  schemaDefaults2("tick_controller"),
@@ -28544,7 +29019,7 @@ var VALIDATION_DESCRIPTORS = [
28544
29019
  descriptor({
28545
29020
  type: "hook",
28546
29021
  resources: (config) => config.hooks ?? [],
28547
- identify: named,
29022
+ identify: named2,
28548
29023
  writer: writesOf,
28549
29024
  checks: [
28550
29025
  (hook, context) => validateHook(hook, context.config),
@@ -28555,7 +29030,7 @@ var VALIDATION_DESCRIPTORS = [
28555
29030
  descriptor({
28556
29031
  type: "validator",
28557
29032
  resources: (config) => config.validators ?? [],
28558
- identify: named,
29033
+ identify: named2,
28559
29034
  checks: [
28560
29035
  (validator, context) => validateValidator(validator, context.config),
28561
29036
  schemaDefaults2("validator"),
@@ -28565,7 +29040,7 @@ var VALIDATION_DESCRIPTORS = [
28565
29040
  descriptor({
28566
29041
  type: "endpoint",
28567
29042
  resources: (config) => config.endpoints ?? [],
28568
- identify: named,
29043
+ identify: named2,
28569
29044
  checks: [
28570
29045
  (endpoint, context) => validateEndpoint(endpoint, context.config),
28571
29046
  (endpoint, context) => validateEndpointFiles(endpoint, context.workingDir),
@@ -28576,7 +29051,7 @@ var VALIDATION_DESCRIPTORS = [
28576
29051
  descriptor({
28577
29052
  type: "session",
28578
29053
  resources: (config) => slot(config.session),
28579
- identify: named,
29054
+ identify: named2,
28580
29055
  writer: writesOf,
28581
29056
  checks: [
28582
29057
  userInterfaceReferences,
@@ -28588,7 +29063,7 @@ var VALIDATION_DESCRIPTORS = [
28588
29063
  descriptor({
28589
29064
  type: "waiting_room",
28590
29065
  resources: (config) => slot(config.waiting_room),
28591
- identify: named,
29066
+ identify: named2,
28592
29067
  checks: [
28593
29068
  userInterfaceReferences,
28594
29069
  uiFiles,
@@ -28599,7 +29074,7 @@ var VALIDATION_DESCRIPTORS = [
28599
29074
  descriptor({
28600
29075
  type: "presentation",
28601
29076
  resources: (config) => slot(config.presentation),
28602
- identify: named,
29077
+ identify: named2,
28603
29078
  checks: [userInterfaceReferences, uiFiles]
28604
29079
  }),
28605
29080
  // Composition, settings, locales and roles. A game wires whatever its
@@ -28608,7 +29083,7 @@ var VALIDATION_DESCRIPTORS = [
28608
29083
  descriptor({
28609
29084
  type: "game",
28610
29085
  resources: (config) => slot(config.game),
28611
- identify: named,
29086
+ identify: named2,
28612
29087
  checks: [
28613
29088
  (game, context) => validateGame(game, context.config),
28614
29089
  // With no default, a session can run on no scenario at all, so the
@@ -28665,7 +29140,7 @@ var VALIDATION_DESCRIPTORS = [
28665
29140
  descriptor({
28666
29141
  type: "scenario",
28667
29142
  resources: (config) => config.scenarios ?? [],
28668
- identify: named,
29143
+ identify: named2,
28669
29144
  checks: [
28670
29145
  // The same check `ConfigResolver.assertLayeredSettingsValid` runs at
28671
29146
  // session start (#371). Without it the build was green on a
@@ -28710,11 +29185,17 @@ var VALIDATION_DESCRIPTORS = [
28710
29185
  // (§15.8).
28711
29186
  async (scenario, context) => {
28712
29187
  const identifier = scenario.definition.identifier;
29188
+ const packagePath = dirname6(context.configPath);
28713
29189
  return scenarioRefusals(
28714
29190
  await runScenarioGates({
28715
- packagePath: dirname6(context.configPath),
29191
+ packagePath,
28716
29192
  config: context.config,
28717
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
+ },
28718
29199
  scenarioSettings: scenario.definition.settings ?? {}
28719
29200
  }),
28720
29201
  `Scenario "${identifier}"`,
@@ -28729,7 +29210,7 @@ var VALIDATION_DESCRIPTORS = [
28729
29210
  descriptor({
28730
29211
  type: "guide",
28731
29212
  resources: (config) => slot(config.guide),
28732
- identify: named,
29213
+ identify: named2,
28733
29214
  checks: [
28734
29215
  (guide, context) => validateFacilitatorGuideContent({
28735
29216
  definition: guide.definition,
@@ -28767,7 +29248,7 @@ async function validateLoadedPackage(config, options) {
28767
29248
  configPath: options.configPath,
28768
29249
  workingDir: options.workingDir,
28769
29250
  writtenInPackage,
28770
- capabilityIds: new Set((config.capabilities ?? []).map(named)),
29251
+ capabilityIds: new Set((config.capabilities ?? []).map(named2)),
28771
29252
  logicLoader: new LogicLoader(dirname6(options.configPath), {
28772
29253
  transpile: Transpile,
28773
29254
  fs: { existsSync: existsSync13, readFile: readFile7 }
@@ -29599,7 +30080,14 @@ async function saveSessionScenario(session, packagePath, request) {
29599
30080
  packagePath,
29600
30081
  config,
29601
30082
  scenarioSettings: settings,
29602
- 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
+ }
29603
30091
  });
29604
30092
  if (problems.length > 0) {
29605
30093
  throw new SaveScenarioError("denied", describeScenarioProblems(problems).join("\n"));
@@ -29722,10 +30210,11 @@ function themeMessages(theme) {
29722
30210
  { type: "themePreferenceChanged", preference: theme.preference }
29723
30211
  ];
29724
30212
  }
29725
- function assetUrls(assetOrigin) {
30213
+ function assetUrls(assetOrigin, editing) {
30214
+ const scenarioAssets = editing === void 0 ? "scenario/" : editing.scenario === null ? "no-scenario/" : `scenarios/${encodeURIComponent(editing.scenario)}/`;
29726
30215
  return {
29727
30216
  blobPrefix: `${assetOrigin}/assets/blobs/`,
29728
- scenarioAssetPrefix: `${assetOrigin}/assets/scenario/`,
30217
+ scenarioAssetPrefix: `${assetOrigin}/assets/${scenarioAssets}`,
29729
30218
  sharedAssetPrefix: `${assetOrigin}/assets/shared/`,
29730
30219
  assetAuthRedeemUrl: `${assetOrigin}/assets/auth/redeem`
29731
30220
  };
@@ -29751,7 +30240,13 @@ function buildBatch(options) {
29751
30240
  const { surface, state: state2, theme, origin, assetOrigin } = options;
29752
30241
  const common = [
29753
30242
  { type: "setLocale", payload: { locale: state2.session.locale } },
29754
- { type: "setAssetUrls", payload: assetUrls(assetOrigin ?? origin) },
30243
+ {
30244
+ type: "setAssetUrls",
30245
+ payload: assetUrls(
30246
+ assetOrigin ?? origin,
30247
+ surface.kind === "scenario-editor" ? { scenario: options.viewer.scenario ?? null } : void 0
30248
+ )
30249
+ },
29755
30250
  ...theme ? themeMessages(theme) : []
29756
30251
  ];
29757
30252
  switch (surface.kind) {
@@ -30210,12 +30705,16 @@ var ASSET_PATHS = {
30210
30705
  "/api": {
30211
30706
  blob: "/api/blobs/:blobId",
30212
30707
  scenario: "/api/scenario/assets/*path",
30708
+ editedScenario: "/api/scenarios/:scenario/assets/*path",
30709
+ noScenario: "/api/no-scenario/assets/*path",
30213
30710
  shared: "/api/shared/assets/*path",
30214
30711
  redeem: "/api/asset-auth/redeem"
30215
30712
  },
30216
30713
  "/assets": {
30217
30714
  blob: "/assets/blobs/:blobId",
30218
30715
  scenario: "/assets/scenario/*path",
30716
+ editedScenario: "/assets/scenarios/:scenario/*path",
30717
+ noScenario: "/assets/no-scenario/*path",
30219
30718
  shared: "/assets/shared/*path",
30220
30719
  redeem: "/assets/auth/redeem"
30221
30720
  }
@@ -30233,15 +30732,17 @@ function registerAssetRoutes(app, deps, prefix) {
30233
30732
  res.json({ ok: true });
30234
30733
  });
30235
30734
  app.get(paths.blob, async (req, res) => {
30735
+ let blob;
30236
30736
  try {
30237
- const blob = await readBlob(packagePath, req.params.blobId);
30238
- res.setHeader("Content-Type", blob.mimeType);
30239
- res.setHeader("X-Asset-Name", encodeURIComponent(blob.name));
30240
- res.setHeader("Access-Control-Expose-Headers", "X-Asset-Name");
30241
- res.send(blob.data);
30737
+ blob = await readBlob(packagePath, req.params.blobId);
30242
30738
  } catch {
30243
30739
  res.status(404).send("Blob not found");
30740
+ return;
30244
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);
30245
30746
  });
30246
30747
  app.get(paths.scenario, (req, res) => {
30247
30748
  const scenario = session.activeScenario();
@@ -30249,9 +30750,23 @@ function registerAssetRoutes(app, deps, prefix) {
30249
30750
  res.status(404).send("No active scenario");
30250
30751
  return;
30251
30752
  }
30252
- const root2 = isAbsolute11(scenario.rootDirectory) ? scenario.rootDirectory : resolve11(packagePath, scenario.rootDirectory);
30253
- 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));
30254
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
+ }
30255
30770
  app.get(paths.shared, (req, res) => {
30256
30771
  serveAsset(req, res, resolve11(packagePath, "shared-assets"));
30257
30772
  });
@@ -30282,10 +30797,27 @@ function serveAsset(req, res, root2) {
30282
30797
  res.status(404).send("Asset not found");
30283
30798
  return;
30284
30799
  }
30800
+ res.setHeader("Content-Type", mediaTypeOf(resolved));
30285
30801
  res.setHeader("X-Asset-Name", encodeURIComponent(assetPath.split("/").pop() ?? assetPath));
30286
30802
  res.setHeader("Access-Control-Expose-Headers", "X-Asset-Name");
30287
30803
  res.sendFile(normalize3(assetPath), { root: root2 });
30288
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
+ }
30289
30821
 
30290
30822
  // cli/dev/view/commands.ts
30291
30823
  var FRAME_COMMANDS = {