castle-web-cli 0.4.193 → 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.
- package/dist/agent-prompts.d.ts +1 -0
- package/dist/agent-prompts.js +14 -5
- package/dist/agent.js +101 -4
- package/dist/api.d.ts +1 -0
- package/dist/api.js +5 -0
- package/dist/bundle.js +2 -1
- package/dist/castleJson.d.ts +1 -2
- package/dist/castleJson.js +0 -39
- package/dist/check.js +14 -6
- package/dist/devSessionFrameBudget.d.ts +14 -0
- package/dist/devSessionFrameBudget.js +64 -0
- package/dist/devSessionServer.d.ts +6 -0
- package/dist/devSessionServer.js +38 -1
- package/dist/editorConfig.d.ts +1 -1
- package/dist/editorConfig.js +12 -4
- package/dist/filesChanged.js +7 -3
- package/dist/ide.js +28 -59
- package/dist/importUpdateHook.d.ts +31 -0
- package/dist/importUpdateHook.js +135 -0
- package/dist/importUpdateHookRunner.d.ts +2 -0
- package/dist/importUpdateHookRunner.js +24 -0
- package/dist/imports.js +58 -10
- package/dist/index.js +58 -7
- package/dist/init.d.ts +1 -0
- package/dist/init.js +15 -9
- package/dist/multiplayerDoc.d.ts +1 -0
- package/dist/multiplayerDoc.js +228 -0
- package/dist/native/loop.js +29 -9
- package/dist/platformDoc.d.ts +1 -0
- package/dist/platformDoc.js +25 -6
- package/dist/remix.js +4 -1
- package/dist/scriptErrors.d.ts +23 -0
- package/dist/scriptErrors.js +147 -0
- package/dist/serve.js +366 -36
- package/dist/serverBundle.js +1 -1
- package/dist/shell/assets/index-kMH1qj6D.js +449 -0
- package/dist/shell/index.html +1 -1
- package/dist/versions.d.ts +14 -0
- package/dist/versions.js +21 -0
- package/dist/viteClientStub.d.ts +18 -0
- package/dist/viteClientStub.js +193 -0
- package/dist/vitePlugins.d.ts +1 -0
- package/dist/vitePlugins.js +18 -0
- package/kits/base/CLAUDE.md +3 -3
- package/kits/base/castle.json +1 -3
- package/kits/base/sdk/README.md +17 -0
- package/kits/multiplayer-2d/CLAUDE.md +9 -2
- package/kits/multiplayer-2d/blueprints/crate.scene +32 -4
- package/kits/multiplayer-2d/blueprints/other-player.scene +31 -4
- package/kits/multiplayer-2d/blueprints/player.scene +38 -6
- package/kits/multiplayer-2d/blueprints/wall.scene +25 -3
- package/kits/multiplayer-2d/castle.json +3 -12
- package/kits/multiplayer-2d/test/two-client-test.mjs +4 -4
- package/kits/multiplayer-3d/CLAUDE.md +5 -2
- package/kits/multiplayer-3d/castle.json +3 -11
- package/kits/multiplayer-3d/scenes/main.scene +128 -0
- package/kits/physics-2d/CLAUDE.md +16 -11
- package/kits/physics-2d/behaviors/Camera.jsx +5 -6
- package/kits/physics-2d/behaviors/Goal.jsx +5 -2
- package/kits/physics-2d/behaviors/Joints.jsx +4 -3
- package/kits/physics-2d/behaviors/Layout.jsx +120 -3
- package/kits/physics-2d/behaviors/Sprite.jsx +9 -9
- package/kits/physics-2d/behaviors/Style.jsx +22 -15
- package/kits/physics-2d/behaviors/Text.jsx +7 -6
- package/kits/physics-2d/blueprints/ball.scene +27 -5
- package/kits/physics-2d/blueprints/block.scene +16 -3
- package/kits/physics-2d/blueprints/cauldron.scene +3 -1
- package/kits/physics-2d/blueprints/crate.scene +23 -4
- package/kits/physics-2d/blueprints/goal.scene +12 -2
- package/kits/physics-2d/blueprints/text.scene +13 -3
- package/kits/physics-2d/castle.json +2 -11
- package/kits/physics-2d/editors/SceneEditor.jsx +68 -5
- package/kits/physics-2d/editors/SelectionOverlay.jsx +27 -20
- package/kits/physics-2d/editors/behaviorRegistry.js +8 -2
- package/kits/physics-2d/engine/ErrorOverlay.jsx +69 -0
- package/kits/physics-2d/engine/ScenePlayer.jsx +2 -67
- package/kits/physics-2d/engine/blueprint.js +111 -54
- package/kits/physics-2d/engine/blueprintCore.js +59 -0
- package/kits/physics-2d/engine/collider.js +28 -17
- package/kits/physics-2d/engine/layout.js +61 -0
- package/kits/physics-2d/engine/layoutOriginMigration.js +223 -0
- package/kits/physics-2d/engine/liveReload.js +5 -4
- package/kits/physics-2d/engine/physics/PhysicsSystem.js +11 -7
- package/kits/physics-2d/engine/physics/controls.js +4 -8
- package/kits/physics-2d/engine/physics/matterBridge.js +13 -8
- package/kits/physics-2d/engine/scene.js +38 -34
- package/kits/physics-2d/engine/spriteGeometry.js +17 -9
- package/kits/physics-2d/engine/tap.js +4 -3
- package/kits/physics-2d/scenes/main.scene +59 -6
- package/kits/physics-2d/scenes/sandbox.scene +69 -7
- package/kits/physics-2d/scripts/onUpdate.mjs +199 -0
- package/kits/physics-3d/castle.json +0 -11
- package/kits/real-time/castle.json +2 -8
- package/kits/real-time/code/server/persist.js +14 -0
- package/kits/turn-based/CLAUDE.md +18 -10
- package/kits/turn-based/blueprints/board.scene +3 -1
- package/kits/turn-based/blueprints/square.scene +3 -1
- package/kits/turn-based/castle.json +3 -14
- package/kits/turn-based/code/behaviors/Board.jsx +33 -21
- package/package.json +1 -1
- 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';
|
|
@@ -18,6 +20,7 @@ import * as config from './config.js';
|
|
|
18
20
|
import { graphql as castleGraphql } from './api.js';
|
|
19
21
|
import { executeCommand } from './castle-host/host.js';
|
|
20
22
|
import { ServeSecurity } from './serveSecurity.js';
|
|
23
|
+
import { atomicWriteFileSync } from './atomicFile.js';
|
|
21
24
|
import { isSameOriginUpgrade } from './wsOrigin.js';
|
|
22
25
|
import { createAssetCompression } from './assetCompression.js';
|
|
23
26
|
import { resolveServerConfig } from './castleJson.js';
|
|
@@ -40,18 +43,59 @@ export function appendCapped(file, line) {
|
|
|
40
43
|
// logging must never take the serve down
|
|
41
44
|
}
|
|
42
45
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
46
|
+
const PORT_PROBE_TIMEOUT_MS = 300;
|
|
47
|
+
const PORT_PROBE_FREE_ERRORS = new Set([
|
|
48
|
+
'ECONNREFUSED',
|
|
49
|
+
'EHOSTUNREACH',
|
|
50
|
+
'EADDRNOTAVAIL',
|
|
51
|
+
'EAFNOSUPPORT',
|
|
52
|
+
]);
|
|
53
|
+
// A wildcard or localhost serve is reached as http://localhost:<port>, which
|
|
54
|
+
// resolves to either loopback family, so a listener on just one of them still
|
|
55
|
+
// makes the port unusable (two decks answered on one hostname that way).
|
|
56
|
+
function connectProbeHosts(host) {
|
|
57
|
+
return !host || host === 'localhost' || host === '0.0.0.0' || host === '::'
|
|
58
|
+
? ['127.0.0.1', '::1']
|
|
59
|
+
: [host];
|
|
60
|
+
}
|
|
61
|
+
function canConnectToPort(port, host) {
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
const socket = net.createConnection({ port, host });
|
|
64
|
+
socket.setTimeout(PORT_PROBE_TIMEOUT_MS);
|
|
65
|
+
socket.once('connect', () => {
|
|
66
|
+
socket.destroy();
|
|
67
|
+
resolve(true);
|
|
68
|
+
});
|
|
69
|
+
// A loopback connect that neither completes nor is refused is
|
|
70
|
+
// indeterminate; treat it as occupied so findFreePort moves on and an
|
|
71
|
+
// explicit port fails here rather than deeper in vite.
|
|
72
|
+
socket.once('timeout', () => {
|
|
73
|
+
socket.destroy();
|
|
74
|
+
resolve(true);
|
|
75
|
+
});
|
|
76
|
+
socket.once('error', (error) => {
|
|
77
|
+
if (error.code && PORT_PROBE_FREE_ERRORS.has(error.code))
|
|
78
|
+
resolve(false);
|
|
79
|
+
else
|
|
80
|
+
reject(error);
|
|
49
81
|
});
|
|
50
82
|
});
|
|
51
83
|
}
|
|
52
|
-
async function
|
|
84
|
+
async function isPortFree(port, host) {
|
|
85
|
+
for (const probeHost of connectProbeHosts(host)) {
|
|
86
|
+
if (await canConnectToPort(port, probeHost))
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
async function requireFreePort(port, host) {
|
|
92
|
+
if (await isPortFree(port, host))
|
|
93
|
+
return;
|
|
94
|
+
throw new Error(`Port ${port} is already in use. Try another port with --port <n>.`);
|
|
95
|
+
}
|
|
96
|
+
async function findFreePort(startPort, host) {
|
|
53
97
|
for (let port = startPort; port < startPort + 100; port += 1) {
|
|
54
|
-
if (await isPortFree(port))
|
|
98
|
+
if (await isPortFree(port, host))
|
|
55
99
|
return port;
|
|
56
100
|
}
|
|
57
101
|
throw new Error(`No free port found starting from ${startPort}`);
|
|
@@ -238,6 +282,188 @@ const CONSOLE_CAPTURE = `<script>(function(){
|
|
|
238
282
|
};
|
|
239
283
|
});
|
|
240
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>`;
|
|
241
467
|
function hostnameFromHeader(value) {
|
|
242
468
|
if (!value)
|
|
243
469
|
return '';
|
|
@@ -272,7 +498,25 @@ const EDIT_CONTENT_READ_ENDPOINTS = new Set([
|
|
|
272
498
|
export function isAllowedContentFilesRequest(role, method, reqPath) {
|
|
273
499
|
return role === 'edit' && method === 'GET' && EDIT_CONTENT_READ_ENDPOINTS.has(reqPath);
|
|
274
500
|
}
|
|
275
|
-
|
|
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) {
|
|
276
520
|
return {
|
|
277
521
|
name: 'castle-dev',
|
|
278
522
|
transformIndexHtml: {
|
|
@@ -286,7 +530,7 @@ function castlePlugin(security, ideServer, agentServer, configuredHost) {
|
|
|
286
530
|
const favicon = /<link[^>]+rel=["']?[^"'>]*icon/i.test(html)
|
|
287
531
|
? ''
|
|
288
532
|
: `\n ${FAVICON_LINK_TAGS}`;
|
|
289
|
-
|
|
533
|
+
const injected = `${favicon}\n <script>
|
|
290
534
|
window.CastleEmbed={edit:true,host:'dev'};
|
|
291
535
|
window.__castleShellOrigin=(function(){
|
|
292
536
|
var h=location.hostname.toLowerCase();
|
|
@@ -313,7 +557,8 @@ window.__castleShellOrigin=(function(){
|
|
|
313
557
|
});
|
|
314
558
|
window.addEventListener('load',function(){setTimeout(announce,0);},{once:true});
|
|
315
559
|
})();
|
|
316
|
-
</script>\n ${CONSOLE_CAPTURE}
|
|
560
|
+
</script>\n ${FRAME_ERROR_CAPTURE}\n ${CONSOLE_CAPTURE}`;
|
|
561
|
+
return injectIntoHead(html, injected);
|
|
317
562
|
},
|
|
318
563
|
},
|
|
319
564
|
configureServer(server) {
|
|
@@ -383,11 +628,29 @@ window.__castleShellOrigin=(function(){
|
|
|
383
628
|
res.end(JSON.stringify({ path: `${LEGACY_CONTENT_WS_PATH}?ticket=${ticket}` }));
|
|
384
629
|
return;
|
|
385
630
|
}
|
|
386
|
-
if (reqPath === '/__castle/auth' ||
|
|
387
|
-
reqPath === '/__castle/context') {
|
|
631
|
+
if (reqPath === '/__castle/auth' || reqPath === '/__castle/context') {
|
|
388
632
|
res.writeHead(404).end();
|
|
389
633
|
return;
|
|
390
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
|
+
}
|
|
391
654
|
if (content) {
|
|
392
655
|
if (reqPath === '/')
|
|
393
656
|
req.url = `/index.html${req.url?.includes('?') ? req.url.slice(req.url.indexOf('?')) : ''}`;
|
|
@@ -557,13 +820,64 @@ function readServeJson(projectDir) {
|
|
|
557
820
|
return null;
|
|
558
821
|
}
|
|
559
822
|
}
|
|
823
|
+
function removeServeJsonIfOwned(serveJsonPath, pid) {
|
|
824
|
+
try {
|
|
825
|
+
const before = fs.statSync(serveJsonPath);
|
|
826
|
+
const info = JSON.parse(fs.readFileSync(serveJsonPath, 'utf8'));
|
|
827
|
+
if (info.pid !== pid)
|
|
828
|
+
return;
|
|
829
|
+
const after = fs.statSync(serveJsonPath);
|
|
830
|
+
if (before.dev !== after.dev || before.ino !== after.ino)
|
|
831
|
+
return;
|
|
832
|
+
// The final stat-to-unlink race remains, but this narrow window is accepted.
|
|
833
|
+
fs.unlinkSync(serveJsonPath);
|
|
834
|
+
}
|
|
835
|
+
catch {
|
|
836
|
+
// Missing, malformed, or replaced by another serve: leave it alone.
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
function removeStaleServeJson(serveJsonPath) {
|
|
840
|
+
try {
|
|
841
|
+
const raw = fs.readFileSync(serveJsonPath, 'utf8');
|
|
842
|
+
let pid = null;
|
|
843
|
+
try {
|
|
844
|
+
const info = JSON.parse(raw);
|
|
845
|
+
if (typeof info.pid === 'number' && Number.isInteger(info.pid) && info.pid > 0) {
|
|
846
|
+
pid = info.pid;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
catch {
|
|
850
|
+
// An unreadable record cannot name a live owner.
|
|
851
|
+
}
|
|
852
|
+
if (pid !== null) {
|
|
853
|
+
if (isPidAlive(pid))
|
|
854
|
+
return;
|
|
855
|
+
removeServeJsonIfOwned(serveJsonPath, pid);
|
|
856
|
+
return;
|
|
857
|
+
}
|
|
858
|
+
// Do not unlink a valid record that replaced the malformed one we read.
|
|
859
|
+
if (fs.readFileSync(serveJsonPath, 'utf8') === raw)
|
|
860
|
+
fs.unlinkSync(serveJsonPath);
|
|
861
|
+
}
|
|
862
|
+
catch {
|
|
863
|
+
// No stale record to remove, or another process changed it concurrently.
|
|
864
|
+
}
|
|
865
|
+
}
|
|
560
866
|
function isPidAlive(pid) {
|
|
561
867
|
try {
|
|
562
868
|
process.kill(pid, 0);
|
|
563
869
|
return true;
|
|
564
870
|
}
|
|
871
|
+
catch (error) {
|
|
872
|
+
return error.code === 'EPERM';
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
function readLogTail(logPath, maxLines) {
|
|
876
|
+
try {
|
|
877
|
+
return fs.readFileSync(logPath, 'utf8').trimEnd().split(/\r?\n/).slice(-maxLines).join('\n');
|
|
878
|
+
}
|
|
565
879
|
catch {
|
|
566
|
-
return
|
|
880
|
+
return '';
|
|
567
881
|
}
|
|
568
882
|
}
|
|
569
883
|
// Return the live serve already owning this deck, if any. Lets repeated
|
|
@@ -633,6 +947,9 @@ export async function serve(dir, options = {}) {
|
|
|
633
947
|
return;
|
|
634
948
|
}
|
|
635
949
|
}
|
|
950
|
+
const explicitPort = options.port ? Number.parseInt(options.port, 10) : undefined;
|
|
951
|
+
if (explicitPort !== undefined)
|
|
952
|
+
await requireFreePort(explicitPort, options.host);
|
|
636
953
|
// --detach is kept for back-compat. Agent evals (and any harness running
|
|
637
954
|
// castle-web in a context that can't manage a foreground process) should
|
|
638
955
|
// prefer the CASTLE_WEB_CLI_DETACH=1 env var instead.
|
|
@@ -693,8 +1010,8 @@ export async function serve(dir, options = {}) {
|
|
|
693
1010
|
// already destroyed / inaccessible
|
|
694
1011
|
}
|
|
695
1012
|
}
|
|
696
|
-
const startPort =
|
|
697
|
-
const port =
|
|
1013
|
+
const startPort = explicitPort ?? DEFAULT_PORT;
|
|
1014
|
+
const port = explicitPort ?? (await findFreePort(startPort, options.host));
|
|
698
1015
|
const security = new ServeSecurity(port);
|
|
699
1016
|
// Local WebSocket server for SDK communication
|
|
700
1017
|
const castleDir = path.join(projectDir, '.castle');
|
|
@@ -716,12 +1033,7 @@ export async function serve(dir, options = {}) {
|
|
|
716
1033
|
const screenshotsDir = path.join(castleDir, 'screenshots');
|
|
717
1034
|
const serveJsonPath = path.join(castleDir, 'serve.json');
|
|
718
1035
|
process.on('exit', () => {
|
|
719
|
-
|
|
720
|
-
fs.unlinkSync(serveJsonPath);
|
|
721
|
-
}
|
|
722
|
-
catch {
|
|
723
|
-
// already removed / never written
|
|
724
|
-
}
|
|
1036
|
+
removeServeJsonIfOwned(serveJsonPath, process.pid);
|
|
725
1037
|
});
|
|
726
1038
|
process.on('SIGINT', () => process.exit());
|
|
727
1039
|
process.on('SIGTERM', () => process.exit());
|
|
@@ -753,6 +1065,9 @@ export async function serve(dir, options = {}) {
|
|
|
753
1065
|
const playtestHolder = { run: null };
|
|
754
1066
|
const { broadcast, handleUpgrade: handleCastleUpgrade } = startWSServer(projectDir, logFile, screenshotsDir, viteHolder, security, devSession, playtestHolder);
|
|
755
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);
|
|
756
1071
|
// The deck root `/` serves a split-view shell: the deck in an iframe plus a
|
|
757
1072
|
// toggle button for an xterm.js terminal. The terminal's PTY is lazy -- it
|
|
758
1073
|
// spawns only when a browser first opens the PTY WebSocket.
|
|
@@ -838,11 +1153,15 @@ export async function serve(dir, options = {}) {
|
|
|
838
1153
|
// to recover from an outdated optimized-dependency response (HMR is off).
|
|
839
1154
|
...(importsChangedAtStartup ? { optimizeDeps: { force: true } } : {}),
|
|
840
1155
|
plugins: [
|
|
841
|
-
|
|
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),
|
|
842
1160
|
forksOverlayPlugin(),
|
|
843
1161
|
importsAliasPlugin(),
|
|
844
1162
|
sdkAliasPlugin(),
|
|
845
1163
|
sceneFilesPlugin(),
|
|
1164
|
+
scriptErrorsPlugin(scriptErrors),
|
|
846
1165
|
],
|
|
847
1166
|
server: {
|
|
848
1167
|
port,
|
|
@@ -910,7 +1229,9 @@ export async function serve(dir, options = {}) {
|
|
|
910
1229
|
// Bring content up first so `--open` cannot race an iframe against a port
|
|
911
1230
|
// that is not listening yet. Vite opens the shell from inside `vite.listen()`.
|
|
912
1231
|
await vite.listen();
|
|
913
|
-
|
|
1232
|
+
// Atomic so a replacement lands under a new inode: the owned-removal check
|
|
1233
|
+
// in removeServeJsonIfOwned compares inodes to tell a rewrite apart.
|
|
1234
|
+
atomicWriteFileSync(serveJsonPath, JSON.stringify({
|
|
914
1235
|
port,
|
|
915
1236
|
// Kept for older CLI commands: they connect to this port's root path.
|
|
916
1237
|
// New clients use wsPath. Both routes reach the same noServer WSS.
|
|
@@ -990,13 +1311,9 @@ async function serveDetached(projectDir, options) {
|
|
|
990
1311
|
if (!fs.existsSync(castleDir))
|
|
991
1312
|
fs.mkdirSync(castleDir, { recursive: true });
|
|
992
1313
|
const serveJsonPath = path.join(castleDir, 'serve.json');
|
|
993
|
-
// Clear stale
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
}
|
|
997
|
-
catch {
|
|
998
|
-
// no stale serve.json — fine
|
|
999
|
-
}
|
|
1314
|
+
// Clear only a stale record. A live serve owns its file even when this
|
|
1315
|
+
// explicit invocation is going to attempt a second serve for the deck.
|
|
1316
|
+
removeStaleServeJson(serveJsonPath);
|
|
1000
1317
|
const logPath = path.join(castleDir, 'serve.log');
|
|
1001
1318
|
const logFd = fs.openSync(logPath, 'a');
|
|
1002
1319
|
// Re-exec this CLI with the same args minus --detach. process.argv[0] is
|
|
@@ -1027,16 +1344,29 @@ async function serveDetached(projectDir, options) {
|
|
|
1027
1344
|
stdio: ['ignore', logFd, logFd],
|
|
1028
1345
|
env: childEnv,
|
|
1029
1346
|
});
|
|
1030
|
-
child.unref();
|
|
1031
1347
|
fs.closeSync(logFd);
|
|
1032
|
-
|
|
1033
|
-
|
|
1348
|
+
const childPid = child.pid;
|
|
1349
|
+
if (childPid === undefined)
|
|
1350
|
+
throw new Error('detached serve did not start a child process');
|
|
1351
|
+
child.unref();
|
|
1352
|
+
// Import auto-update happens in the child before it binds and can be slow on
|
|
1353
|
+
// the network. Wait while that child is alive, with a generous final bound.
|
|
1354
|
+
const deadline = Date.now() + 120_000;
|
|
1034
1355
|
while (Date.now() < deadline) {
|
|
1356
|
+
if (!isPidAlive(childPid)) {
|
|
1357
|
+
const tail = readLogTail(logPath, 10);
|
|
1358
|
+
throw new Error(`Detached serve process ${childPid} exited before writing ${serveJsonPath}.\n` +
|
|
1359
|
+
`Last lines of ${logPath}:\n${tail || '(no log output)'}`);
|
|
1360
|
+
}
|
|
1035
1361
|
if (fs.existsSync(serveJsonPath)) {
|
|
1036
1362
|
try {
|
|
1037
1363
|
const info = JSON.parse(fs.readFileSync(serveJsonPath, 'utf8'));
|
|
1364
|
+
if (info.pid !== childPid || typeof info.port !== 'number') {
|
|
1365
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
1366
|
+
continue;
|
|
1367
|
+
}
|
|
1038
1368
|
console.log(`Started serve in background: http://localhost:${info.port}`);
|
|
1039
|
-
console.log(`PID: ${
|
|
1369
|
+
console.log(`PID: ${childPid}`);
|
|
1040
1370
|
console.log(`Logs: ${logPath}`);
|
|
1041
1371
|
return;
|
|
1042
1372
|
}
|
|
@@ -1046,7 +1376,7 @@ async function serveDetached(projectDir, options) {
|
|
|
1046
1376
|
}
|
|
1047
1377
|
await new Promise((r) => setTimeout(r, 200));
|
|
1048
1378
|
}
|
|
1049
|
-
throw new Error(`Detached serve did not write ${serveJsonPath} within
|
|
1379
|
+
throw new Error(`Detached serve did not write ${serveJsonPath} within 120s; check ${logPath} for startup errors.`);
|
|
1050
1380
|
}
|
|
1051
1381
|
// Answered by the SERVE itself (the agent server owns the warm Chromium),
|
|
1052
1382
|
// unlike screenshot_request which a browser tab answers -- so no
|
package/dist/serverBundle.js
CHANGED
|
@@ -69,7 +69,7 @@ export async function bundleServerModule(projectDir, config, minify) {
|
|
|
69
69
|
assetsInlineLimit: Number.MAX_SAFE_INTEGER,
|
|
70
70
|
rollupOptions: {
|
|
71
71
|
input: VIRTUAL_ENTRY,
|
|
72
|
-
output: { format: 'es',
|
|
72
|
+
output: { format: 'es', codeSplitting: false },
|
|
73
73
|
},
|
|
74
74
|
},
|
|
75
75
|
});
|