Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): typed, versioned play-realm protocol contract (RC10 P0+P1)

esengine8bea40cd2ede
diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.ts
index e3c726077..70a80280f 100644
--- a/desktop/src/engine/PlayRealm.ts
+++ b/desktop/src/engine/PlayRealm.ts
@@ -12,17 +12,12 @@
* touched, so there is nothing to restore.
*/
import { createStore } from 'zustand/vanilla';
-import type { SceneData, PhysicsPluginConfig, SubsystemStatus } from 'esengine';
-import { LogStore, type LogLevel } from '@/store/LogStore';
-
-export interface PlayPayload {
- sceneData: SceneData;
- assetManifest: Record<string, string>;
- /** Project-declared physics enable (features.physics) — forwarded to the realm. */
- physicsEnabled?: boolean;
- /** Project physics world config (gravity, solver, collision matrix) — forwarded to the realm. */
- physicsConfig?: PhysicsPluginConfig;
-}
+import type { SubsystemStatus } from 'esengine';
+import { LogStore } from '@/store/LogStore';
+import { playProtocolMismatch } from './playProtocol';
+import type { PlayOutbound, PlayInbound, PlayPayload, PlaySnapshot } from './playProtocol';
+
+export type { PlayPayload, PlaySnapshot } from './playProtocol';
export interface PlayRealmSnapshot {
playing: boolean;
@@ -30,13 +25,6 @@ export interface PlayRealmSnapshot {
error: string | null;
}
-/** A live inspect snapshot: a shallow entity tree (Outliner) + the selected
- * entity's full data (Details). See PlayRealm.snapshot. */
-export interface PlaySnapshot {
- tree: SceneData;
- selected: SceneData['entities'][number] | null;
-}
-
class PlayRealmImpl {
private iframe: HTMLIFrameElement | null = null;
private payload: PlayPayload | null = null;
@@ -149,21 +137,27 @@ class PlayRealmImpl {
this.post({ type: 'estella:play:setField', entityId, comp, key, value });
}
- private post(message: Record<string, unknown>): void {
+ private post(message: PlayOutbound): void {
this.iframe?.contentWindow?.postMessage(message, '*');
}
private onMessage = (e: MessageEvent): void => {
if (!this.iframe || e.source !== this.iframe.contentWindow) return;
- const data = e.data as
- | { type?: string; message?: string; reqId?: number; data?: unknown; level?: LogLevel; line?: string }
- | null;
+ const data = e.data as PlayInbound | null;
if (!data?.type) return;
switch (data.type) {
- case 'estella:play:hello':
- // Realm mounted + listening — hand it the scene snapshot.
+ case 'estella:play:hello': {
+ // Realm mounted + listening. Verify the protocol contract before handing over
+ // the scene — a version mismatch is a stale realm bundle, surfaced as an error
+ // rather than a baffling downstream failure on an unknown message shape.
+ const mismatch = playProtocolMismatch(data.protocolVersion);
+ if (mismatch) {
+ this.set({ error: mismatch });
+ break;
+ }
if (this.payload) this.post({ type: 'estella:play:init', ...this.payload });
break;
+ }
case 'estella:play:log':
// The running game's console/wasm output, forwarded from the realm iframe so
// it lands in the editor's Output Log (it runs in a separate JS realm, so the
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
new file mode 100644
index 000000000..e4ccc84e3
--- /dev/null
+++ b/desktop/src/engine/playProtocol.ts
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file playProtocol.ts — the single typed contract for the editor↔play-realm
+ * postMessage boundary (RC10). Both ends import these discriminated unions
+ * so the message shapes can't drift: the editor controller (PlayRealm.ts)
+ * and the realm-side host (playHost.ts, esbuilt with esengine external).
+ *
+ * Keep this module dependency-free beyond `import type` from esengine —
+ * playHost's esbuild has no '@/' alias and inlines local imports, so a value
+ * import of an editor module here would break the realm bundle. Type-only
+ * imports are erased before resolution and are safe.
+ */
+import type { SceneData, PhysicsPluginConfig } from 'esengine';
+
+/**
+ * Editor↔realm message-contract version. The realm reports it in `hello`; the editor
+ * compares it against its own and refuses a mismatch (P1) rather than failing
+ * obscurely on a shape it doesn't understand. Bump on any incompatible message change.
+ */
+export const PLAY_PROTOCOL_VERSION = 1;
+
+/**
+ * The handshake check: `null` if the realm's reported protocol version is compatible
+ * with this editor build, else a human-readable error. The editor calls this on the
+ * realm's `hello` and refuses to hand over the scene on a mismatch — a stale realm
+ * bundle (editor and running game built from different versions) fails loudly with a
+ * "rebuild" hint instead of silently mis-handling a message shape it doesn't share.
+ */
+export function playProtocolMismatch(realmVersion: number | undefined): string | null {
+ if (realmVersion === PLAY_PROTOCOL_VERSION) return null;
+ return `Play realm protocol v${realmVersion ?? '?'} ≠ editor v${PLAY_PROTOCOL_VERSION}. `
+ + `Rebuild the play realm — the editor and the running game were built from different versions.`;
+}
+
+/** Matches LogStore's LogLevel; redeclared here to keep the contract editor-dep-free. */
+export type PlayLogLevel = 'info' | 'warn' | 'error';
+
+/** The scene + project config handed to a fresh realm on boot. */
+export interface PlayPayload {
+ sceneData: SceneData;
+ assetManifest: Record<string, string>;
+ /** Project-declared physics enable (features.physics) — forwarded to the realm. */
+ physicsEnabled?: boolean;
+ /** Project physics world config (gravity, solver, collision matrix) — forwarded. */
+ physicsConfig?: PhysicsPluginConfig;
+}
+
+/** A live inspect snapshot: a shallow entity tree (Outliner) + the selected entity's
+ * full data (Details). The reply payload of a `query { kind: 'snapshot' }`. */
+export interface PlaySnapshot {
+ tree: SceneData;
+ selected: SceneData['entities'][number] | null;
+}
+
+export type PlayQueryKind = 'snapshot' | 'subsystems' | 'stats';
+
+/** editor → realm. Discriminated by `type`. */
+export type PlayOutbound =
+ | ({ type: 'estella:play:init' } & PlayPayload)
+ | { type: 'estella:play:setPaused'; paused: boolean }
+ | { type: 'estella:play:reload' }
+ | { type: 'estella:play:query'; kind: PlayQueryKind; reqId: number; selectedId?: number | null }
+ | { type: 'estella:play:setField'; entityId: number; comp: string; key: string; value: unknown };
+
+/** realm → editor. Discriminated by `type`. */
+export type PlayInbound =
+ | { type: 'estella:play:hello'; protocolVersion: number }
+ | { type: 'estella:play:ready' }
+ | { type: 'estella:play:error'; message: string }
+ | { type: 'estella:play:log'; level: PlayLogLevel; line: string }
+ | { type: 'estella:play:reply'; reqId: number; data: unknown };
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index fcad8c376..f2696945e 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -15,7 +15,9 @@
* sidestepping the custom-scheme cross-fetch ban.
*/
import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, getComponent, clearUserComponents } from 'esengine';
-import type { App, ESEngineModule, SceneData, PhysicsPluginConfig } from 'esengine';
+import type { App, ESEngineModule, SceneData } from 'esengine';
+import { PLAY_PROTOCOL_VERSION } from './engine/playProtocol';
+import type { PlayOutbound, PlayInbound } from './engine/playProtocol';
type LiveEntity = SceneData['entities'][number];
@@ -75,13 +77,7 @@ function liveSnapshot(world: App['world'], selectedId: number | null): { tree: S
return { tree, selected };
}
-interface InitMessage {
- type: 'estella:play:init';
- sceneData: SceneData;
- assetManifest: Record<string, string>;
- physicsEnabled?: boolean;
- physicsConfig?: PhysicsPluginConfig;
-}
+type InitMessage = Extract<PlayOutbound, { type: 'estella:play:init' }>;
const canvas = document.getElementById('canvas') as HTMLCanvasElement;
const wasmBase = new URL('./wasm/', import.meta.url).href; // sibling of host.js
@@ -104,7 +100,7 @@ let glHandle = 0;
let lastInit: InitMessage | null = null;
let booted = false;
let reloadSeq = 0;
-const post = (m: Record<string, unknown>) => parent.postMessage(m, '*');
+const post = (m: PlayInbound) => parent.postMessage(m, '*');
// Forward the running game's console output to the editor's Output Log. The realm is
// a separate JS realm, so the editor's console patch never sees these — mirror each
@@ -276,7 +272,7 @@ function setField(entityId: number, comp: string, key: string, value: unknown):
}
window.addEventListener('message', (e: MessageEvent) => {
- const data = e.data as { type?: string; paused?: boolean; reqId?: number; kind?: string; entityId?: number; comp?: string; key?: string; value?: unknown; selectedId?: number } | null;
+ const data = e.data as PlayOutbound | null;
if (!data || typeof data !== 'object') return;
switch (data.type) {
case 'estella:play:init':
@@ -309,4 +305,4 @@ window.addEventListener('message', (e: MessageEvent) => {
}
});
-post({ type: 'estella:play:hello' });
+post({ type: 'estella:play:hello', protocolVersion: PLAY_PROTOCOL_VERSION });
diff --git a/desktop/tests/play-protocol.test.ts b/desktop/tests/play-protocol.test.ts
new file mode 100644
index 000000000..dd8d08655
--- /dev/null
+++ b/desktop/tests/play-protocol.test.ts
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { PLAY_PROTOCOL_VERSION, playProtocolMismatch } from '@/engine/playProtocol';
+
+// RC10 P1: the editor↔play-realm version handshake. The realm reports its protocol
+// version in `hello`; the editor refuses to proceed on a mismatch (a stale realm
+// bundle) instead of failing obscurely on an unknown message shape.
+describe('play protocol handshake', () => {
+ it('accepts a matching protocol version', () => {
+ expect(playProtocolMismatch(PLAY_PROTOCOL_VERSION)).toBeNull();
+ });
+
+ it('rejects an older/newer realm with a rebuild hint', () => {
+ const older = playProtocolMismatch(PLAY_PROTOCOL_VERSION - 1);
+ expect(older).not.toBeNull();
+ expect(older).toContain('Rebuild');
+ expect(playProtocolMismatch(PLAY_PROTOCOL_VERSION + 1)).not.toBeNull();
+ });
+
+ it('rejects a pre-handshake realm that reports no version', () => {
+ // An old realm bundle (built before the handshake) sends `hello` with no
+ // protocolVersion → undefined → mismatch, not a silent pass.
+ expect(playProtocolMismatch(undefined)).not.toBeNull();
+ });
+});