castle-web-cli 0.4.208 → 0.4.210

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 (56) hide show
  1. package/dist/api.d.ts +5 -0
  2. package/dist/castle-host/host.js +234 -0
  3. package/dist/castleJson.d.ts +4 -0
  4. package/dist/castleJson.js +3 -1
  5. package/dist/devSessionServer.js +1 -0
  6. package/dist/editorConfig.d.ts +12 -0
  7. package/dist/editorConfig.js +72 -6
  8. package/dist/init.js +1 -1
  9. package/dist/modulePreload.d.ts +14 -0
  10. package/dist/modulePreload.js +150 -0
  11. package/dist/native/loop.js +1 -1
  12. package/dist/native/playtest-executor.js +36 -4
  13. package/dist/native/playtest-remote.d.ts +1 -0
  14. package/dist/native/playtest-remote.js +61 -5
  15. package/dist/native/playtest.d.ts +35 -2
  16. package/dist/native/playtest.js +162 -18
  17. package/dist/platformDoc.d.ts +1 -0
  18. package/dist/platformDoc.js +24 -3
  19. package/dist/playUrl.d.ts +3 -0
  20. package/dist/playUrl.js +12 -0
  21. package/dist/save-deck.js +1 -0
  22. package/dist/serve.js +2 -0
  23. package/dist/shell/assets/{index-b_bebkRb.css → index-BCrgYh76.css} +1 -1
  24. package/dist/shell/assets/{index-C6SXXPwm.js → index-DzLbNBc7.js} +68 -68
  25. package/dist/shell/index.html +2 -2
  26. package/kits/base/CLAUDE.md +1 -0
  27. package/kits/base/castle.json +1 -1
  28. package/kits/base/sdk/README.md +70 -7
  29. package/kits/base/sdk/castle.d.ts +1 -0
  30. package/kits/base/sdk/commands.d.ts +78 -0
  31. package/kits/base/sdk/commands.js +25 -0
  32. package/kits/base/sdk/multiplayer.d.ts +3 -0
  33. package/kits/base/sdk/multiplayer.js +13 -0
  34. package/kits/base/sdk/multiplayerVoice.d.ts +91 -0
  35. package/kits/base/sdk/multiplayerVoice.js +424 -0
  36. package/kits/base/sdk/transport.d.ts +2 -1
  37. package/kits/base/sdk/transport.js +15 -1
  38. package/kits/multiplayer-2d/castle.json +2 -2
  39. package/kits/multiplayer-2d/code/systems/multiplayer.js +7 -1
  40. package/kits/multiplayer-3d/castle.json +2 -2
  41. package/kits/multiplayer-3d/code/systems/multiplayer.js +8 -4
  42. package/kits/physics-2d/castle.json +1 -1
  43. package/kits/physics-2d/editors/SceneEditor.jsx +18 -4
  44. package/kits/physics-2d/systems/media.js +3 -5
  45. package/kits/physics-3d/castle.json +2 -2
  46. package/kits/physics-3d/engine3d/PxModelEditor.jsx +2 -2
  47. package/kits/physics-3d/engine3d/pxmodel.js +7 -0
  48. package/kits/real-time/CLAUDE.md +3 -0
  49. package/kits/real-time/castle.json +1 -1
  50. package/kits/real-time/code/client/connection.js +17 -2
  51. package/kits/real-time/code/client/gameHooks.js +5 -0
  52. package/kits/real-time/code/client/joinOverlay.js +23 -5
  53. package/kits/real-time/code/client/messages.js +4 -0
  54. package/kits/real-time/code/server/persist.js +19 -10
  55. package/kits/real-time/code/server/session.js +19 -0
  56. package/package.json +2 -2
package/dist/api.d.ts CHANGED
@@ -21,6 +21,8 @@ export type BrowserOperation = {
21
21
  durationMs?: number;
22
22
  }>;
23
23
  screenshots: number[];
24
+ input?: 'touch';
25
+ playFile?: string;
24
26
  } | {
25
27
  kind: 'cover';
26
28
  };
@@ -142,6 +144,9 @@ export declare function createCauldronServerBundleUploadConfig(deckId: string):
142
144
  export interface CauldronServerConfig {
143
145
  tickRate: number;
144
146
  maxPlayers: number;
147
+ voice: {
148
+ enabled: boolean;
149
+ };
145
150
  }
146
151
  export interface CauldronServerBundleResult {
147
152
  deckId: string;
@@ -40,6 +40,11 @@ const COMMAND_NAMES = [
40
40
  "portal.info",
41
41
  "haptics.play",
42
42
  "multiplayer.getSession",
43
+ "voice.getState",
44
+ "voice.requestJoin",
45
+ "voice.leave",
46
+ "voice.setMix",
47
+ "voice.setSpatial",
43
48
  "characters.open",
44
49
  "characters.send",
45
50
  "characters.status",
@@ -79,6 +84,29 @@ function isCommandName(value) {
79
84
  function isPlatformCommand(command) {
80
85
  return PLATFORM_COMMAND_NAMES.includes(command);
81
86
  }
87
+ // What a host posts to the deck (web: postMessage to the iframe; mobile:
88
+ // window.__castleSdkHost.receive) for a voice state change or a new set of speakers.
89
+ export function voiceEventEnvelope(event) {
90
+ return { castleSdk: 1, voice: event };
91
+ }
92
+ const CAULDRON_VOICE_TOKEN_QUERY = `query CastleCauldronVoiceToken($sessionId: ID!, $deckId: ID!, $env: String) {
93
+ getCauldronVoiceToken(sessionId: $sessionId, deckId: $deckId, env: $env) {
94
+ available
95
+ reason
96
+ url
97
+ token
98
+ roomName
99
+ blockedUserIds
100
+ }
101
+ }`;
102
+ // For a host's voice implementation: a LiveKit token for the session's room, issued
103
+ // only if the signed-in player may be in it. Tokens last about a minute and only gate
104
+ // the join, so fetch one right before connecting.
105
+ export async function fetchCauldronVoiceToken(gql, ctx, sessionId, env) {
106
+ const deckId = requireDeckId(ctx, "voice.requestJoin");
107
+ const data = await graphql(gql, CAULDRON_VOICE_TOKEN_QUERY, { sessionId, deckId, env: env ?? null }, "voice.requestJoin");
108
+ return data.getCauldronVoiceToken;
109
+ }
82
110
  class HostCommandError extends Error {
83
111
  code;
84
112
  command;
@@ -151,6 +179,16 @@ function runCommand(ctx, command, params, caps, options) {
151
179
  return passHas(ctx, params, caps);
152
180
  case "multiplayer.getSession":
153
181
  return multiplayerGetSession(ctx, params, caps);
182
+ case "voice.getState":
183
+ return voiceGetState(ctx, params, caps);
184
+ case "voice.requestJoin":
185
+ return voiceRequestJoin(ctx, params, caps, options.signal);
186
+ case "voice.leave":
187
+ return voiceLeave(ctx, params, caps);
188
+ case "voice.setSpatial":
189
+ return Promise.resolve(voiceSetSpatial(ctx, params, caps));
190
+ case "voice.setMix":
191
+ return Promise.resolve(voiceSetMix(ctx, params, caps));
154
192
  case "characters.open":
155
193
  return charactersOpen(ctx, params, gql);
156
194
  case "characters.send":
@@ -265,6 +303,202 @@ async function passHas(ctx, params, caps) {
265
303
  const match = (data.passesForDeck ?? []).find((p) => p?.passId === passId);
266
304
  return { hasPass: match?.isActive === true };
267
305
  }
306
+ // A session id is ghost's: a deck id plus a short suffix, or a nanoid.
307
+ const VOICE_SESSION_ID_MAX_LENGTH = 256;
308
+ // A room holds at most 24 players; anything past this is a confused deck.
309
+ const VOICE_MIX_MAX_ENTRIES = 64;
310
+ const VOICE_JOIN_STATUSES = ["joined", "declined", "unavailable"];
311
+ // After the player declines, a deck asking again within this long gets "declined"
312
+ // without another prompt, so a deck can't nag.
313
+ export const VOICE_DECLINE_COOLDOWN_MS = 10_000;
314
+ // Keys a deck could use to reach Object.prototype through a plain object.
315
+ const RESERVED_MIX_KEYS = new Set(["__proto__", "constructor", "prototype"]);
316
+ const voiceJoinsInFlight = new Map();
317
+ const voiceDeclinedAt = new Map();
318
+ const HOST_VOICE_STATES = ["unavailable", "off", "joining", "live"];
319
+ function voiceSessionId(params, command) {
320
+ const sessionId = asString(params.sessionId, "sessionId", command);
321
+ if (sessionId.length > VOICE_SESSION_ID_MAX_LENGTH) {
322
+ throw new HostCommandError("INVALID_ARGUMENT", `Castle command ${command} requires a valid sessionId.`, command);
323
+ }
324
+ return sessionId;
325
+ }
326
+ async function voiceGetState(ctx, params, caps) {
327
+ const sessionId = voiceSessionId(params, "voice.getState");
328
+ if (!caps.voice)
329
+ return { state: "unavailable" };
330
+ const state = await caps.voice.getState(sessionId, ctx);
331
+ return { state: HOST_VOICE_STATES.includes(state) ? state : "unavailable" };
332
+ }
333
+ async function voiceRequestJoin(ctx, params, caps, signal) {
334
+ const sessionId = voiceSessionId(params, "voice.requestJoin");
335
+ const voice = caps.voice;
336
+ if (!voice)
337
+ return { status: "unavailable" };
338
+ const key = `${ctx.deckId ?? ""}\u0000${sessionId}`;
339
+ const declinedAt = voiceDeclinedAt.get(key);
340
+ if (declinedAt !== undefined) {
341
+ if (Date.now() - declinedAt < VOICE_DECLINE_COOLDOWN_MS)
342
+ return { status: "declined" };
343
+ voiceDeclinedAt.delete(key);
344
+ }
345
+ let inFlight = voiceJoinsInFlight.get(key);
346
+ while (inFlight?.signal?.aborted) {
347
+ // A withdrawn prompt the host hasn't closed yet: this is a new ask, so let the
348
+ // old one finish and prompt afresh rather than hand back its "unavailable".
349
+ await inFlight.request.catch(() => undefined);
350
+ if (signal?.aborted)
351
+ return { status: "unavailable" };
352
+ inFlight = voiceJoinsInFlight.get(key);
353
+ }
354
+ if (inFlight)
355
+ return inFlight.request;
356
+ const request = (async () => {
357
+ const outcome = await voice.requestJoin(sessionId, ctx, signal);
358
+ if (signal?.aborted) {
359
+ // The deck withdrew the request while the player was choosing.
360
+ if (outcome === "joined")
361
+ await voice.leave(sessionId, ctx);
362
+ return { status: "unavailable" };
363
+ }
364
+ const status = VOICE_JOIN_STATUSES.includes(outcome)
365
+ ? outcome
366
+ : "declined";
367
+ if (status === "declined") {
368
+ pruneVoiceDeclines();
369
+ voiceDeclinedAt.set(key, Date.now());
370
+ }
371
+ else {
372
+ voiceDeclinedAt.delete(key);
373
+ }
374
+ return { status };
375
+ })().finally(() => {
376
+ if (voiceJoinsInFlight.get(key)?.request === request)
377
+ voiceJoinsInFlight.delete(key);
378
+ });
379
+ voiceJoinsInFlight.set(key, { request, signal });
380
+ return request;
381
+ }
382
+ function pruneVoiceDeclines() {
383
+ const now = Date.now();
384
+ for (const [key, declinedAt] of voiceDeclinedAt) {
385
+ if (now - declinedAt >= VOICE_DECLINE_COOLDOWN_MS)
386
+ voiceDeclinedAt.delete(key);
387
+ }
388
+ }
389
+ async function voiceLeave(ctx, params, caps) {
390
+ const sessionId = voiceSessionId(params, "voice.leave");
391
+ await caps.voice?.leave(sessionId, ctx);
392
+ return { ok: true };
393
+ }
394
+ function voiceSetMix(ctx, params, caps) {
395
+ const sessionId = voiceSessionId(params, "voice.setMix");
396
+ const raw = params.mix;
397
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
398
+ throw new HostCommandError("INVALID_ARGUMENT", "Castle command voice.setMix requires mix.", "voice.setMix");
399
+ }
400
+ const entries = Object.entries(raw).slice(0, VOICE_MIX_MAX_ENTRIES);
401
+ const mix = Object.create(null);
402
+ for (const [userId, entry] of entries) {
403
+ if (!userId || userId.length > 64 || RESERVED_MIX_KEYS.has(userId))
404
+ continue;
405
+ if (typeof entry !== "object" || entry === null)
406
+ continue;
407
+ const record = entry;
408
+ mix[userId] = {
409
+ gain: finiteOr(record.gain, 1, 0, 1),
410
+ pan: finiteOr(record.pan, 0, -1, 1),
411
+ };
412
+ }
413
+ if (caps.voice && Object.keys(mix).length > 0)
414
+ caps.voice.setMix(sessionId, mix, ctx);
415
+ return { ok: true };
416
+ }
417
+ // World coordinates past this are a confused deck, not a big world.
418
+ const VOICE_COORDINATE_LIMIT = 1_000_000;
419
+ const VOICE_DISTANCE_MODELS = ["linear", "inverse", "exponential"];
420
+ function voiceVector(value) {
421
+ if (!Array.isArray(value) || value.length !== 3)
422
+ return null;
423
+ const vector = value.map((component) => typeof component === "number" && Number.isFinite(component)
424
+ ? Math.min(VOICE_COORDINATE_LIMIT, Math.max(-VOICE_COORDINATE_LIMIT, component))
425
+ : NaN);
426
+ return vector.every((component) => !Number.isNaN(component))
427
+ ? vector
428
+ : null;
429
+ }
430
+ function isZero(vector) {
431
+ return vector[0] === 0 && vector[1] === 0 && vector[2] === 0;
432
+ }
433
+ // A camera looking straight down (a top-down deck) with the default y-up has forward
434
+ // parallel to up, which leaves no left or right: every voice would play centered.
435
+ // Swap in an up that is perpendicular, so the top of the screen (-z) stays "ahead".
436
+ function perpendicularUp(forward, up) {
437
+ const cross = [
438
+ forward[1] * up[2] - forward[2] * up[1],
439
+ forward[2] * up[0] - forward[0] * up[2],
440
+ forward[0] * up[1] - forward[1] * up[0],
441
+ ];
442
+ const crossLength = Math.hypot(cross[0], cross[1], cross[2]);
443
+ const scale = Math.hypot(...forward) * Math.hypot(...up);
444
+ if (crossLength > 1e-6 * scale)
445
+ return up;
446
+ return Math.abs(forward[2]) < 0.9 * Math.hypot(...forward) ? [0, 0, -1] : [0, 1, 0];
447
+ }
448
+ function voiceSetSpatial(ctx, params, caps) {
449
+ const sessionId = voiceSessionId(params, "voice.setSpatial");
450
+ const update = {};
451
+ const listener = params.listener;
452
+ if (listener && typeof listener === "object") {
453
+ const position = voiceVector(listener.position);
454
+ const forward = voiceVector(listener.forward);
455
+ const up = listener.up === undefined ? [0, 1, 0] : voiceVector(listener.up);
456
+ // A zero forward or up has no direction to face.
457
+ if (position && forward && up && !isZero(forward) && !isZero(up)) {
458
+ update.listener = { position, forward, up: perpendicularUp(forward, up) };
459
+ }
460
+ }
461
+ const rawPositions = params.positions;
462
+ if (rawPositions && typeof rawPositions === "object" && !Array.isArray(rawPositions)) {
463
+ const positions = Object.create(null);
464
+ const entries = Object.entries(rawPositions).slice(0, VOICE_MIX_MAX_ENTRIES);
465
+ for (const [userId, value] of entries) {
466
+ if (!userId || userId.length > 64 || RESERVED_MIX_KEYS.has(userId))
467
+ continue;
468
+ if (value === null) {
469
+ positions[userId] = null;
470
+ continue;
471
+ }
472
+ const position = voiceVector(value);
473
+ if (position)
474
+ positions[userId] = position;
475
+ }
476
+ if (Object.keys(positions).length > 0)
477
+ update.positions = positions;
478
+ }
479
+ const options = params.options;
480
+ if (options && typeof options === "object") {
481
+ const model = VOICE_DISTANCE_MODELS.includes(options.distanceModel)
482
+ ? options.distanceModel
483
+ : "inverse";
484
+ const refDistance = finiteOr(options.refDistance, 1, 0.01, VOICE_COORDINATE_LIMIT);
485
+ update.options = {
486
+ distanceModel: model,
487
+ refDistance,
488
+ maxDistance: Math.max(refDistance, finiteOr(options.maxDistance, 100, 0.01, VOICE_COORDINATE_LIMIT)),
489
+ rolloff: finiteOr(options.rolloff, 1, 0, 100),
490
+ };
491
+ }
492
+ if (caps.voice?.setSpatial && (update.listener || update.positions || update.options)) {
493
+ caps.voice.setSpatial(sessionId, update, ctx);
494
+ }
495
+ return { ok: true };
496
+ }
497
+ function finiteOr(value, fallback, min, max) {
498
+ return typeof value === "number" && Number.isFinite(value)
499
+ ? Math.min(max, Math.max(min, value))
500
+ : fallback;
501
+ }
268
502
  async function passesOffer(ctx, params, caps) {
269
503
  const passId = asString(params.passId, "passId", "pass.offer");
270
504
  // Hosts without bricks support (dev CLI — no handler at all) get a normalized
@@ -27,6 +27,9 @@ export interface CastleJson {
27
27
  tickRate?: number;
28
28
  maxPlayers?: number;
29
29
  };
30
+ voice?: {
31
+ enabled?: boolean;
32
+ };
30
33
  importWhenRemixed?: boolean;
31
34
  starterScene?: string;
32
35
  [key: string]: unknown;
@@ -40,6 +43,7 @@ export interface ResolvedServerConfig {
40
43
  entry: string;
41
44
  tickRate: number;
42
45
  maxPlayers: number;
46
+ voiceEnabled: boolean;
43
47
  }
44
48
  export declare function resolveServerConfig(dir: string): ResolvedServerConfig | null;
45
49
  export declare function deckStarterScene(dir: string): string;
@@ -40,7 +40,8 @@ const DEFAULT_SERVER_ENTRIES = [
40
40
  'code/server/index.mjs',
41
41
  ];
42
42
  export function resolveServerConfig(dir) {
43
- const server = readCastleJson(dir)?.server;
43
+ const castleJson = readCastleJson(dir);
44
+ const server = castleJson?.server;
44
45
  const declared = typeof server?.main === 'string' ? server.main.trim() : '';
45
46
  const entry = declared ||
46
47
  DEFAULT_SERVER_ENTRIES.find((candidate) => fs.existsSync(path.join(dir, candidate)));
@@ -50,6 +51,7 @@ export function resolveServerConfig(dir) {
50
51
  entry,
51
52
  tickRate: clampNumber(server?.tickRate, DEFAULT_SERVER_TICK_RATE, 0, SERVER_TICK_RATE_CAP),
52
53
  maxPlayers: Math.floor(clampNumber(server?.maxPlayers, DEFAULT_SERVER_MAX_PLAYERS, 1, SERVER_MAX_PLAYERS_CAP)),
54
+ voiceEnabled: castleJson?.voice?.enabled !== false,
53
55
  };
54
56
  }
55
57
  function isSafeServerEntry(dir, entry) {
@@ -543,6 +543,7 @@ class DevSessionServerImpl {
543
543
  entry: 'server/index.js',
544
544
  tickRate: 20,
545
545
  maxPlayers: 8,
546
+ voiceEnabled: true,
546
547
  });
547
548
  }
548
549
  sendPlatform(frame) {
@@ -33,7 +33,19 @@ export interface EditorConfig {
33
33
  fileTypes?: FileTypeConfig[];
34
34
  extensions?: string[];
35
35
  defaultPlayFile?: string;
36
+ defaultPlayFileRefused?: {
37
+ value: string;
38
+ reason: string;
39
+ };
36
40
  }
41
+ export declare const MAX_PLAY_FILE_LENGTH = 512;
42
+ export declare function normalizePlayFile(deckDir: string, raw: string): {
43
+ ok: true;
44
+ path: string;
45
+ } | {
46
+ ok: false;
47
+ reason: string;
48
+ };
37
49
  export declare function readEditorConfig(deckDir: string): EditorConfig;
38
50
  export declare function deckHidesFiles(deckDir: string): boolean;
39
51
  export declare function resolveFileTypes(deckDir: string): ResolvedFileType[] | null;
@@ -14,6 +14,7 @@
14
14
  // only. `defaultPlayFile` falls back to an import's when the deck names none --
15
15
  // see `importedDefaultPlayFile`.
16
16
  import * as fs from 'fs';
17
+ import * as os from 'os';
17
18
  import * as path from 'path';
18
19
  import { readCastleJson } from './castleJson.js';
19
20
  import { IMPORTS_DIR } from './imports.js';
@@ -24,6 +25,61 @@ export function dataModeOf(type) {
24
25
  return type.data;
25
26
  return null;
26
27
  }
28
+ // A play file as the Play panel, the playtest and the cloud browser worker all
29
+ // take it: a normalized deck-relative POSIX path. The worker and Ghost refuse
30
+ // anything else outright (castle-sandboxes/ghost-server validPlayFile), and a
31
+ // kit looks the file up by exact key, so a loose spelling is put in this form
32
+ // once, here, or refused with the reason.
33
+ export const MAX_PLAY_FILE_LENGTH = 512;
34
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
35
+ const within = (child, parent) => {
36
+ const rel = path.relative(parent, child);
37
+ return rel === '' || (!rel.startsWith(`..${path.sep}`) && rel !== '..' && !path.isAbsolute(rel));
38
+ };
39
+ // Directories an absolute declaration must not point into: the deck and the
40
+ // home dir, each as given and as its real path (/tmp vs /private/tmp). A home
41
+ // of `/` would claim every leading-slash path, so it is left out.
42
+ function filesystemRoots(deckRoot) {
43
+ const real = (dir) => {
44
+ try {
45
+ return fs.realpathSync(dir);
46
+ }
47
+ catch {
48
+ return dir;
49
+ }
50
+ };
51
+ const home = path.resolve(os.homedir());
52
+ const dirs = [deckRoot, real(deckRoot)];
53
+ if (home !== path.parse(home).root)
54
+ dirs.push(home, real(home));
55
+ return dirs.filter((dir) => dir !== path.parse(dir).root);
56
+ }
57
+ export function normalizePlayFile(deckDir, raw) {
58
+ const value = raw.trim();
59
+ if (!value)
60
+ return { ok: false, reason: 'it is empty' };
61
+ if ([...value].some((c) => c.charCodeAt(0) < 0x20 || c === '\u007f')) {
62
+ return { ok: false, reason: 'it contains a control character' };
63
+ }
64
+ if (value.includes('\\'))
65
+ return { ok: false, reason: 'it contains a backslash' };
66
+ if (LONE_SURROGATE.test(value))
67
+ return { ok: false, reason: 'it contains an unpaired surrogate' };
68
+ const root = path.resolve(deckDir);
69
+ if (path.isAbsolute(value) && filesystemRoots(root).some((dir) => within(value, dir))) {
70
+ return { ok: false, reason: 'it is an absolute filesystem path, not a path inside the deck' };
71
+ }
72
+ const inside = path.relative(root, path.resolve(root, value.replace(/^\/+/, '')));
73
+ if (!inside)
74
+ return { ok: false, reason: 'it names the deck folder, not a file' };
75
+ if (!within(path.join(root, inside), root))
76
+ return { ok: false, reason: 'it points outside the deck' };
77
+ const posix = inside.split(path.sep).join('/');
78
+ if (posix.length > MAX_PLAY_FILE_LENGTH) {
79
+ return { ok: false, reason: `it is longer than ${MAX_PLAY_FILE_LENGTH} characters` };
80
+ }
81
+ return { ok: true, path: posix };
82
+ }
27
83
  // An array with no usable entries stays an (empty) array rather than becoming
28
84
  // undefined: "I declare no file types" is a real answer, distinct from "I say
29
85
  // nothing about file types", and only the second one defers to the imports.
@@ -55,11 +111,20 @@ export function readEditorConfig(deckDir) {
55
111
  hiddenPaths: asStringArray(editor.hiddenPaths),
56
112
  fileTypes: asFileTypes(editor.fileTypes),
57
113
  extensions: asStringArray(editor.extensions) ?? asStringArray(data.editorExtensions),
58
- defaultPlayFile: typeof editor.defaultPlayFile === 'string'
59
- ? editor.defaultPlayFile
60
- : importedDefaultPlayFile(deckDir),
114
+ ...(typeof editor.defaultPlayFile === 'string'
115
+ ? ownDefaultPlayFile(deckDir, editor.defaultPlayFile)
116
+ : { defaultPlayFile: importedDefaultPlayFile(deckDir) }),
61
117
  };
62
118
  }
119
+ // An empty string keeps its old meaning, "no start file", with nothing refused.
120
+ function ownDefaultPlayFile(deckDir, raw) {
121
+ if (!raw.trim())
122
+ return {};
123
+ const normalized = normalizePlayFile(deckDir, raw);
124
+ return normalized.ok
125
+ ? { defaultPlayFile: normalized.path }
126
+ : { defaultPlayFileRefused: { value: raw, reason: normalized.reason } };
127
+ }
63
128
  // Which scene the play panel opens with, when the deck names none itself. Only a
64
129
  // scene kit has the concept, and a deck that imported one has its scenes without
65
130
  // having said so -- without this the panel loads the kit's runtime with no scene
@@ -74,10 +139,11 @@ function importedDefaultPlayFile(deckDir) {
74
139
  const declared = value && typeof value === 'object'
75
140
  ? value.defaultPlayFile
76
141
  : undefined;
77
- if (typeof declared !== 'string' || !declared.trim())
142
+ if (typeof declared !== 'string')
78
143
  continue;
79
- if (fs.existsSync(path.join(deckDir, declared.trim())))
80
- return declared.trim();
144
+ const normalized = normalizePlayFile(deckDir, declared);
145
+ if (normalized.ok && fs.existsSync(path.join(deckDir, normalized.path)))
146
+ return normalized.path;
81
147
  }
82
148
  return undefined;
83
149
  }
package/dist/init.js CHANGED
@@ -54,7 +54,7 @@ if (!(await mountEditorRoute())) startGame(initCard());
54
54
  // Registry version of castle-web-sdk to inject when scaffolding from a
55
55
  // globally-installed castle-web (not from inside the workspace). Bumped
56
56
  // alongside cli/sdk version bumps.
57
- const PUBLISHED_SDK_VERSION = '0.4.35';
57
+ const PUBLISHED_SDK_VERSION = '0.4.36';
58
58
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
59
59
  // face can ship without a cli release, and a caret range means an existing
60
60
  // deck's next install picks it up. Nothing here has to move when it does.
@@ -0,0 +1,14 @@
1
+ import type { EnvironmentModuleNode, Plugin } from 'vite';
2
+ export declare function isPreloadableModuleUrl(url: string): boolean;
3
+ export declare function moduleEntrySrcs(html: string): string[];
4
+ type PreloadGraph = {
5
+ transformRequest(url: string): Promise<unknown>;
6
+ getModuleByUrl(url: string): Promise<EnvironmentModuleNode | undefined>;
7
+ };
8
+ export declare function isStaticImportIn(code: string, url: string): boolean;
9
+ export declare function collectModulePreloads(graph: PreloadGraph, entries: string[], budgetMs?: number): Promise<string[]>;
10
+ export declare function modulePreloadPlugin(options: {
11
+ enabled: boolean;
12
+ budgetMs?: number;
13
+ }): Plugin;
14
+ export {};
@@ -0,0 +1,150 @@
1
+ // The dev server hands a deck's modules to the browser one file at a time, and
2
+ // the browser only learns a module's imports once that module has arrived. A
3
+ // kit deck is 150-300 modules deep in that chain, so on a phone every level
4
+ // costs a network round trip: physics-2d measured 1.5 s on localhost and 6.5 s
5
+ // at 150 ms RTT. Listing the whole static graph up front as modulepreload links
6
+ // lets the browser fetch it in parallel instead, while each module is still
7
+ // served, cached and executed exactly as before.
8
+ //
9
+ // Off unless CASTLE_MODULE_PRELOAD=1, so the sandbox image decides.
10
+ const DEFAULT_BUDGET_MS = 1500;
11
+ // Listed links, not walked modules: the walk itself is bounded by the budget.
12
+ const MAX_MODULES = 1000;
13
+ // Only plain script modules. Anything Vite serves under an `?import`, `?raw`,
14
+ // `?url` or `?worker` style query, and every non-script file (scenes, json,
15
+ // styles, assets), is left for the page to ask for itself: preloading a URL
16
+ // the page never imports would fetch twice, and preloading a non-module one
17
+ // would log a load error into the deck's console.
18
+ const SCRIPT_URL = /^\/(?!\/)[^?#]*\.(?:m?[jt]sx?)(?:\?v=[\w.-]+)?$/;
19
+ export function isPreloadableModuleUrl(url) {
20
+ return SCRIPT_URL.test(url);
21
+ }
22
+ // `<script type="module" src="/...">` entries of the page as Vite will serve it.
23
+ export function moduleEntrySrcs(html) {
24
+ const srcs = [];
25
+ for (const tag of html.match(/<script\b[^>]*>/gi) ?? []) {
26
+ if (!/\btype\s*=\s*["']?module\b/i.test(tag))
27
+ continue;
28
+ const src = /\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(tag);
29
+ const value = src?.[1] ?? src?.[2] ?? src?.[3];
30
+ if (value && value.startsWith('/') && !value.startsWith('//'))
31
+ srcs.push(value);
32
+ }
33
+ return srcs;
34
+ }
35
+ // Vite rewrites each import to a URL and records it, minus any HMR timestamp,
36
+ // in `staticImportedUrls`; that recorded string is what the browser asks for,
37
+ // so it is what gets preloaded. It can differ from the child node's own url: a
38
+ // shared chunk inside an optimized dep is imported with its importer's `?v=`.
39
+ function childNode(byUrl, importUrl) {
40
+ return byUrl.get(importUrl) ?? byUrl.get(importUrl.replace(/[?&]v=[\w.-]+$/, ''));
41
+ }
42
+ // Vite's `staticImportedUrls` holds every literal import specifier, dynamic ones
43
+ // included (`import('./x.js')`, a lazy `import.meta.glob`). Those load on demand,
44
+ // so only a URL the transformed code imports statically -- `import "u"`,
45
+ // `from "u"` -- is preloaded and walked.
46
+ function escapeRegExp(value) {
47
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
48
+ }
49
+ export function isStaticImportIn(code, url) {
50
+ const u = escapeRegExp(url);
51
+ return new RegExp(`(?:\\bfrom|\\bimport)\\s*(["'])${u}(?:[?&]t=\\d+)?\\1`).test(code);
52
+ }
53
+ // Walk the static import graph below `entries`, transforming modules the
54
+ // server has not seen yet (work the browser's requests would otherwise wait
55
+ // on one by one). A module is listed only once its own transform succeeded.
56
+ // The walk is raced against the budget, so a slow transform (a dependency
57
+ // re-optimization, a plugin that never settles) cannot hold the page: when
58
+ // the timer fires the list so far is returned and the rest load the ordinary way.
59
+ export async function collectModulePreloads(graph, entries, budgetMs = DEFAULT_BUDGET_MS) {
60
+ const out = [];
61
+ let stopped = false;
62
+ const walk = async () => {
63
+ const seen = new Set(entries);
64
+ let level = entries.map((url) => ({ url, href: null }));
65
+ while (level.length && !stopped) {
66
+ const next = [];
67
+ await Promise.all(level.map(async ({ url, href }) => {
68
+ let mod = await graph.getModuleByUrl(url);
69
+ if (!mod?.transformResult) {
70
+ try {
71
+ await graph.transformRequest(url);
72
+ }
73
+ catch {
74
+ return; // The page will hit the same error and report it itself.
75
+ }
76
+ mod = await graph.getModuleByUrl(url);
77
+ }
78
+ if (!mod?.transformResult || stopped)
79
+ return;
80
+ if (href && out.length < MAX_MODULES)
81
+ out.push(href);
82
+ const staticUrls = mod.staticImportedUrls;
83
+ const code = mod.transformResult.code;
84
+ if (!staticUrls || typeof code !== 'string')
85
+ return;
86
+ const byUrl = new Map([...mod.importedModules].map((child) => [child.url, child]));
87
+ for (const importUrl of staticUrls) {
88
+ if (!isStaticImportIn(code, importUrl))
89
+ continue;
90
+ const child = childNode(byUrl, importUrl);
91
+ if (!child || seen.has(child.url))
92
+ continue;
93
+ seen.add(child.url);
94
+ // A timestamped import carries `t=` at a position that depends on its
95
+ // other queries; skip rather than risk a second fetch. HMR is off, so
96
+ // this is rare (Vite still stamps pruned modules).
97
+ if (child.type !== 'js' || child.lastHMRTimestamp > 0)
98
+ continue;
99
+ if (!isPreloadableModuleUrl(importUrl))
100
+ continue;
101
+ next.push({ url: child.url, href: importUrl });
102
+ }
103
+ }));
104
+ level = next;
105
+ }
106
+ };
107
+ let timer;
108
+ const timeout = new Promise((resolve) => {
109
+ timer = setTimeout(resolve, budgetMs);
110
+ });
111
+ await Promise.race([walk().catch(() => { }), timeout]);
112
+ stopped = true;
113
+ clearTimeout(timer);
114
+ return out.slice();
115
+ }
116
+ export function modulePreloadPlugin(options) {
117
+ let server = null;
118
+ return {
119
+ name: 'castle-module-preload',
120
+ apply: 'serve',
121
+ configureServer(s) {
122
+ server = s;
123
+ },
124
+ transformIndexHtml: {
125
+ order: 'post',
126
+ async handler(html) {
127
+ const client = server?.environments?.client;
128
+ if (!options.enabled || !client)
129
+ return html;
130
+ const graph = {
131
+ transformRequest: (url) => client.transformRequest(url),
132
+ getModuleByUrl: (url) => client.moduleGraph.getModuleByUrl(url),
133
+ };
134
+ let urls;
135
+ try {
136
+ urls = await collectModulePreloads(graph, moduleEntrySrcs(html), options.budgetMs);
137
+ }
138
+ catch {
139
+ return html; // An optimisation only: never cost the page itself.
140
+ }
141
+ const tags = urls.map((href) => ({
142
+ tag: 'link',
143
+ attrs: { rel: 'modulepreload', href },
144
+ injectTo: 'head',
145
+ }));
146
+ return { html, tags };
147
+ },
148
+ },
149
+ };
150
+ }
@@ -25,7 +25,7 @@ const MAX_ITERATIONS = 40;
25
25
  // PLAYTEST_MAX_SHOTS frames each -- at most 24 -- small enough to list in
26
26
  // full for the task card, with no truncation needed.
27
27
  function playtestFrameList(frames) {
28
- return [...frames].sort();
28
+ return [...frames].sort((a, b) => a.localeCompare(b, "en", { numeric: true }));
29
29
  }
30
30
  // -- run logging ----------------------------------------------------------------
31
31
  // Structured JSONL, one event per line, appended (task retry attempts share