castle-web-cli 0.4.194 → 0.4.195

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 (42) hide show
  1. package/dist/agent-prompts.d.ts +1 -0
  2. package/dist/agent-prompts.js +14 -5
  3. package/dist/agent.js +14 -0
  4. package/dist/castleJson.d.ts +0 -2
  5. package/dist/castleJson.js +0 -39
  6. package/dist/devSessionFrameBudget.d.ts +14 -0
  7. package/dist/devSessionFrameBudget.js +64 -0
  8. package/dist/devSessionServer.js +15 -0
  9. package/dist/editorConfig.d.ts +1 -1
  10. package/dist/editorConfig.js +12 -4
  11. package/dist/ide.js +28 -59
  12. package/dist/imports.js +2 -4
  13. package/dist/init.js +9 -8
  14. package/dist/multiplayerDoc.d.ts +1 -0
  15. package/dist/multiplayerDoc.js +228 -0
  16. package/dist/platformDoc.d.ts +1 -0
  17. package/dist/platformDoc.js +21 -2
  18. package/dist/scriptErrors.d.ts +23 -0
  19. package/dist/scriptErrors.js +147 -0
  20. package/dist/serve.js +233 -4
  21. package/dist/shell/assets/index-kMH1qj6D.js +449 -0
  22. package/dist/shell/index.html +1 -1
  23. package/dist/viteClientStub.d.ts +18 -0
  24. package/dist/viteClientStub.js +193 -0
  25. package/kits/base/CLAUDE.md +3 -3
  26. package/kits/base/castle.json +1 -3
  27. package/kits/base/sdk/README.md +17 -0
  28. package/kits/multiplayer-2d/castle.json +0 -9
  29. package/kits/multiplayer-3d/castle.json +0 -8
  30. package/kits/physics-2d/CLAUDE.md +5 -6
  31. package/kits/physics-2d/castle.json +1 -11
  32. package/kits/physics-2d/editors/SceneEditor.jsx +42 -3
  33. package/kits/physics-2d/editors/behaviorRegistry.js +8 -2
  34. package/kits/physics-2d/engine/ErrorOverlay.jsx +69 -0
  35. package/kits/physics-2d/engine/ScenePlayer.jsx +2 -67
  36. package/kits/physics-2d/engine/liveReload.js +5 -4
  37. package/kits/physics-3d/castle.json +0 -11
  38. package/kits/real-time/castle.json +0 -6
  39. package/kits/turn-based/CLAUDE.md +6 -3
  40. package/kits/turn-based/castle.json +1 -14
  41. package/package.json +1 -1
  42. package/dist/shell/assets/index-ColHKJYj.js +0 -449
package/dist/serve.js CHANGED
@@ -9,6 +9,8 @@ import { isIP } from 'net';
9
9
  import { createIdeServer, FAVICON_FILES, FAVICON_LINK_TAGS } from './ide.js';
10
10
  import { createAgentServer } from './agent.js';
11
11
  import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin, sdkAliasPlugin, } from './vitePlugins.js';
12
+ import { viteClientStubPlugin } from './viteClientStub.js';
13
+ import { createScriptErrors, scriptErrorsPlugin } from './scriptErrors.js';
12
14
  import { installFilesChangedWatcher } from './filesChanged.js';
13
15
  import { autoUpdateImports, IMPORTS_DIR, lockImportTree } from './imports.js';
14
16
  import { ensureAgentsSymlink } from './init.js';
@@ -280,6 +282,188 @@ const CONSOLE_CAPTURE = `<script>(function(){
280
282
  };
281
283
  });
282
284
  })();</script>`;
285
+ // Injected into EVERY deck iframe (both roles, logs or not), before any module
286
+ // runs, so a page whose module graph never evaluates still says why.
287
+ //
288
+ // This is the only report there is when a module 500s: the deck's own entry
289
+ // never runs, so its React error boundary, its console interception and the
290
+ // kit's play/edit redboxes do not exist yet. A `<script type="module">` that
291
+ // fails to load fires a RESOURCE error -- no message, the event target is the
292
+ // element -- so that case asks the serve what it recorded
293
+ // (`/__castle/script-errors`, see scriptErrors.ts).
294
+ //
295
+ // Injected by dev serve only: the published bundle is built by `bundle.ts` and
296
+ // never passes through this plugin, so an end user can never see this redbox.
297
+ // Kit-agnostic and dependency-free: styled inline so it works on a bare
298
+ // `--kit none` deck, and ES5 so it needs no transform of its own.
299
+ const FRAME_ERROR_CAPTURE = `<script>(function(){
300
+ var role = 'edit';
301
+ try { role = new URLSearchParams(location.search).get('edit') === '0' ? 'play' : 'edit'; } catch (e) {}
302
+ var seen = {};
303
+ var shown = [];
304
+ var box = null;
305
+ var list = null;
306
+ var relPath = function (value) {
307
+ var text = value ? String(value) : '';
308
+ if (text.indexOf(location.origin) === 0) text = text.slice(location.origin.length);
309
+ var query = text.indexOf('?');
310
+ if (query >= 0) text = text.slice(0, query);
311
+ if (text.charAt(0) === '/') text = text.slice(1);
312
+ return text;
313
+ };
314
+ var post = function (entry) {
315
+ if (window.parent === window) return;
316
+ try {
317
+ window.parent.postMessage({
318
+ type: 'castle-frame-error',
319
+ role: role,
320
+ message: entry.message,
321
+ path: entry.path || '',
322
+ line: entry.line || 0,
323
+ column: entry.column || 0
324
+ }, window.__castleShellOrigin || '*');
325
+ } catch (e) {}
326
+ };
327
+ var mount = function () {
328
+ if (box) return;
329
+ box = document.createElement('div');
330
+ box.setAttribute('data-castle-frame-error', '1');
331
+ box.style.cssText = 'position:fixed;left:0;top:0;right:0;bottom:0;z-index:2147483000;box-sizing:border-box;padding:18px 20px;overflow:auto;background:rgba(20,8,8,0.96);color:#ffd9dc;font:13px/1.5 SFMono-Regular,Consolas,Liberation Mono,monospace';
332
+ var head = document.createElement('div');
333
+ head.style.cssText = 'display:flex;align-items:center;margin-bottom:10px';
334
+ var title = document.createElement('div');
335
+ title.style.cssText = 'font-size:15px;font-weight:700;color:#ff6b74';
336
+ title.textContent = 'Script error';
337
+ head.appendChild(title);
338
+ // Dismissable: a runtime throw in one handler should not lock a person out
339
+ // of a game that otherwise runs. A later, different error mounts it again.
340
+ var close = document.createElement('button');
341
+ close.type = 'button';
342
+ close.textContent = 'Dismiss';
343
+ close.style.cssText = 'margin-left:auto;padding:4px 12px;border:1px solid #a02828;border-radius:4px;background:#a02828;color:#fff;font:inherit;cursor:pointer';
344
+ close.onclick = function () {
345
+ if (box && box.parentNode) box.parentNode.removeChild(box);
346
+ box = null;
347
+ list = null;
348
+ };
349
+ head.appendChild(close);
350
+ box.appendChild(head);
351
+ list = document.createElement('div');
352
+ box.appendChild(list);
353
+ var hint = document.createElement('div');
354
+ hint.style.cssText = 'margin-top:12px;color:#c98a8f;font-size:12px';
355
+ hint.textContent = 'Fix the file and reload.';
356
+ box.appendChild(hint);
357
+ var attach = function () { if (document.body) document.body.appendChild(box); };
358
+ if (document.body) attach();
359
+ else document.addEventListener('DOMContentLoaded', attach);
360
+ };
361
+ var show = function (entry) {
362
+ var where = entry.path || '';
363
+ if (where && entry.line) where = where + ':' + entry.line + (entry.column ? ':' + entry.column : '');
364
+ var key = where + '|' + entry.message;
365
+ if (seen[key]) return;
366
+ seen[key] = 1;
367
+ mount();
368
+ var row = document.createElement('div');
369
+ row.style.cssText = 'margin-bottom:10px';
370
+ if (where) {
371
+ var head = document.createElement('div');
372
+ head.style.cssText = 'color:#fff;font-weight:600;word-break:break-word';
373
+ head.textContent = where;
374
+ row.appendChild(head);
375
+ }
376
+ var message = document.createElement('div');
377
+ message.style.cssText = 'word-break:break-word;white-space:pre-wrap';
378
+ message.textContent = entry.message;
379
+ row.appendChild(message);
380
+ if (entry.frame) {
381
+ var frame = document.createElement('pre');
382
+ frame.style.cssText = 'margin:6px 0 0;color:#e79aa0;font-size:12px;white-space:pre-wrap;word-break:break-word';
383
+ frame.textContent = entry.frame;
384
+ row.appendChild(frame);
385
+ }
386
+ list.appendChild(row);
387
+ shown.push(entry);
388
+ post(entry);
389
+ };
390
+ var askServe = function (src) {
391
+ var generic = function () {
392
+ show({ message: "The deck's code failed to load" + (src ? ' (' + relPath(src) + ')' : ''), path: '' });
393
+ };
394
+ var render = function (data) {
395
+ var found = data && data.errors ? data.errors : null;
396
+ var keys = found ? Object.keys(found) : [];
397
+ for (var i = 0; i < keys.length; i++) {
398
+ var entry = found[keys[i]] || {};
399
+ show({
400
+ message: entry.message || 'Failed to compile',
401
+ path: entry.path || keys[i],
402
+ line: entry.line,
403
+ column: entry.column,
404
+ frame: entry.frame
405
+ });
406
+ }
407
+ if (!keys.length) generic();
408
+ };
409
+ try {
410
+ fetch('/__castle/script-errors', { credentials: 'same-origin' }).then(function (res) {
411
+ return res.ok ? res.json() : null;
412
+ }).then(render, generic);
413
+ } catch (e) { generic(); }
414
+ };
415
+ // Capture phase: a resource error (a module script that 500s) does not
416
+ // bubble, so a listener on window only hears it on the way down. Only a
417
+ // MODULE script served from this origin counts: the deck entry and
418
+ // everything Vite serves are modules, so a CDN script, a stylesheet that
419
+ // fails offline, or a classic src script is not a transform failure.
420
+ window.addEventListener('error', function (event) {
421
+ var node = event && event.target;
422
+ if (node && node !== window && node.tagName) {
423
+ if (node.tagName === 'SCRIPT' && node.type === 'module' && node.src && node.src.indexOf(location.origin + '/') === 0) askServe(node.src);
424
+ return;
425
+ }
426
+ var error = event && event.error;
427
+ var message = (event && event.message) || (error && error.message) || String(error || 'Unknown error');
428
+ // Two browser-side non-errors that would otherwise cover a working deck:
429
+ // the benign ResizeObserver notice, and the opaque cross-origin
430
+ // "Script error." that carries nothing anyone can act on.
431
+ if (message.indexOf('ResizeObserver loop') >= 0) return;
432
+ if (message.indexOf('Script error') === 0 && !(event && event.filename)) return;
433
+ show({
434
+ message: message,
435
+ path: relPath(event && event.filename),
436
+ line: event && event.lineno,
437
+ column: event && event.colno
438
+ });
439
+ }, true);
440
+ window.addEventListener('unhandledrejection', function (event) {
441
+ var reason = event && event.reason;
442
+ var message = (reason && reason.message) || String(reason || 'Unhandled rejection');
443
+ show({ message: message, path: '' });
444
+ });
445
+ // Replay on request, because posting once loses the race both ways: the
446
+ // shell registers the frame in its iframe onLoad handler, so an error posted
447
+ // before that is dropped, and the compile-error redbox posts only after an
448
+ // async fetch of /__castle/script-errors, so it can land AFTER the readiness
449
+ // message that clears the shell's frame errors.
450
+ //
451
+ // The shell asks for readiness right after it registers the frame, which
452
+ // settles both. The announce block above registered its message listener
453
+ // first, so for one request the browser runs it first and its
454
+ // castle-content-frame-ready is posted before these re-posts: the shell
455
+ // always sees the clear followed by whatever is on screen right now. Errors
456
+ // still post immediately as well, for throws long after boot.
457
+ //
458
+ // Same sender checks as the announce block: only the parent that embeds us,
459
+ // and only from the shell origin once we know it.
460
+ window.addEventListener('message', function (event) {
461
+ var data = event && event.data;
462
+ if (event.source !== window.parent || !data || data.type !== 'castle-request-content-frame-ready') return;
463
+ if (window.__castleShellOrigin && event.origin !== window.__castleShellOrigin) return;
464
+ for (var i = 0; i < shown.length; i++) post(shown[i]);
465
+ });
466
+ })();</script>`;
283
467
  function hostnameFromHeader(value) {
284
468
  if (!value)
285
469
  return '';
@@ -314,7 +498,25 @@ const EDIT_CONTENT_READ_ENDPOINTS = new Set([
314
498
  export function isAllowedContentFilesRequest(role, method, reqPath) {
315
499
  return role === 'edit' && method === 'GET' && EDIT_CONTENT_READ_ENDPOINTS.has(reqPath);
316
500
  }
317
- function castlePlugin(security, ideServer, agentServer, configuredHost) {
501
+ // Mirrors Vite's own `injectToHead` fallback order (see
502
+ // vite/dist/node/chunks/node.js): after `<head>` when the document has one,
503
+ // else after `<html>`, else before `<body>`, else at the very top. A minimal
504
+ // deck page with no head at all still has to get the shell-origin script and
505
+ // the redbox. Replacer functions throughout, so `$&` in the injected script
506
+ // stays literal.
507
+ function injectIntoHead(html, injected) {
508
+ const head = /<head(\s[^>]*)?>/i;
509
+ if (head.test(html))
510
+ return html.replace(head, (match) => `${match}${injected}`);
511
+ const htmlTag = /<html(\s[^>]*)?>/i;
512
+ if (htmlTag.test(html))
513
+ return html.replace(htmlTag, (match) => `${match}${injected}`);
514
+ const body = /<body(\s[^>]*)?>/i;
515
+ if (body.test(html))
516
+ return html.replace(body, (match) => `${injected}${match}`);
517
+ return `${injected}${html}`;
518
+ }
519
+ function castlePlugin(security, ideServer, agentServer, scriptErrors, configuredHost) {
318
520
  return {
319
521
  name: 'castle-dev',
320
522
  transformIndexHtml: {
@@ -328,7 +530,7 @@ function castlePlugin(security, ideServer, agentServer, configuredHost) {
328
530
  const favicon = /<link[^>]+rel=["']?[^"'>]*icon/i.test(html)
329
531
  ? ''
330
532
  : `\n ${FAVICON_LINK_TAGS}`;
331
- return html.replace(/<head(\s[^>]*)?>/i, (match) => `${match}${favicon}\n <script>
533
+ const injected = `${favicon}\n <script>
332
534
  window.CastleEmbed={edit:true,host:'dev'};
333
535
  window.__castleShellOrigin=(function(){
334
536
  var h=location.hostname.toLowerCase();
@@ -355,7 +557,8 @@ window.__castleShellOrigin=(function(){
355
557
  });
356
558
  window.addEventListener('load',function(){setTimeout(announce,0);},{once:true});
357
559
  })();
358
- </script>\n ${CONSOLE_CAPTURE}`);
560
+ </script>\n ${FRAME_ERROR_CAPTURE}\n ${CONSOLE_CAPTURE}`;
561
+ return injectIntoHead(html, injected);
359
562
  },
360
563
  },
361
564
  configureServer(server) {
@@ -429,6 +632,25 @@ window.__castleShellOrigin=(function(){
429
632
  res.writeHead(404).end();
430
633
  return;
431
634
  }
635
+ // What failed to compile, for a frame that could not boot far enough to
636
+ // hold a socket (see FRAME_ERROR_CAPTURE). Open to BOTH content roles --
637
+ // an edit frame and a play frame are equally blank when a module 500s --
638
+ // and to the authenticated shell. Read-only, and it says nothing a
639
+ // frame could not already see in its own failed module request.
640
+ if (reqPath === '/__castle/script-errors') {
641
+ if (req.method !== 'GET') {
642
+ res.writeHead(405).end();
643
+ return;
644
+ }
645
+ if (!content &&
646
+ !security.authorizeHttp(req) &&
647
+ !security.authorizeSignedPath(req, reqPath)) {
648
+ security.rejectHttpAuth(res);
649
+ return;
650
+ }
651
+ scriptErrors.respond(res);
652
+ return;
653
+ }
432
654
  if (content) {
433
655
  if (reqPath === '/')
434
656
  req.url = `/index.html${req.url?.includes('?') ? req.url.slice(req.url.indexOf('?')) : ''}`;
@@ -843,6 +1065,9 @@ export async function serve(dir, options = {}) {
843
1065
  const playtestHolder = { run: null };
844
1066
  const { broadcast, handleUpgrade: handleCastleUpgrade } = startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, devSession, playtestHolder);
845
1067
  broadcastDevLog = broadcast;
1068
+ // Failed module transforms, remembered here so a deck whose entry never
1069
+ // evaluated can still be told what broke (scriptErrors.ts).
1070
+ const scriptErrors = createScriptErrors(projectDir, broadcast);
846
1071
  // The deck root `/` serves a split-view shell: the deck in an iframe plus a
847
1072
  // toggle button for an xterm.js terminal. The terminal's PTY is lazy -- it
848
1073
  // spawns only when a browser first opens the PTY WebSocket.
@@ -928,11 +1153,15 @@ export async function serve(dir, options = {}) {
928
1153
  // to recover from an outdated optimized-dependency response (HMR is off).
929
1154
  ...(importsChangedAtStartup ? { optimizeDeps: { force: true } } : {}),
930
1155
  plugins: [
931
- castlePlugin(security, ideServer, agentServer, options.host),
1156
+ // HMR is off (below), but Vite still injects and imports `/@vite/client`.
1157
+ // Serve a socket-free stub of it so no page logs a failed HMR connection.
1158
+ viteClientStubPlugin(),
1159
+ castlePlugin(security, ideServer, agentServer, scriptErrors, options.host),
932
1160
  forksOverlayPlugin(),
933
1161
  importsAliasPlugin(),
934
1162
  sdkAliasPlugin(),
935
1163
  sceneFilesPlugin(),
1164
+ scriptErrorsPlugin(scriptErrors),
936
1165
  ],
937
1166
  server: {
938
1167
  port,