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): ship export matches the realm — custom systems run in the game (IM4)

esengine8a4eda0ebc5b
diff --git a/desktop/electron/buildPlayRealm.ts b/desktop/electron/buildPlayRealm.ts
index 9da74662b..eb0976d3f 100644
--- a/desktop/electron/buildPlayRealm.ts
+++ b/desktop/electron/buildPlayRealm.ts
@@ -25,7 +25,10 @@ const PLAY_DIR = '.esengine/play';
// Subpath exports can't be a single `esengine/` → `./sdk/` mapping (import maps
// don't append /index.js for directories), so list the real files (mirrors
// sdk/package.json `exports`).
-const IMPORT_MAP = {
+// The realm + the shipped game share this import map (esengine → ./sdk) and the
+// CSP hash for the inline <script type=importmap>. Subpath exports are listed
+// explicitly (import maps don't append /index.js for a directory).
+export const IMPORT_MAP = {
imports: {
esengine: './sdk/index.js',
'esengine/spine': './sdk/spine/index.js',
@@ -34,20 +37,19 @@ const IMPORT_MAP = {
'esengine/factory': './sdk/webAppFactory.js',
},
};
+export const IMPORT_MAP_JSON = JSON.stringify(IMPORT_MAP);
+export const IMPORT_MAP_CSP_HASH = `sha256-${createHash('sha256').update(IMPORT_MAP_JSON).digest('base64')}`;
// The inline import map is an inline <script>, so CSP must allow it — by HASH
// (not 'unsafe-inline', which would permit any inline script). 'unsafe-eval' is
// for the emscripten glue; everything else is same-origin estella://.
-const IMPORT_MAP_JSON = JSON.stringify(IMPORT_MAP);
-const IMPORT_MAP_HASH = `sha256-${createHash('sha256').update(IMPORT_MAP_JSON).digest('base64')}`;
-
const PLAY_HTML = `<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
- content="default-src 'self' estella:; script-src 'self' 'unsafe-eval' '${IMPORT_MAP_HASH}' estella:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: estella:; font-src 'self' data: estella:; connect-src 'self' data: blob: estella:; worker-src 'self' blob:;"
+ content="default-src 'self' estella:; script-src 'self' 'unsafe-eval' '${IMPORT_MAP_CSP_HASH}' estella:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: estella:; font-src 'self' data: estella:; connect-src 'self' data: blob: estella:; worker-src 'self' blob:;"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>Estella Play</title>
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index f2b36d328..59b37f450 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -10,11 +10,12 @@
*
* Pure Node (esbuild + fs) — IPC wiring is in main.ts.
*/
-import { build } from 'esbuild';
+import { build, type BuildOptions } from 'esbuild';
import { writeFile, mkdir, cp } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { cookAssets } from './cookAssets';
+import { IMPORT_MAP_JSON, IMPORT_MAP_CSP_HASH } from './buildPlayRealm';
export interface ExportGameResult {
ok: boolean;
@@ -32,10 +33,11 @@ function indexHtml(title: string): string {
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
- content="default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self' data: blob:; worker-src 'self' blob:;"
+ content="default-src 'self'; script-src 'self' 'unsafe-eval' '${IMPORT_MAP_CSP_HASH}'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self' data: blob:; worker-src 'self' blob:;"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>${title}</title>
+ <script type="importmap">${IMPORT_MAP_JSON}</script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { width: 100%; height: 100%; overflow: hidden; background: #0e121b; }
@@ -59,10 +61,13 @@ export async function exportGame(opts: {
root: string;
entryScene: string;
gameHostEntry: string;
+ /** Project-relative startup entry (e.g. src/main.ts) → bundled to scripts.mjs. */
+ scriptsEntry?: string;
+ sdkDistDir: string;
wasmDir: string;
outDir: string;
title?: string;
- /** Shipping config: minify the host bundle, no sourcemap. Default off (dev). */
+ /** Shipping config: minify the bundles, no sourcemap. Default off (dev). */
minify?: boolean;
sourcemap?: boolean;
}): Promise<ExportGameResult> {
@@ -70,41 +75,47 @@ export async function exportGame(opts: {
const warnings: string[] = [];
const errors: string[] = [];
await mkdir(absOut, { recursive: true });
+ const common: BuildOptions = {
+ bundle: true,
+ format: 'esm',
+ platform: 'browser',
+ target: 'es2020',
+ external: ['esengine', 'esengine/*'],
+ minify: opts.minify ?? false,
+ sourcemap: opts.sourcemap ?? false,
+ write: true,
+ logLevel: 'silent',
+ };
// 1. Cook reachable assets + manifest (the entry scene file is staged too).
const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: absOut });
warnings.push(...cook.warnings);
- // 2. Bundle the game host (esengine inlined → self-contained game.js).
try {
- const res = await build({
- entryPoints: [opts.gameHostEntry],
- bundle: true,
- format: 'esm',
- platform: 'browser',
- target: 'es2020',
- outfile: path.join(absOut, 'game.js'),
- minify: opts.minify ?? false,
- sourcemap: opts.sourcemap ?? false,
- write: true,
- logLevel: 'silent',
- });
- errors.push(...res.errors.map((e) => e.text));
- warnings.push(...res.warnings.map((w) => w.text));
+ // 2. Game host — esengine EXTERNAL (resolved by the index.html import map),
+ // so the shipped game shares one SDK with the project bundle and runs
+ // custom systems (same shape as the play realm).
+ const host = await build({ ...common, entryPoints: [opts.gameHostEntry], outfile: path.join(absOut, 'game.js') });
+ errors.push(...host.errors.map((e) => e.text));
+ // 3. Project bundle (defineComponent/defineSystem) → scripts.mjs, esengine external.
+ const scriptsAbs = opts.scriptsEntry ? path.join(opts.root, opts.scriptsEntry) : null;
+ if (scriptsAbs && existsSync(scriptsAbs)) {
+ const proj = await build({ ...common, entryPoints: [scriptsAbs], outfile: path.join(absOut, 'scripts.mjs') });
+ errors.push(...proj.errors.map((e) => e.text));
+ }
} catch (err) {
const e = err as { errors?: { text: string }[]; message?: string };
errors.push(...(e.errors?.map((x) => x.text) ?? [String(e.message ?? err)]));
return { ok: false, outDir: absOut, included: cook.included.length, warnings, errors };
}
- // 3. Copy the wasm runtime (glue + binary + side modules).
- if (existsSync(opts.wasmDir)) {
- await cp(opts.wasmDir, path.join(absOut, 'wasm'), { recursive: true });
- } else {
- warnings.push(`wasm runtime dir not found: ${opts.wasmDir}`);
- }
+ // 4. SDK (import-map target) + wasm runtime.
+ if (existsSync(opts.sdkDistDir)) await cp(opts.sdkDistDir, path.join(absOut, 'sdk'), { recursive: true });
+ else warnings.push(`sdk dist not found: ${opts.sdkDistDir}`);
+ if (existsSync(opts.wasmDir)) await cp(opts.wasmDir, path.join(absOut, 'wasm'), { recursive: true });
+ else warnings.push(`wasm runtime dir not found: ${opts.wasmDir}`);
- // 4. Host page + entry-scene config.
+ // 5. Host page + entry-scene config.
await writeFile(path.join(absOut, 'index.html'), indexHtml(opts.title ?? 'Game'));
await writeFile(
path.join(absOut, 'game.config.json'),
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 1a6454bc3..688b6af4f 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -275,12 +275,13 @@ ipcMain.handle(
const entryScene = manifest.defaultScene;
if (!entryScene) throw new Error('project has no defaultScene to export');
const publicWasm = path.join(VITE_PUBLIC, 'wasm');
- const wasmDir = existsSync(publicWasm) ? publicWasm : path.join(RENDERER_DIST, 'wasm');
return exportGame({
root,
entryScene,
gameHostEntry: path.join(process.env.APP_ROOT!, 'src', 'gameHost.ts'),
- wasmDir,
+ scriptsEntry: resolveScripts(manifest).main,
+ sdkDistDir: path.join(process.env.APP_ROOT!, 'node_modules', 'esengine', 'dist'),
+ wasmDir: existsSync(publicWasm) ? publicWasm : path.join(RENDERER_DIST, 'wasm'),
outDir: opts?.outDir || 'dist-game',
title: manifest.name,
minify: opts?.minify,
diff --git a/desktop/src/gameHost.ts b/desktop/src/gameHost.ts
index c100893f5..c7c2ef659 100644
--- a/desktop/src/gameHost.ts
+++ b/desktop/src/gameHost.ts
@@ -29,19 +29,27 @@ async function boot(): Promise<void> {
window.addEventListener('resize', resize);
resize();
+ // Register the project's own components/systems first (side-effect import; its
+ // `import 'esengine'` resolves through the page import map to the shared SDK).
+ try {
+ await import(/* @vite-ignore */ new URL('./scripts.mjs', import.meta.url).href);
+ } catch {
+ /* no project bundle — builtin-only */
+ }
+
const cfg = (await (await fetch('./game.config.json')).json()) as GameConfig;
const manifest = (await (await fetch('./assets.manifest.json')).json()) as CookedManifest;
const sceneData = (await (await fetch(`./${cfg.entryScene}`)).json()) as SceneData;
const assetManifest: Record<string, string> = {};
for (const e of manifest.entries) assetManifest[e.uuid.toLowerCase()] = `./${e.path}`;
- const wasmBase = `${location.origin}/wasm`;
- const { default: createModule } = (await import(/* @vite-ignore */ `${wasmBase}/esengine.js`)) as {
+ const wasmBase = new URL('./wasm/', import.meta.url).href; // relative → mount-path agnostic
+ const { default: createModule } = (await import(/* @vite-ignore */ `${wasmBase}esengine.js`)) as {
default: (options?: Record<string, unknown>) => Promise<ESEngineModule>;
};
const module = await createModule({
canvas,
- locateFile: (p: string) => `${wasmBase}/${p}`,
+ locateFile: (p: string) => `${wasmBase}${p}`,
print: (t: string) => console.log(t),
printErr: (t: string) => console.error(t),
});
@@ -59,7 +67,7 @@ async function boot(): Promise<void> {
const app = createWebApp(module, {
glContextHandle: glHandle,
getViewportSize: () => ({ width: canvas.width, height: canvas.height }),
- wasmBaseUrl: wasmBase,
+ wasmBaseUrl: wasmBase.replace(/\/$/, ''), // SDK appends "/<file>" — no trailing slash
});
setEditorMode(false);
setPlayMode(true);
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index b83b12f52..dcef1a5ef 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -73,7 +73,7 @@ async function boot(msg: InitMessage): Promise<void> {
app = createWebApp(module, {
glContextHandle: glHandle,
getViewportSize: () => ({ width: canvas.width, height: canvas.height }),
- wasmBaseUrl: wasmBase,
+ wasmBaseUrl: wasmBase.replace(/\/$/, ''), // SDK appends "/<file>" — no trailing slash
});
setEditorMode(false);
setPlayMode(true);
diff --git a/desktop/tests/export-game.test.ts b/desktop/tests/export-game.test.ts
index 1ca4cc5b6..da8ccd19d 100644
--- a/desktop/tests/export-game.test.ts
+++ b/desktop/tests/export-game.test.ts
@@ -34,7 +34,12 @@ beforeAll(async () => {
JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }),
);
writeFileSync(path.join(root, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
- // A stand-in wasm runtime dir to copy.
+ // A project startup entry (esengine external) → bundled to scripts.mjs.
+ mkdirSync(path.join(root, 'src'), { recursive: true });
+ writeFileSync(path.join(root, 'src', 'main.ts'), `import { defineComponent } from 'esengine';\ndefineComponent('SpawnMarker', { rate: 1 });\n`);
+ // Stand-in SDK dist + wasm runtime dirs to copy.
+ mkdirSync(path.join(root, '_sdk'), { recursive: true });
+ writeFileSync(path.join(root, '_sdk', 'index.js'), 'export const x = 1;');
mkdirSync(path.join(root, '_wasm'), { recursive: true });
writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');
writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'wasmbytes');
@@ -45,11 +50,13 @@ beforeAll(async () => {
afterAll(() => rmSync(root, { recursive: true, force: true }));
describe('exportGame', () => {
- it('produces a self-contained web build (cook + host + wasm + html)', async () => {
+ it('produces an import-map web build (cook + host + sdk + scripts + wasm + html)', async () => {
const res = await exportGame({
root,
entryScene: 'scenes/main.esscene',
gameHostEntry: GAME_HOST,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wasm'),
outDir: out,
title: 'My Game',
@@ -63,21 +70,25 @@ describe('exportGame', () => {
const has = (p: string) => existsSync(path.join(out, p));
expect(has('index.html')).toBe(true);
expect(has('game.js')).toBe(true);
+ expect(has('scripts.mjs')).toBe(true);
+ expect(has('sdk/index.js')).toBe(true);
expect(has('game.config.json')).toBe(true);
expect(has('assets.manifest.json')).toBe(true);
expect(has('scenes/main.esscene')).toBe(true);
expect(has('assets/hero.png')).toBe(true);
expect(has('wasm/esengine.js')).toBe(true);
- expect(has('wasm/esengine.wasm')).toBe(true);
- // The host is real + esengine-INLINED (self-contained): an external build is
- // ~1-2 KB with a bare `import "esengine"`; the inlined SDK is hundreds of KB.
+ // The host + project bundle are esengine-EXTERNAL (small; resolved by the
+ // import map) — NOT an inlined hundreds-of-KB SDK.
const gameJs = readFileSync(path.join(out, 'game.js'), 'utf8');
- expect(gameJs.length).toBeGreaterThan(100_000);
- expect(gameJs).not.toMatch(/^\s*import\s*[^;]*from\s*["']esengine["']/m);
+ expect(gameJs.length).toBeLessThan(100_000);
+ expect(readFileSync(path.join(out, 'scripts.mjs'), 'utf8')).toMatch(/from\s*["']esengine["']/);
- // index.html loads the host; config points at the entry scene.
- expect(readFileSync(path.join(out, 'index.html'), 'utf8')).toContain('./game.js');
+ // index.html carries the import map + loads the host; config points at the scene.
+ const html = readFileSync(path.join(out, 'index.html'), 'utf8');
+ expect(html).toContain('importmap');
+ expect(html).toContain('./sdk/index.js');
+ expect(html).toContain('./game.js');
expect(JSON.parse(readFileSync(path.join(out, 'game.config.json'), 'utf8')).entryScene).toBe('scenes/main.esscene');
}, 60_000);
});