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(replication): the authoritative-host story — RC11 N5

esengine902c1aeba44f
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 200695469..67d99d1cc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -102,6 +102,9 @@ importers:
'@rollup/plugin-typescript':
specifier: ^11.1.5
+ '@types/ws':
+ specifier: ^8.18.1
+ version: 8.18.1
'@vitest/coverage-v8':
specifier: ^2.1.9
version: 2.1.9([email protected])
@@ -132,6 +135,9 @@ importers:
vitest:
specifier: ^2.1.0
+ ws:
+ specifier: ^8.21.0
+ version: 8.21.0
packages:
@@ -672,36 +678,42 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@rolldown/[email protected]':
resolution: {integrity: sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@rolldown/[email protected]':
resolution: {integrity: sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==}
@@ -794,66 +806,79 @@ packages:
resolution: {integrity: sha512-F8sWbhZ7tyuEfsmOxwc2giKDQzN3+kuBLPwwZGyVkLlKGdV1nvnNwYD0fKQ8+XS6hp9nY7B+ZeK01EBUE7aHaw==}
cpu: [arm]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-rGfNUfn0GIeXtBP1wL5MnzSj98+PZe/AXaGBCRmT0ts80lU5CATYGxXukeTX39XBKsxzFpEeK+Mrp9faXOlmrw==}
cpu: [arm]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-MMtej3YHWeg/0klK2Qodf3yrNzz6CGjo2UntLvk2RSPlhzgLvYEB3frRvbEF2wRKh1Z2fDIg9KRPe1fawv7C+g==}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-1a/qhaaOXhqXGpMFMET9VqwZakkljWHLmZOX48R0I/YLbhdxr1m4gtG1Hq7++VhVUmf+L3sTAf9op4JlhQ5u1Q==}
cpu: [arm64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-QWO6RQTZ/cqYtJMtxhkRkidoNGXc7ERPbZN7dVW5SdURuLeVU7lwKMpo18XdcmpWYd0qsP1bwKPf7DNSUinhvA==}
cpu: [loong64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-xpObYIf+8gprgWaPP32xiN5RVTi/s5FCR+XMXSKmhfoJjrpRAjCuuqQXyxUa/eJTdAE6eJ+KDKaoEqjZQxh3Gw==}
cpu: [loong64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-4BrCgrpZo4hvzMDKRqEaW1zeecScDCR+2nZ86ATLhAoJ5FQ+lbHVD3ttKe74/c7tNT9c6F2viwB3ufwp01Oh2w==}
cpu: [ppc64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-NOlUuzesGauESAyEYFSe3QTUguL+lvrN1HtwEEsU2rOwdUDeTMJdO5dUYl/2hKf9jWydJrO9OL/XSSf65R5+Xw==}
cpu: [ppc64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-ptA88htVp0AwUUqhVghwDIKlvJMD/fmL/wrQj99PRHFRAG6Z5nbWoWG4o81Nt9FT+IuqUQi+L31ZKAFeJ5Is+A==}
cpu: [riscv64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-S51t7aMMTNdmAMPpBg7OOsTdn4tySRQvklmL3RpDRyknk87+Sp3xaumlatU+ppQ+5raY7sSTcC2beGgvhENfuw==}
cpu: [riscv64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-Bl00OFnVFkL82FHbEqy3k5CUCKH6OEJL54KCyx2oqsmZnFTR8IoNqBF+mjQVcRCT5sB6yOvK8A37LNm/kPJiZg==}
cpu: [s390x]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-ABca4ceT4N+Tv/GtotnWAeXZUZuM/9AQyCyKYyKnpk4yoA7QIAuBt6Hkgpw8kActYlew2mvckXkvx0FfoInnLg==}
cpu: [x64]
os: [linux]
+ libc: [glibc]
'@rollup/[email protected]':
resolution: {integrity: sha512-HFps0JeGtuOR2convgRRkHCekD7j+gdAuXM+/i6kGzQtFhlCtQkpwtNzkNj6QhCDp7DRJ7+qC/1Vg2jt5iSOFw==}
cpu: [x64]
os: [linux]
+ libc: [musl]
'@rollup/[email protected]':
resolution: {integrity: sha512-H+hXEv9gdVQuDTgnqD+SQffoWoc0Of59AStSzTEj/feWTBAnSfSD3+Dql1ZruJQxmykT/JVY0dE8Ka7z0DH1hw==}
@@ -937,6 +962,9 @@ packages:
resolution: {integrity: sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
+
'@vitejs/[email protected]':
resolution: {integrity: sha512-DlSMqo4WhThw4vB8Mpn0Woe9J+Jfq1geJ61AKW0QEgLzGMNwtIMdxbDUzLxcun8W7NbJO0e2Jg/Nxm3cCSVzzg==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -1914,24 +1942,28 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [glibc]
resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ libc: [musl]
resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
@@ -2913,6 +2945,18 @@ packages:
utf-8-validate:
optional: true
+ resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==}
+ engines: {node: '>=10.0.0'}
+ peerDependencies:
+ bufferutil: ^4.0.1
+ utf-8-validate: '>=5.0.2'
+ peerDependenciesMeta:
+ bufferutil:
+ optional: true
+ utf-8-validate:
+ optional: true
+
resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}
engines: {node: '>=18'}
@@ -3621,6 +3665,10 @@ snapshots:
dependencies:
'@types/node': 25.9.3
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 25.9.3
+
dependencies:
'@rolldown/pluginutils': 1.0.1
@@ -5746,6 +5794,8 @@ snapshots:
optional: true
+
optional: true
diff --git a/sdk/package.json b/sdk/package.json
index b12463df0..83b1ca184 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -6,7 +6,8 @@
"sideEffects": [
"./dist/index.js",
"./dist/index.wechat.js",
- "./dist/index.wechat.cjs.js"
+ "./dist/index.wechat.cjs.js",
+ "./dist/index.node.js"
],
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -22,6 +23,10 @@
"./wechat": {
"import": "./dist/index.wechat.js"
},
+ "./node": {
+ "import": "./dist/index.node.js",
+ "types": "./dist/index.node.d.ts"
+ },
"./spine": {
"import": "./dist/spine/index.js",
"types": "./dist/spine/index.d.ts"
@@ -62,6 +67,7 @@
"devDependencies": {
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.5",
+ "@types/ws": "^8.18.1",
"@vitest/coverage-v8": "^2.1.9",
"@vitest/ui": "^2.1.0",
"happy-dom": "^15.11.0",
@@ -71,7 +77,8 @@
"rollup-plugin-dts": "^6.1.0",
"tslib": "^2.6.2",
"typescript": "^5.3.0",
- "vitest": "^2.1.0"
+ "vitest": "^2.1.0",
+ "ws": "^8.21.0"
},
"repository": {
"type": "git",
diff --git a/sdk/rollup.config.js b/sdk/rollup.config.js
index 85eccbc19..2bf973fa0 100644
--- a/sdk/rollup.config.js
+++ b/sdk/rollup.config.js
@@ -4,7 +4,7 @@ import typescript from '@rollup/plugin-typescript';
import terser from '@rollup/plugin-terser';
import dts from 'rollup-plugin-dts';
-const ENTRY_FILES = ['/index.ts', '/index.wechat.ts'];
+const ENTRY_FILES = ['/index.ts', '/index.wechat.ts', '/index.node.ts'];
const treeshake = {
moduleSideEffects: (id) => ENTRY_FILES.some(e => id.endsWith(e)),
};
@@ -47,12 +47,20 @@ const esmBuilds = [
plugins: [typescript({ tsconfig: './tsconfig.json', declaration: false }), terser({ format: { comments: (_, comment) => comment.value.includes('@vite-ignore') } })],
treeshake,
},
+ {
+ input: 'src/index.node.ts',
+ output: { file: 'dist/index.node.js', format: 'esm', sourcemap: true },
+ external: (id) => id.startsWith('node:'),
+ plugins: [typescript({ tsconfig: './tsconfig.json', declaration: false }), terser({ format: { comments: (_, comment) => comment.value.includes('@vite-ignore') } })],
+ treeshake,
+ },
];
const dtsBuilds = [
{
input: {
'index': 'src/index.ts',
+ 'index.node': 'src/index.node.ts',
'physics/index': 'src/physics/index.ts',
'spine/index': 'src/spine/index.ts',
'wasm': 'src/wasm.ts',
diff --git a/sdk/src/audio/NullAudioBackend.ts b/sdk/src/audio/NullAudioBackend.ts
new file mode 100644
index 000000000..914883cdc
--- /dev/null
+++ b/sdk/src/audio/NullAudioBackend.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file NullAudioBackend.ts
+ * @brief A silent PlatformAudioBackend for hosts with no audio device — the
+ * headless Node server, muted embeds, tests. Every call succeeds and
+ * does nothing, so gameplay code that plays sounds runs unchanged on
+ * an authoritative server.
+ */
+import type { AudioMixer } from './AudioMixer';
+import type {
+ AudioBackendInitOptions, AudioBufferHandle, AudioHandle,
+ PlatformAudioBackend, PlayConfig,
+} from './PlatformAudioBackend';
+
+class NullAudioHandle implements AudioHandle {
+ constructor(readonly id: number) {}
+ stop(): void {}
+ pause(): void {}
+ resume(): void {}
+ setVolume(): void {}
+ setPan(): void {}
+ setLoop(): void {}
+ setPlaybackRate(): void {}
+ get isPlaying(): boolean { return false; }
+ get currentTime(): number { return 0; }
+ get duration(): number { return 0; }
+}
+
+export class NullAudioBackend implements PlatformAudioBackend {
+ readonly name = 'null';
+ readonly mixer: AudioMixer | null = null;
+ readonly isReady = true;
+ private nextId_ = 1;
+
+ async initialize(_options?: AudioBackendInitOptions): Promise<void> {}
+ async ensureResumed(): Promise<void> {}
+
+ async loadBuffer(_url: string): Promise<AudioBufferHandle> {
+ return { id: this.nextId_++, duration: 0, bytes: 0 };
+ }
+
+ async loadBufferFromData(_url: string, _data: ArrayBuffer): Promise<AudioBufferHandle> {
+ return { id: this.nextId_++, duration: 0, bytes: 0 };
+ }
+
+ unloadBuffer(_handle: AudioBufferHandle): void {}
+
+ play(_buffer: AudioBufferHandle, _config: PlayConfig): AudioHandle {
+ return new NullAudioHandle(this.nextId_++);
+ }
+
+ suspend(): void {}
+ resume(): void {}
+ dispose(): void {}
+}
diff --git a/sdk/src/index.node.ts b/sdk/src/index.node.ts
new file mode 100644
index 000000000..a931269c6
--- /dev/null
+++ b/sdk/src/index.node.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.node.ts
+ * @brief ESEngine SDK — Node entry point (authoritative game servers,
+ * headless tooling). Same engine wasm, same gameplay code, no
+ * presentation. Boot shape:
+ *
+ * import { loadEsengineModule, createHeadlessApp, runHeadless, Net } from 'esengine/node';
+ * const module = await loadEsengineModule('./wasm');
+ * const app = createHeadlessApp(module);
+ * const server = app.getResource(Net).startServer();
+ * // accept sockets however the host likes → server.attachConnection(transport)
+ * runHeadless(app);
+ */
+import { setPlatform } from './platform';
+import { nodeAdapter } from './platform/node';
+import { ensureBuiltinComponentsRegistered, markEngineComponentBaseline } from './component';
+import type { ESEngineModule } from './wasm';
+
+setPlatform(nodeAdapter);
+
+// Register every engine component (COMPONENT_META) so scenes never silently drop
+// a component that exists in the engine but lacks a typed const.
+ensureBuiltinComponentsRegistered();
+markEngineComponentBaseline();
+
+export * from './core';
+export * from './webAppFactory';
+export { nodeAdapter } from './platform/node';
+
+/**
+ * Load the engine wasm module from a directory holding the web build
+ * artifacts (esengine.js + esengine.wasm) — the emscripten glue runs natively
+ * under Node. `dir` is filesystem-relative to the process cwd.
+ */
+export async function loadEsengineModule(dir: string): Promise<ESEngineModule> {
+ const { readFile } = await import('node:fs/promises');
+ const { join, resolve } = await import('node:path');
+ const { pathToFileURL } = await import('node:url');
+ const wasmBinary = await readFile(join(dir, 'esengine.wasm'));
+ const glueUrl = pathToFileURL(resolve(join(dir, 'esengine.js'))).href;
+ const factory = (await import(/* @vite-ignore */ glueUrl)).default;
+ return await factory({ wasmBinary }) as ESEngineModule;
+}
diff --git a/sdk/src/lifecycle.ts b/sdk/src/lifecycle.ts
index 3ccefa980..fa69476c7 100644
--- a/sdk/src/lifecycle.ts
+++ b/sdk/src/lifecycle.ts
@@ -111,9 +111,11 @@ export const lifecyclePlugin = (options?: LifecyclePluginOptions): Plugin => {
if (platformType === 'wechat') {
setupWeChatLifecycle_(manager, app);
- } else {
+ } else if (typeof document !== 'undefined' && typeof window !== 'undefined') {
cleanupFn_ = setupWebLifecycle_(manager, app);
}
+ // Headless hosts (node server, workers) have no visibility/focus
+ // signal — the Lifecycle resource still exists, always visible.
},
cleanup() {
cleanupFn_?.();
diff --git a/sdk/src/platform/node.ts b/sdk/src/platform/node.ts
new file mode 100644
index 000000000..eb5a1f524
--- /dev/null
+++ b/sdk/src/platform/node.ts
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file node.ts
+ * @brief Node platform adapter — the authoritative-server host. The same
+ * engine wasm + SDK gameplay code runs headless: filesystem-first
+ * asset access (http(s) URLs still fetch), sockets over the global
+ * WebSocket (Node ≥ 22), silent audio, no DOM. Anything that
+ * fundamentally needs a render host (image decode, canvas) fails
+ * loud rather than pretending.
+ */
+import { readFile as fsReadFile, access } from 'node:fs/promises';
+import type {
+ PlatformAdapter,
+ PlatformRequestOptions,
+ PlatformResponse,
+ WasmInstantiateResult,
+ InputEventCallbacks,
+ ImageLoadResult,
+ PlatformSocket,
+ PlatformSocketOptions,
+} from './types';
+import type { PlatformAudioBackend } from '../audio/PlatformAudioBackend';
+import { NullAudioBackend } from '../audio/NullAudioBackend';
+import { GameSocket } from '../net/GameSocket';
+
+function isUrl(path: string): boolean {
+ return /^https?:\/\//.test(path);
+}
+
+class NodePlatformAdapter implements PlatformAdapter {
+ readonly name = 'node' as const;
+ private readonly storage_ = new Map<string, string>();
+
+ async fetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse> {
+ if (!isUrl(url)) {
+ // Local project files resolve through the filesystem so a server
+ // can point straight at a cooked build directory.
+ const buffer = await this.readFile(url);
+ const text = () => Promise.resolve(new TextDecoder().decode(buffer));
+ return {
+ ok: true,
+ status: 200,
+ statusText: 'OK',
+ headers: {},
+ json: async <T>() => JSON.parse(await text()) as T,
+ text,
+ arrayBuffer: () => Promise.resolve(buffer),
+ };
+ }
+ const response = await globalThis.fetch(url, {
+ method: options?.method ?? 'GET',
+ headers: options?.headers,
+ body: options?.body,
+ });
+ const headers: Record<string, string> = {};
+ response.headers.forEach((value, key) => { headers[key] = value; });
+ return {
+ ok: response.ok,
+ status: response.status,
+ statusText: response.statusText,
+ headers,
+ json: <T>() => response.json() as Promise<T>,
+ text: () => response.text(),
+ arrayBuffer: () => response.arrayBuffer(),
+ };
+ }
+
+ async readFile(path: string): Promise<ArrayBuffer> {
+ if (isUrl(path)) {
+ const res = await this.fetch(path);
+ if (!res.ok) throw new Error(`Failed to read file: ${path} (${res.status})`);
+ return res.arrayBuffer();
+ }
+ const buf = await fsReadFile(path);
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer;
+ }
+
+ async readTextFile(path: string): Promise<string> {
+ return new TextDecoder().decode(await this.readFile(path));
+ }
+
+ async fileExists(path: string): Promise<boolean> {
+ if (isUrl(path)) {
+ try {
+ const res = await globalThis.fetch(path, { method: 'HEAD' });
+ return res.ok;
+ } catch {
+ return false;
+ }
+ }
+ try {
+ await access(path);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ async loadImagePixels(_path: string): Promise<ImageLoadResult> {
+ throw new Error(
+ '[node] image decode needs a render host — a headless server must not load textures ' +
+ '(load gameplay data only, or run a renderer-equipped host)');
+ }
+
+ async instantiateWasm(
+ pathOrBuffer: string | ArrayBuffer,
+ imports: WebAssembly.Imports,
+ ): Promise<WasmInstantiateResult> {
+ const buffer = typeof pathOrBuffer === 'string' ? await this.readFile(pathOrBuffer) : pathOrBuffer;
+ const { instance, module } = await WebAssembly.instantiate(buffer, imports);
+ return { instance, module };
+ }
+
+ createCanvas(_width: number, _height: number): HTMLCanvasElement {
+ throw new Error('[node] no canvas on a headless host');
+ }
+
+ createImage(): HTMLImageElement {
+ throw new Error('[node] no DOM images on a headless host');
+ }
+
+ now(): number {
+ return performance.now();
+ }
+
+ bindInputEvents(_callbacks: InputEventCallbacks): void {
+ // No local input device — player input arrives over the network.
+ }
+
+ createAudioBackend(): PlatformAudioBackend {
+ return new NullAudioBackend();
+ }
+
+ createSocket(options: PlatformSocketOptions): PlatformSocket {
+ // Node ≥ 22 ships a spec-compliant global WebSocket client.
+ return new GameSocket(options);
+ }
+
+ devicePixelRatio(): number {
+ return 1;
+ }
+
+ getStorageItem(key: string): string | null {
+ return this.storage_.get(key) ?? null;
+ }
+
+ setStorageItem(key: string, value: string): void {
+ this.storage_.set(key, value);
+ }
+
+ removeStorageItem(key: string): void {
+ this.storage_.delete(key);
+ }
+
+ clearStorage(prefix: string): void {
+ for (const k of [...this.storage_.keys()]) {
+ if (k.startsWith(prefix)) this.storage_.delete(k);
+ }
+ }
+}
+
+export const nodeAdapter = new NodePlatformAdapter();
diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.ts
index 277157485..85a9a4e14 100644
--- a/sdk/src/webAppFactory.ts
+++ b/sdk/src/webAppFactory.ts
@@ -1,8 +1,11 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { createWebApp as _createWebApp, type WebAppOptions } from './app';
-import type { App } from './app';
-import type { ESEngineModule } from './wasm';
+import { App, createWebApp as _createWebApp, type Plugin, type WebAppOptions } from './app';
+import type { CppRegistry, ESEngineModule } from './wasm';
+import { assetPlugin } from './asset';
+import { prefabsPlugin } from './prefabServer';
+import { sceneManagerPlugin } from './scenePlugin';
+import { seedEngineComponents } from './component';
import { uiPlugins } from './uiPlugins';
import { animationPlugin } from './animation';
import { audioPlugin } from './audio';
@@ -71,3 +74,62 @@ export function createWebApp(module: ESEngineModule, options?: CreateWebAppOptio
const plugins = [...uiPlugins, ...basePlugins, spinePlugin, ...(options?.plugins ?? [])];
return _createWebApp(module, { ...options, sideModules, plugins });
}
+
+export interface HeadlessAppOptions {
+ plugins?: Plugin[];
+ /** Optional-native-module acquirer (physics on the server). */
+ sideModules?: SideModuleHost;
+}
+
+// The simulation-relevant plugin set: timers/lifecycle, gameplay AI, audio
+// (silent on hosts without a device) and replication. Presentation plugins
+// (particles, tilemap render, post-process, timeline, UI, spine) stay out —
+// they exist to be seen.
+const headlessBasePlugins = (): Plugin[] => [
+ timerPlugin, lifecyclePlugin(), audioPlugin,
+ perceptionPlugin, fsmPlugin, btPlugin, navPlugin, replicationPlugin,
+];
+
+/**
+ * An App with the full simulation stack and no presentation: no renderer, no
+ * render pipeline, no input device, no UI. This is the authoritative-server
+ * shape (same wasm module, same gameplay code, same fixed-tick loop) — also
+ * useful for workers and tests. Drive it with {@link runHeadless} or
+ * `app.tick(dt)`.
+ */
+export function createHeadlessApp(module: ESEngineModule, options?: HeadlessAppOptions): App {
+ seedEngineComponents();
+ const app = App.new();
+ if (options?.sideModules) app.setSideModules(options.sideModules);
+ const cppRegistry = new module.Registry() as unknown as CppRegistry;
+ app.connectCpp(cppRegistry, module, { strict: true });
+
+ // No corePlugin: it wires the render facades (ResourceManager, draw,
+ // material, post-process) that only exist after initRenderer().
+ app.addPlugin(assetPlugin);
+ app.addPlugin(prefabsPlugin);
+ app.addPlugin(sceneManagerPlugin);
+ app.addPlugins(headlessBasePlugins());
+ if (options?.plugins) app.addPlugins(options.plugins);
+ return app;
+}
+
+/**
+ * Drive an app on a wall-clock interval (no requestAnimationFrame on a
+ * server). Delta is measured, so the fixed-step accumulator keeps simulation
+ * cadence exact across timer jitter. Returns a stop function.
+ */
+export function runHeadless(app: App, options?: { fps?: number }): () => void {
+ const intervalMs = 1000 / (options?.fps ?? 60);
+ let last = Date.now();
+ let ticking = false;
+ const timer = setInterval(() => {
+ if (ticking) return; // a slow async tick must not pile up re-entrantly
+ const now = Date.now();
+ const delta = (now - last) / 1000;
+ last = now;
+ ticking = true;
+ void app.tick(delta).finally(() => { ticking = false; });
+ }, intervalMs);
+ return () => clearInterval(timer);
+}
diff --git a/sdk/tests/replication-e2e-ws.test.ts b/sdk/tests/replication-e2e-ws.test.ts
new file mode 100644
index 000000000..12d5a6d23
--- /dev/null
+++ b/sdk/tests/replication-e2e-ws.test.ts
@@ -0,0 +1,122 @@
+// @vitest-environment node
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file RC11 N5: the authoritative-host story over a real network stack —
+ * a headless server App (createHeadlessApp, real wasm, no renderer)
+ * accepts a `ws` WebSocket connection; the client rides GameSocket on
+ * the global WebSocket. Same engine, same gameplay code, loopback TCP
+ * in between.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { WebSocketServer, type WebSocket as WsSocket } from 'ws';
+import { App } from '../src/app';
+import { createHeadlessApp } from '../src/webAppFactory';
+import { defineComponent, clearUserComponents, Transform } from '../src/component';
+import type { ESEngineModule } from '../src/wasm';
+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
+import { GameSocket } from '../src/net/GameSocket';
+import type { NetTransport } from '../src/net/NetChannel';
+import { replicationPlugin, Net, Replicated } from '../src/net/replication';
+import { setPlatform } from '../src/platform/base';
+import { nodeAdapter } from '../src/platform/node';
+
+// What the esengine/node entry does for a real server host.
+setPlatform(nodeAdapter);
+
+const STEP = 1 / 60;
+const delay = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/** Server-side end of one accepted `ws` connection as a NetTransport. */
+function wsServerTransport(conn: WsSocket): NetTransport {
+ const t: NetTransport = {
+ onMessage: null,
+ send: (d) => conn.send(d),
+ };
+ conn.on('message', (data, isBinary) => {
+ if (isBinary) {
+ const buf = data as Buffer;
+ t.onMessage?.(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer);
+ } else {
+ t.onMessage?.(data.toString());
+ }
+ });
+ return t;
+}
+
+describe.skipIf(!HAS_WASM)('replication e2e over real WebSocket', () => {
+ let module: ESEngineModule;
+ let wss: WebSocketServer;
+ let port: number;
+
+ beforeAll(async () => {
+ module = await loadWasmModule();
+ wss = new WebSocketServer({ port: 0, host: '127.0.0.1' });
+ await new Promise<void>((r) => wss.on('listening', () => r()));
+ port = (wss.address() as { port: number }).port;
+ });
+
+ afterAll(async () => {
+ await new Promise<void>((r) => wss.close(() => r()));
+ });
+
+ it('a headless server replicates to a socket client end-to-end', async () => {
+ clearUserComponents();
+ const NetHealth = defineComponent('NetHealth', { hp: 100 }, { replicatedFields: ['hp'] });
+
+ // The authoritative host: headless factory, real wasm, no renderer.
+ const serverApp = createHeadlessApp(module);
+ const server = serverApp.getResource(Net).startServer();
+ wss.on('connection', (conn) => server.attachConnection(wsServerTransport(conn)));
+
+ // The client rides the same socket class shipped games use.
+ const clientApp = App.new();
+ const clientRegistry = new (module as any).Registry();
+ clientApp.connectCpp(clientRegistry, module);
+ clientApp.addPlugin(replicationPlugin);
+
+ const socket = new GameSocket({ url: `ws://127.0.0.1:${port}` });
+ socket.connect();
+ const client = await clientApp.getResource(Net).connect(socket, { interpolationDelayTicks: 0 });
+ expect(client.connected).toBe(true);
+
+ // Authoritative spawn: an annotated builtin + a user component.
+ const e = serverApp.world.spawn('boss');
+ serverApp.world.insert(e, Transform, { position: { x: 64, y: -8, z: 0 } });
+ serverApp.world.insert(e, NetHealth, { hp: 250 });
+ serverApp.world.insert(e, Replicated, {});
+ await serverApp.tick(STEP);
+
+ await delay(50); // real network delivery
+ await clientApp.tick(STEP);
+
+ const ghosts = clientApp.world.getEntitiesWithComponents([Replicated]);
+ expect(ghosts).toHaveLength(1);
+ const ghost = ghosts[0];
+ expect(clientApp.world.tryGet(ghost, Transform)!.position.x).toBe(64);
+ expect(clientApp.world.tryGet(ghost, NetHealth)!.hp).toBe(250);
+
+ // Authoritative mutation streams as a binary delta over the wire.
+ const t = serverApp.world.tryGet(e, Transform)!;
+ t.position.x = -128.5;
+ serverApp.world.set(e, Transform, t);
+ const h = serverApp.world.tryGet(e, NetHealth)!;
+ h.hp = 1;
+ serverApp.world.set(e, NetHealth, h);
+ await serverApp.tick(STEP);
+
+ await delay(50);
+ await clientApp.tick(STEP);
+ expect(clientApp.world.tryGet(ghost, Transform)!.position.x).toBe(-128.5);
+ expect(clientApp.world.tryGet(ghost, NetHealth)!.hp).toBe(1);
+
+ // Input uplink back over the same socket.
+ client.sendInput({ fire: true });
+ await delay(50);
+ const connId = client.connectionId;
+ expect(server.inputOf(connId)!.actions).toEqual({ fire: true });
+
+ client.disconnect();
+ socket.close();
+ });
+});