castle-web-cli 0.4.149 → 0.4.150

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 (44) hide show
  1. package/dist/api.d.ts +14 -0
  2. package/dist/api.js +18 -0
  3. package/dist/castle-host/host.d.ts +17 -0
  4. package/dist/castle-host/host.js +10 -7
  5. package/dist/castleJson.d.ts +15 -0
  6. package/dist/castleJson.js +36 -0
  7. package/dist/devSessionChild.d.ts +1 -0
  8. package/dist/devSessionChild.js +129 -0
  9. package/dist/devSessionServer.d.ts +19 -0
  10. package/dist/devSessionServer.js +511 -0
  11. package/dist/index.js +8 -8
  12. package/dist/init.js +9 -1
  13. package/dist/list-decks.js +7 -6
  14. package/dist/preview.d.ts +1 -1
  15. package/dist/preview.js +4 -2
  16. package/dist/save-deck.js +63 -14
  17. package/dist/serve.js +220 -85
  18. package/dist/serveSecurity.d.ts +5 -1
  19. package/dist/serveSecurity.js +48 -10
  20. package/dist/serverBundle.d.ts +8 -0
  21. package/dist/serverBundle.js +82 -0
  22. package/dist/shell/assets/{index-BzFzFtEP.js → index-Dlhc3eZW.js} +42 -42
  23. package/dist/shell/assets/index-DwezawBs.css +1 -0
  24. package/dist/shell/index.html +2 -2
  25. package/kits/blank/.castle/agent/children.json +1 -0
  26. package/kits/blank/.castle/agent/messages.json +9 -0
  27. package/kits/blank/.castle/agent/pending-sends.json +1 -0
  28. package/kits/blank/.castle/agent/tasks/index.md +2 -0
  29. package/kits/blank/.castle/docs/platform.md +36 -0
  30. package/kits/blank/castle.json +5 -2
  31. package/kits/blank/node_modules/.vite/deps/_metadata.json +8 -0
  32. package/kits/blank/node_modules/.vite/deps/package.json +3 -0
  33. package/kits/physics-2d/behaviors/Collider.jsx +1 -2
  34. package/kits/physics-2d/behaviors/Joints.jsx +1 -1
  35. package/kits/physics-2d/castle.json +1 -1
  36. package/kits/physics-2d/editors/BlueprintLibrary.jsx +33 -3
  37. package/kits/physics-2d/editors/SceneEditor.jsx +171 -57
  38. package/kits/physics-2d/editors/SingleEditor.jsx +6 -0
  39. package/kits/physics-2d/engine/blueprint.js +106 -14
  40. package/kits/physics-2d/engine/scene.js +9 -2
  41. package/kits/physics-2d/engine/ui.jsx +30 -2
  42. package/kits/physics-2d/engine/ui.module.css +59 -0
  43. package/package.json +1 -1
  44. package/dist/shell/assets/index-DN8HQBnW.css +0 -1
package/dist/api.d.ts CHANGED
@@ -92,6 +92,20 @@ export interface WebDeckSourceUploadConfig {
92
92
  postFields: Record<string, string>;
93
93
  }
94
94
  export declare function createWebDeckSourceUploadConfig(deckId: string): Promise<WebDeckSourceUploadConfig>;
95
+ export interface CauldronServerBundleUploadConfig {
96
+ deckId: string;
97
+ uploadId: string;
98
+ postUrl: string;
99
+ postFields: Record<string, string>;
100
+ }
101
+ export declare function createCauldronServerBundleUploadConfig(deckId: string): Promise<CauldronServerBundleUploadConfig>;
102
+ export interface CauldronServerConfig {
103
+ tickRate: number;
104
+ maxPlayers: number;
105
+ }
106
+ export declare function saveCauldronServerBundle(deckId: string, uploadId: string | null, serverConfig?: CauldronServerConfig): Promise<{
107
+ deckId: string;
108
+ } | null>;
95
109
  export interface WebDeckSource {
96
110
  deckId: string;
97
111
  archiveUrl: string;
package/dist/api.js CHANGED
@@ -203,6 +203,24 @@ export async function createWebDeckSourceUploadConfig(deckId) {
203
203
  handleAPIError(data);
204
204
  return pickData(data, 'createWebDeckSourceUploadConfig');
205
205
  }
206
+ export async function createCauldronServerBundleUploadConfig(deckId) {
207
+ const data = await graphql(`mutation($deckId: ID!) {
208
+ createCauldronServerBundleUploadConfig(deckId: $deckId) {
209
+ deckId uploadId postUrl postFields
210
+ }
211
+ }`, { deckId });
212
+ handleAPIError(data);
213
+ return pickData(data, 'createCauldronServerBundleUploadConfig');
214
+ }
215
+ export async function saveCauldronServerBundle(deckId, uploadId, serverConfig) {
216
+ const data = await graphql(`mutation($deckId: ID!, $uploadId: ID, $config: Json) {
217
+ saveCauldronServerBundle(deckId: $deckId, uploadId: $uploadId, config: $config) {
218
+ deckId
219
+ }
220
+ }`, { deckId, uploadId, ...(serverConfig ? { config: serverConfig } : {}) });
221
+ handleAPIError(data);
222
+ return pickData(data, 'saveCauldronServerBundle');
223
+ }
206
224
  // Title + author, for naming an import. Readable without auth for the same decks
207
225
  // webDeckSource is (unlisted ones), so this works in a sandbox with no login.
208
226
  export async function deckMeta(deckId) {
@@ -13,6 +13,7 @@ export interface HostContext {
13
13
  username: string | null;
14
14
  isAnonymous?: boolean;
15
15
  deepLinkUri?: string | null;
16
+ partyId?: string | null;
16
17
  }
17
18
 
18
19
  export interface GraphqlError {
@@ -45,6 +46,22 @@ export interface HostCapabilities {
45
46
  leaderboardShowsParties?: boolean;
46
47
  onStreakCredit?: (credit: LeaderboardStreakCredit) => void;
47
48
  logAnalyticsEvent?: (event: string, properties: Record<string, unknown>) => void;
49
+ getMultiplayerSession?: (
50
+ params: MultiplayerGetSessionParams,
51
+ ctx: HostContext,
52
+ ) => Promise<MultiplayerGetSessionResult>;
53
+ }
54
+
55
+ export interface MultiplayerGetSessionParams {
56
+ mode: 'named' | 'party' | 'public';
57
+ key?: string | null;
58
+ }
59
+
60
+ export interface MultiplayerGetSessionResult {
61
+ status: 'ok' | 'solo' | 'unavailable';
62
+ url: string | null;
63
+ nonce: string | null;
64
+ sessionId: string | null;
48
65
  }
49
66
 
50
67
  export interface LeaderboardStreakCredit {
@@ -86,6 +86,9 @@ export async function executeCommand(ctx, command, params, capabilities) {
86
86
  }
87
87
  }
88
88
  function runCommand(ctx, command, params, caps) {
89
+ if (command === "multiplayer.getSession" && caps.getMultiplayerSession) {
90
+ return caps.getMultiplayerSession(multiplayerSessionRequest(params), ctx);
91
+ }
89
92
  if (isPlatformCommand(command)) {
90
93
  return runPlatformCommand(ctx, command, params, caps);
91
94
  }
@@ -123,19 +126,19 @@ function runCommand(ctx, command, params, caps) {
123
126
  }
124
127
  }
125
128
  async function multiplayerGetSession(ctx, params, caps) {
129
+ const request = multiplayerSessionRequest(params);
130
+ const deckId = requireDeckId(ctx, "multiplayer.getSession");
131
+ const data = await graphql(caps.graphqlFetch, CAULDRON_MULTIPLAYER_SESSION_QUERY, { deckId, mode: request.mode, key: request.key ?? null, partyId: ctx.partyId ?? null }, "multiplayer.getSession");
132
+ return multiplayerSessionResult(data.getCauldronMultiplayerSession);
133
+ }
134
+ function multiplayerSessionRequest(params) {
126
135
  const mode = asMultiplayerMode(params.mode);
127
- const request = {
136
+ return {
128
137
  mode,
129
138
  key: mode === "named"
130
139
  ? asString(params.key, "key", "multiplayer.getSession")
131
140
  : null,
132
141
  };
133
- if (caps.getMultiplayerSession) {
134
- return caps.getMultiplayerSession(request, ctx);
135
- }
136
- const deckId = requireDeckId(ctx, "multiplayer.getSession");
137
- const data = await graphql(caps.graphqlFetch, CAULDRON_MULTIPLAYER_SESSION_QUERY, { deckId, mode, key: request.key ?? null, partyId: ctx.partyId ?? null }, "multiplayer.getSession");
138
- return multiplayerSessionResult(data.getCauldronMultiplayerSession);
139
142
  }
140
143
  function multiplayerSessionResult(value) {
141
144
  const sessionId = asOptionalString(value?.sessionId);
@@ -18,11 +18,26 @@ export interface CastleJson {
18
18
  agent?: {
19
19
  plan?: 'on' | 'off';
20
20
  };
21
+ server?: {
22
+ main?: string;
23
+ tickRate?: number;
24
+ maxPlayers?: number;
25
+ };
21
26
  importWhenRemixed?: boolean;
22
27
  starterScene?: string;
23
28
  [key: string]: unknown;
24
29
  }
25
30
  export declare const DEFAULT_STARTER_SCENE = "scenes/main.scene";
31
+ export declare const DEFAULT_SERVER_TICK_RATE = 20;
32
+ export declare const DEFAULT_SERVER_MAX_PLAYERS = 8;
33
+ export declare const SERVER_TICK_RATE_CAP = 30;
34
+ export declare const SERVER_MAX_PLAYERS_CAP = 24;
35
+ export interface ResolvedServerConfig {
36
+ entry: string;
37
+ tickRate: number;
38
+ maxPlayers: number;
39
+ }
40
+ export declare function resolveServerConfig(dir: string): ResolvedServerConfig | null;
26
41
  export declare function deckStarterScene(dir: string): string;
27
42
  export declare const DEFAULT_MAIN = "main.jsx";
28
43
  export declare function deckMainFile(dir: string): string;
@@ -7,6 +7,42 @@ import picomatch from 'picomatch';
7
7
  // cycle.
8
8
  export const IMPORTS_DIR = 'imports';
9
9
  export const DEFAULT_STARTER_SCENE = 'scenes/main.scene';
10
+ export const DEFAULT_SERVER_TICK_RATE = 20;
11
+ export const DEFAULT_SERVER_MAX_PLAYERS = 8;
12
+ export const SERVER_TICK_RATE_CAP = 30;
13
+ export const SERVER_MAX_PLAYERS_CAP = 24;
14
+ const DEFAULT_SERVER_ENTRIES = [
15
+ 'server/index.js',
16
+ 'server/index.ts',
17
+ 'server/index.mjs',
18
+ ];
19
+ export function resolveServerConfig(dir) {
20
+ const server = readCastleJson(dir)?.server;
21
+ const declared = typeof server?.main === 'string' ? server.main.trim() : '';
22
+ const entry = declared || DEFAULT_SERVER_ENTRIES.find((candidate) => fs.existsSync(path.join(dir, candidate)));
23
+ if (!entry || !isSafeServerEntry(dir, entry))
24
+ return null;
25
+ return {
26
+ entry,
27
+ tickRate: clampNumber(server?.tickRate, DEFAULT_SERVER_TICK_RATE, 0, SERVER_TICK_RATE_CAP),
28
+ maxPlayers: Math.floor(clampNumber(server?.maxPlayers, DEFAULT_SERVER_MAX_PLAYERS, 1, SERVER_MAX_PLAYERS_CAP)),
29
+ };
30
+ }
31
+ function isSafeServerEntry(dir, entry) {
32
+ if (!/\.(?:js|ts|mjs)$/.test(entry))
33
+ return false;
34
+ const absolute = path.resolve(dir, entry);
35
+ const relative = path.relative(dir, absolute);
36
+ return (relative !== '' &&
37
+ !relative.startsWith(`..${path.sep}`) &&
38
+ relative !== '..' &&
39
+ !path.isAbsolute(relative) &&
40
+ fs.existsSync(absolute));
41
+ }
42
+ function clampNumber(value, fallback, min, max) {
43
+ const number = typeof value === 'number' && Number.isFinite(value) ? value : fallback;
44
+ return Math.min(max, Math.max(min, number));
45
+ }
10
46
  export function deckStarterScene(dir) {
11
47
  const declared = readCastleJson(dir)?.starterScene;
12
48
  return typeof declared === 'string' && declared.trim() ? declared.trim() : DEFAULT_STARTER_SCENE;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,129 @@
1
+ import { pathToFileURL } from 'url';
2
+ import WebSocket from 'ws';
3
+ const PROTOCOL_VERSION = 1;
4
+ class PlatformEvents {
5
+ callbacks = new Map();
6
+ on(event, callback) {
7
+ const callbacks = this.callbacks.get(event) ?? [];
8
+ callbacks.push(callback);
9
+ this.callbacks.set(event, callbacks);
10
+ }
11
+ async emit(event, ...args) {
12
+ for (const callback of this.callbacks.get(event) ?? [])
13
+ await callback(...args);
14
+ }
15
+ }
16
+ const channelUrl = new URL(requiredEnv('CASTLE_DEV_SESSION_CHANNEL_URL'));
17
+ channelUrl.searchParams.set('bootToken', requiredEnv('CASTLE_DEV_SESSION_BOOT_TOKEN'));
18
+ const bundlePath = requiredEnv('CASTLE_DEV_SESSION_BUNDLE_PATH');
19
+ const socket = new WebSocket(channelUrl);
20
+ let events = null;
21
+ let initialized = false;
22
+ let shuttingDown = false;
23
+ let messageQueue = Promise.resolve();
24
+ socket.on('message', (data, isBinary) => {
25
+ messageQueue = messageQueue.then(() => handleMessage(data, isBinary));
26
+ void messageQueue.catch(fail);
27
+ });
28
+ socket.on('error', (error) => console.error(`platform channel error: ${error.message}`));
29
+ socket.on('close', () => {
30
+ if (!shuttingDown)
31
+ process.exit(1);
32
+ });
33
+ async function handleMessage(data, isBinary) {
34
+ if (isBinary)
35
+ throw new Error('platform channel sent a binary frame');
36
+ const frame = parseFrame(data.toString());
37
+ if (!initialized) {
38
+ if (frame.t !== 'init')
39
+ throw new Error('expected init as the first platform frame');
40
+ initialized = true;
41
+ events = new PlatformEvents();
42
+ const bundle = (await import(pathToFileURL(bundlePath).href));
43
+ const boot = bundle.__castleBootSession;
44
+ if (typeof boot !== 'function')
45
+ throw new Error('server bundle has no __castleBootSession export');
46
+ await boot(createPlatformHandle(frame, events));
47
+ send({ protocolVersion: PROTOCOL_VERSION, t: 'ready' });
48
+ return;
49
+ }
50
+ if (!events)
51
+ throw new Error('platform event dispatcher unavailable');
52
+ await dispatch(events, frame);
53
+ }
54
+ function createPlatformHandle(init, platformEvents) {
55
+ const config = asRecord(init.config);
56
+ return {
57
+ send(connId, text) {
58
+ send({ protocolVersion: PROTOCOL_VERSION, t: 'sendTo', playerId: connId, d: text });
59
+ },
60
+ broadcast(text) {
61
+ send({ protocolVersion: PROTOCOL_VERSION, t: 'broadcast', d: text });
62
+ },
63
+ disconnect(connId, code) {
64
+ send({ protocolVersion: PROTOCOL_VERSION, t: 'kick', playerId: connId, reason: String(code) });
65
+ },
66
+ on(event, callback) {
67
+ platformEvents.on(event, callback);
68
+ },
69
+ config: Object.freeze({
70
+ sessionId: String(init.sessionId),
71
+ deckId: String(init.deckId),
72
+ mode: 'named',
73
+ tickRate: Number(config.tickRate),
74
+ maxPlayers: Number(config.maxPlayers),
75
+ }),
76
+ };
77
+ }
78
+ async function dispatch(platformEvents, frame) {
79
+ switch (frame.t) {
80
+ case 'init':
81
+ throw new Error('received duplicate init frame');
82
+ case 'playerJoined': {
83
+ const player = asRecord(frame.player);
84
+ await platformEvents.emit('join', player.playerId, player);
85
+ return;
86
+ }
87
+ case 'playerLeft':
88
+ await platformEvents.emit('leave', frame.playerId);
89
+ return;
90
+ case 'clientMessage':
91
+ await platformEvents.emit('message', frame.playerId, JSON.stringify(frame.d));
92
+ return;
93
+ case 'replaced':
94
+ await platformEvents.emit('replaced');
95
+ return;
96
+ case 'shutdown':
97
+ shuttingDown = true;
98
+ await platformEvents.emit('shutdown', frame.reason);
99
+ socket.close(1000, 'shutdown');
100
+ }
101
+ }
102
+ function parseFrame(text) {
103
+ const value = asRecord(JSON.parse(text));
104
+ if (value.protocolVersion !== PROTOCOL_VERSION || typeof value.t !== 'string') {
105
+ throw new Error('platform channel sent an invalid frame');
106
+ }
107
+ return value;
108
+ }
109
+ function send(frame) {
110
+ if (socket.readyState !== WebSocket.OPEN)
111
+ throw new Error('platform channel is not open');
112
+ socket.send(JSON.stringify(frame));
113
+ }
114
+ function asRecord(value) {
115
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
116
+ throw new Error('platform channel sent an invalid frame');
117
+ }
118
+ return value;
119
+ }
120
+ function requiredEnv(name) {
121
+ const value = process.env[name];
122
+ if (!value)
123
+ throw new Error(`${name} is required`);
124
+ return value;
125
+ }
126
+ function fail(error) {
127
+ console.error(error instanceof Error ? error.stack ?? error.message : String(error));
128
+ process.exit(1);
129
+ }
@@ -0,0 +1,19 @@
1
+ import type { FilesChangedMessage } from './filesChanged.js';
2
+ export interface DevPlayerIdentity {
3
+ userId: string;
4
+ username: string;
5
+ isAnonymous: boolean;
6
+ scopedUserId?: string;
7
+ }
8
+ export interface DevSessionServer {
9
+ readonly port: number;
10
+ readonly sessionId: 'dev';
11
+ mintNonce(author: DevPlayerIdentity): string;
12
+ handleFilesChanged(message: FilesChangedMessage): void;
13
+ shutdown(): Promise<void>;
14
+ shutdownNow(): void;
15
+ }
16
+ export declare function startDevSessionServer(opts: {
17
+ projectDir: string;
18
+ log: (level: 'log' | 'error', text: string) => void;
19
+ }): Promise<DevSessionServer>;