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.

refactor(sdk): one declaration of what an export writes and a runtime reads

esengine05f7699cc692
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index a0ec9a450..c0db77b84 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -27,6 +27,7 @@ import path from 'node:path';
import { cookAssets, loadAssetGroups } from './cookAssets';
import { buildAddressableManifest } from './addressableManifest';
import { activeRemoteRoot } from '../../sdk/src/asset/assetGroups';
+import type { PackagedGameConfig } from 'esengine';
import { IMPORT_MAP_JSON, IMPORT_MAP_CSP_HASH } from './buildPlayRealm';
import { exportWeChat } from './exportWeChat';
import { exportPlayable } from './exportPlayable';
@@ -481,21 +482,18 @@ export async function exportGame(opts: {
if (!nativeContent) {
await writeFile(path.join(payloadDir, 'index.html'), indexHtml(title, platform === 'web' ? orientation : undefined));
}
- await writeFile(
- path.join(payloadDir, 'game.config.json'),
- JSON.stringify(
- {
- entryScene: opts.entryScene, scenes,
- ...(opts.ySortLayers ? { ySortLayers: opts.ySortLayers } : {}),
- ...(opts.colorSpace === 'linear' ? { colorSpace: opts.colorSpace } : {}),
- ...(opts.screenFit && opts.screenFit.scaleMode >= 0 ? { screenFit: opts.screenFit } : {}),
- ...(opts.uiTheme === 'light' ? { uiTheme: opts.uiTheme } : {}),
- ...(opts.uiThemeColors && Object.keys(opts.uiThemeColors).length > 0 ? { uiThemeColors: opts.uiThemeColors } : {}),
- ...(hotUpdate ? { hotUpdate } : {}),
- },
- null, 2,
- ) + '\n',
- );
+ // Typed against the SDK's contract, so a field the runtimes read can never be
+ // spelled differently here — the two sides share one declaration.
+ const gameConfig: PackagedGameConfig = {
+ entryScene: opts.entryScene, scenes,
+ ...(opts.ySortLayers ? { ySortLayers: opts.ySortLayers } : {}),
+ ...(opts.colorSpace === 'linear' ? { colorSpace: opts.colorSpace } : {}),
+ ...(opts.screenFit && opts.screenFit.scaleMode >= 0 ? { screenFit: opts.screenFit } : {}),
+ ...(opts.uiTheme === 'light' ? { uiTheme: opts.uiTheme } : {}),
+ ...(opts.uiThemeColors && Object.keys(opts.uiThemeColors).length > 0 ? { uiThemeColors: opts.uiThemeColors } : {}),
+ ...(hotUpdate ? { hotUpdate } : {}),
+ };
+ await writeFile(path.join(payloadDir, 'game.config.json'), JSON.stringify(gameConfig, null, 2) + '\n');
// 6. Desktop: wrap the payload in a runnable Electron app.
if (platform === 'desktop') { progress({ phase: 'Staging Electron app' }); await stageDesktopApp(absOut, title, orientation, opts.desktopAppId, opts.desktopProductName); }
diff --git a/desktop/src/gameHost.ts b/desktop/src/gameHost.ts
index 8e85d009b..ac03d5e59 100644
--- a/desktop/src/gameHost.ts
+++ b/desktop/src/gameHost.ts
@@ -12,27 +12,8 @@
* (shared with the play realm's import-map work).
*/
import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, atlasCatalogFields, parseThemeOverrides, Assets } from 'esengine';
-import type { CatalogData, CookedAtlasInfo, ESEngineModule, SceneData, AddressableManifest } from 'esengine';
+import type { CatalogData, CookedAtlasInfo, ESEngineModule, SceneData, AddressableManifest, PackagedGameConfig } from 'esengine';
-interface GameConfig {
- entryScene: string;
- /** Every switchable scene (SceneManager name + cooked path); includes the entry. */
- scenes?: Array<{ name: string; path: string }>;
- /** Bitmask of render layers (0..31) that y-sort within the layer. */
- ySortLayers?: number;
- /** Project color space — 'linear' boots the linear-light pipeline. */
- colorSpace?: 'gamma' | 'linear';
- /** Project camera fit (design resolution + scale mode) — letterboxes the main camera
- * without a UI Canvas; absent = no fit. */
- screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
- /** Project widget theme; absent = dark. */
- uiTheme?: 'light';
- /** Project theme color overrides (role → #rrggbbaa hex). */
- uiThemeColors?: Record<string, string>;
- /** Hot-update delivery: the CDN root `remote`-group assets resolve against +
- * the storage key an applied update persists under (both optional). */
- hotUpdate?: { remoteRoot?: string; persistUpdateKey?: string };
-}
interface CookedManifest {
entries: { uuid: string; path: string; sourcePath?: string; type: string; atlas?: CookedAtlasInfo }[];
}
@@ -60,7 +41,7 @@ async function boot(): Promise<void> {
/* no project bundle — builtin-only */
}
- const cfg = (await (await fetch('./game.config.json')).json()) as GameConfig;
+ const cfg = (await (await fetch('./game.config.json')).json()) as PackagedGameConfig;
const manifest = (await (await fetch('./assets.manifest.json')).json()) as CookedManifest;
// Addressable manifest (v2.0): powers Assets.loadGroup + hot-update. Optional —
// a legacy build without it degrades to eager-only (the flat manifest above).
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 6c69d4f92..44b7f7de3 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1323 stable · 17 beta · 0 deprecated
+Symbols: 1329 stable · 17 beta · 0 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -4089,6 +4089,27 @@ width: number | undefined
Record<string, PtrLayout>
```
+## PackagedAssetIndex — interface
+```
+assetPaths: () => string[]
+catalog: Catalog | undefined
+manifest: AddressableManifest
+model: ManifestModel
+resolvePath: (ref: string) => string
+```
+
+## PackagedGameConfig — interface
+```
+colorSpace: "gamma" | "linear" | undefined
+entryScene: string
+hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
+scenes: { name: string; path: string; }[] | undefined
+screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+uiTheme: "light" | undefined
+uiThemeColors: Record<string, string> | undefined
+ySortLayers: number | undefined
+```
+
## Parent — const
```
BuiltinComponentDef<ParentData>
@@ -8144,6 +8165,11 @@ BtPlugin
(mode: TerrainMode, mask: number): number
```
+## catalogFromManifest — function
+```
+(manifest: AddressableManifest): Catalog | undefined
+```
+
## clearAllCaches — function
```
(): void
@@ -8349,6 +8375,11 @@ Plugin
(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]
```
+## createPackagedAssetSource — function
+```
+(index: PackagedAssetIndex): RuntimeAssetSource
+```
+
## createProgress — function
```
(opts: ProgressOptions): ProgressHandle
@@ -8859,6 +8890,11 @@ FsmPlugin
(flip: boolean): ImageBitmapOptions
```
+## indexPackagedManifest — function
+```
+(manifest: AddressableManifest): PackagedAssetIndex
+```
+
## info — function
```
(category: string, message: string, data?: unknown): void
@@ -9044,6 +9080,11 @@ LifecyclePlugin
(asset: InputMapAsset): InputMap
```
+## loadPackagedAssetIndex — function
+```
+(manifestPath?: string): Promise<PackagedAssetIndex>
+```
+
## loadPhysicsModule — function
```
(wasmUrl: string, factory?: PhysicsModuleFactory): Promise<PhysicsWasmModule>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index e34933c24..e1b128d11 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1339 stable · 22 beta · 0 deprecated
+Symbols: 1343 stable · 22 beta · 0 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -3961,19 +3961,7 @@ text: string | undefined
## NativeGame — interface
```
app: App
-config: NativeGameConfig
-```
-
-## NativeGameConfig — interface
-```
-colorSpace: "gamma" | "linear" | undefined
-entryScene: string
-hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
-scenes: { name: string; path: string; }[] | undefined
-screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
-uiTheme: "light" | undefined
-uiThemeColors: Record<string, string> | undefined
-ySortLayers: number | undefined
+config: PackagedGameConfig
```
## NativeGameOptions — interface
@@ -3985,6 +3973,19 @@ scope: Record<string, unknown> | undefined
width: number
```
+## NativeHostBindings — interface
+```
+es_devicePixelRatio: (() => number) | undefined
+es_getStorageItem: ((key: string) => string | null) | undefined
+es_loadImagePixels: (path: string) => { width: number; height: number; pixels: ArrayBuffer; } | null
+es_readAsset: (path: string) => ArrayBuffer | null
+es_readCacheFile: ((key: string) => ArrayBuffer | null) | undefined
+es_removeStorageItem: ((key: string) => void) | undefined
+es_setStorageItem: ((key: string, value: string) => void) | undefined
+es_storageKeys: (() => string[]) | undefined
+es_writeCacheFile: ((key: string, bytes: ArrayBuffer | Uint8Array | string) => boolean) | undefined
+```
+
## NativeInputListener — interface @beta
```
onKeyDown: ((code: string) => void) | undefined
@@ -4216,6 +4217,18 @@ model: ManifestModel
resolvePath: (ref: string) => string
```
+## PackagedGameConfig — interface
+```
+colorSpace: "gamma" | "linear" | undefined
+entryScene: string
+hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
+scenes: { name: string; path: string; }[] | undefined
+screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+uiTheme: "light" | undefined
+uiThemeColors: Record<string, string> | undefined
+ySortLayers: number | undefined
+```
+
## Parent — const
```
BuiltinComponentDef<ParentData>
@@ -8156,6 +8169,11 @@ AnimationPlugin
<T>(items: readonly T[]): ArrayDataSource<T>
```
+## assertHostEnvironment — function
+```
+(scope?: Record<string, unknown>): void
+```
+
## assetPlugin — const
```
AssetPlugin
@@ -8471,6 +8489,11 @@ Plugin
(module: ESEngineModule, options?: HeadlessAppOptions): App
```
+## createHostBridge — function
+```
+(scope?: Record<string, unknown>): NativeBridge
+```
+
## createListView — function
```
<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>
@@ -8501,6 +8524,11 @@ Plugin
(scope?: Record<string, unknown>): World
```
+## createPackagedAssetSource — function
+```
+(index: PackagedAssetIndex): RuntimeAssetSource
+```
+
## createProgress — function
```
(opts: ProgressOptions): ProgressHandle
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 3342ef378..94b20e615 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1322 stable · 19 beta · 0 deprecated
+Symbols: 1328 stable · 19 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -4084,6 +4084,27 @@ width: number | undefined
Record<string, PtrLayout>
```
+## PackagedAssetIndex — interface
+```
+assetPaths: () => string[]
+catalog: Catalog | undefined
+manifest: AddressableManifest
+model: ManifestModel
+resolvePath: (ref: string) => string
+```
+
+## PackagedGameConfig — interface
+```
+colorSpace: "gamma" | "linear" | undefined
+entryScene: string
+hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
+scenes: { name: string; path: string; }[] | undefined
+screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+uiTheme: "light" | undefined
+uiThemeColors: Record<string, string> | undefined
+ySortLayers: number | undefined
+```
+
## Parent — const
```
BuiltinComponentDef<ParentData>
@@ -8139,6 +8160,11 @@ BtPlugin
(mode: TerrainMode, mask: number): number
```
+## catalogFromManifest — function
+```
+(manifest: AddressableManifest): Catalog | undefined
+```
+
## clearAllCaches — function
```
(): void
@@ -8344,6 +8370,11 @@ Plugin
(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]
```
+## createPackagedAssetSource — function
+```
+(index: PackagedAssetIndex): RuntimeAssetSource
+```
+
## createProgress — function
```
(opts: ProgressOptions): ProgressHandle
@@ -8854,6 +8885,11 @@ FsmPlugin
(flip: boolean): ImageBitmapOptions
```
+## indexPackagedManifest — function
+```
+(manifest: AddressableManifest): PackagedAssetIndex
+```
+
## info — function
```
(category: string, message: string, data?: unknown): void
@@ -9044,6 +9080,11 @@ LifecyclePlugin
(asset: InputMapAsset): InputMap
```
+## loadPackagedAssetIndex — function
+```
+(manifestPath?: string): Promise<PackagedAssetIndex>
+```
+
## loadPhysicsModule — function
```
(wasmUrl: string, factory?: PhysicsModuleFactory): Promise<PhysicsWasmModule>
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index fd4f6d602..5210c106b 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1333 stable · 17 beta · 0 deprecated
+Symbols: 1339 stable · 17 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -4091,6 +4091,27 @@ width: number | undefined
Record<string, PtrLayout>
```
+## PackagedAssetIndex — interface
+```
+assetPaths: () => string[]
+catalog: Catalog | undefined
+manifest: AddressableManifest
+model: ManifestModel
+resolvePath: (ref: string) => string
+```
+
+## PackagedGameConfig — interface
+```
+colorSpace: "gamma" | "linear" | undefined
+entryScene: string
+hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
+scenes: { name: string; path: string; }[] | undefined
+screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+uiTheme: "light" | undefined
+uiThemeColors: Record<string, string> | undefined
+ySortLayers: number | undefined
+```
+
## Parent — const
```
BuiltinComponentDef<ParentData>
@@ -8163,6 +8184,11 @@ BtPlugin
(mode: TerrainMode, mask: number): number
```
+## catalogFromManifest — function
+```
+(manifest: AddressableManifest): Catalog | undefined
+```
+
## clearAllCaches — function
```
(): void
@@ -8368,6 +8394,11 @@ Plugin
(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]
```
+## createPackagedAssetSource — function
+```
+(index: PackagedAssetIndex): RuntimeAssetSource
+```
+
## createProgress — function
```
(opts: ProgressOptions): ProgressHandle
@@ -8878,6 +8909,11 @@ FsmPlugin
(flip: boolean): ImageBitmapOptions
```
+## indexPackagedManifest — function
+```
+(manifest: AddressableManifest): PackagedAssetIndex
+```
+
## info — function
```
(category: string, message: string, data?: unknown): void
@@ -9068,6 +9104,11 @@ LifecyclePlugin
(asset: InputMapAsset): InputMap
```
+## loadPackagedAssetIndex — function
+```
+(manifestPath?: string): Promise<PackagedAssetIndex>
+```
+
## loadPhysicsModule — function
```
(wasmUrl: string, factory?: PhysicsModuleFactory): Promise<PhysicsWasmModule>
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 0ec8e43e9..8720cc082 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -234,6 +234,17 @@ export {
type RuntimeInitConfig,
} from './runtimeLoader';
+// The packaged-realm assembly (WeChat, native) + the game.config.json contract the
+// export pipeline writes and every runtime reads.
+export {
+ loadPackagedAssetIndex,
+ indexPackagedManifest,
+ catalogFromManifest,
+ createPackagedAssetSource,
+ type PackagedAssetIndex,
+ type PackagedGameConfig,
+} from './packagedRuntime';
+
// =============================================================================
// Preview
// =============================================================================
diff --git a/sdk/src/index.native.ts b/sdk/src/index.native.ts
index 9af30e8ff..37f2f9e89 100644
--- a/sdk/src/index.native.ts
+++ b/sdk/src/index.native.ts
@@ -34,8 +34,8 @@ markEngineComponentBaseline();
export * from './core';
export * from './webAppFactory';
-export { NativePlatformAdapter, installNativePlatform } from './platform/native';
-export type { NativeBridge, NativeInputListener, NativeFetchResult } from './platform/native';
+export { NativePlatformAdapter, installNativePlatform, createHostBridge, assertHostEnvironment } from './platform/native';
+export type { NativeBridge, NativeInputListener, NativeFetchResult, NativeHostBindings } from './platform/native';
// Fast-path memory backend for the native core. The shell builds one over its
// host-injected `es_<Component>_buffer` bindings and passes it to the bridge
@@ -67,11 +67,7 @@ export { createNativeApp } from './ecs/nativeRuntime';
// the device) rather than a hand-written game script — the native sibling of the
// WeChat runtime and the web game host.
export { initNativeGame } from './nativeGameRuntime';
-export type { NativeGame, NativeGameConfig, NativeGameOptions } from './nativeGameRuntime';
-
-// The packaged-realm asset assembly the native and WeChat runtimes share.
-export { loadPackagedAssetIndex, indexPackagedManifest, catalogFromManifest } from './packagedRuntime';
-export type { PackagedAssetIndex } from './packagedRuntime';
+export type { NativeGame, NativeGameOptions } from './nativeGameRuntime';
// ABI layout hash of the component schema this bundle was generated from — the
// native shell compares it against the wasm build it loads (same as the editor).
diff --git a/sdk/src/nativeGameRuntime.ts b/sdk/src/nativeGameRuntime.ts
index f5e912b73..e5277359b 100644
--- a/sdk/src/nativeGameRuntime.ts
+++ b/sdk/src/nativeGameRuntime.ts
@@ -19,28 +19,13 @@ import type { App } from './app';
import { initRuntime } from './runtimeLoader';
import { createNativeApp } from './ecs/nativeRuntime';
import type { NativeBridge } from './platform/native';
-import { FileSystemBackend } from './asset/Backend';
-import { platformReadTextFile, platformLoadImagePixels } from './platform';
-import { loadPackagedAssetIndex } from './packagedRuntime';
-import type { RuntimeAssetSource } from './runtimeAssets';
+import { platformReadTextFile } from './platform';
+import { loadPackagedAssetIndex, createPackagedAssetSource, type PackagedGameConfig } from './packagedRuntime';
import type { SceneData } from './scene';
import type { ThemeOverrides } from './ui';
import { parseThemeOverrides } from './ui';
import { log } from './logger';
-/** `game.config.json` — what the export bakes about the project. */
-export interface NativeGameConfig {
- entryScene: string;
- /** Every switchable scene (SceneManager name + cooked path); includes the entry. */
- scenes?: Array<{ name: string; path: string }>;
- ySortLayers?: number;
- colorSpace?: 'gamma' | 'linear';
- screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
- uiTheme?: 'light';
- uiThemeColors?: Record<string, string>;
- hotUpdate?: { remoteRoot?: string; persistUpdateKey?: string };
-}
-
export interface NativeGameOptions {
/** The host's capability bridge (packaged files, image decode, input). */
bridge: NativeBridge;
@@ -55,7 +40,7 @@ export interface NativeGameOptions {
export interface NativeGame {
app: App;
- config: NativeGameConfig;
+ config: PackagedGameConfig;
}
/**
@@ -68,15 +53,10 @@ export async function initNativeGame(options: NativeGameOptions): Promise<Native
const config = JSON.parse(
await platformReadTextFile(options.configPath ?? 'game.config.json'),
- ) as NativeGameConfig;
+ ) as PackagedGameConfig;
const index = await loadPackagedAssetIndex();
- const source: RuntimeAssetSource = {
- backend: new FileSystemBackend(),
- decodePixels: (path) => platformLoadImagePixels(path),
- resolveRef: (ref) => index.resolvePath(ref),
- listAssetPaths: () => index.assetPaths(),
- };
+ const source = createPackagedAssetSource(index);
const scenes = config.scenes ?? [{ name: 'main', path: config.entryScene }];
const entry = scenes.find((s) => s.path === config.entryScene) ?? scenes[0];
diff --git a/sdk/src/packagedRuntime.ts b/sdk/src/packagedRuntime.ts
index 7a1dd62cf..ae29fda3c 100644
--- a/sdk/src/packagedRuntime.ts
+++ b/sdk/src/packagedRuntime.ts
@@ -13,9 +13,37 @@
*/
import { toBuildPath } from './assetTypes';
-import { platformReadTextFile } from './platform';
+import { platformReadTextFile, platformLoadImagePixels } from './platform';
import { ManifestModel, type AddressableManifest } from './asset/AddressableManifest';
import { Catalog, atlasCatalogFields, type CatalogEntry } from './asset/Catalog';
+import { FileSystemBackend } from './asset/Backend';
+import type { RuntimeAssetSource } from './runtimeAssets';
+
+/**
+ * `game.config.json` — what an export bakes about the project, and the contract
+ * between the export pipeline that writes it and every runtime that reads it.
+ * One declaration so the two sides cannot drift.
+ */
+export interface PackagedGameConfig {
+ /** Project-relative path of the scene the game boots into. */
+ entryScene: string;
+ /** Every switchable scene (SceneManager name + cooked path); includes the entry. */
+ scenes?: Array<{ name: string; path: string }>;
+ /** Bitmask of render layers (0..31) that y-sort within the layer. */
+ ySortLayers?: number;
+ /** Project color space — 'linear' boots the linear-light pipeline. */
+ colorSpace?: 'gamma' | 'linear';
+ /** Project camera fit (design resolution + scale mode) — letterboxes the main
+ * camera without a UI Canvas; absent = no fit. */
+ screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
+ /** Project widget theme; absent = dark. */
+ uiTheme?: 'light';
+ /** Project theme color overrides (role → #rrggbbaa hex). */
+ uiThemeColors?: Record<string, string>;
+ /** Hot-update delivery: the CDN root `remote`-group assets resolve against +
+ * the storage key an applied update persists under (both optional). */
+ hotUpdate?: { remoteRoot?: string; persistUpdateKey?: string };
+}
/** The packaged realm's resolved asset index — manifest, catalog, resolution. */
export interface PackagedAssetIndex {
@@ -74,6 +102,23 @@ export function indexPackagedManifest(manifest: AddressableManifest): PackagedAs
model,
catalog: catalogFromManifest(manifest),
resolvePath: (ref) => model.resolvePath(ref, toBuildPath),
- assetPaths: () => model.allAssets().map((a) => a.path),
+ // The logical address where there is one (content-addressed packs rename
+ // the staged file), else the staged path — either keeps the extension
+ // .eslocale discovery filters on.
+ assetPaths: () => model.allAssets().map((a) => a.address ?? a.path),
+ };
+}
+
+/**
+ * The asset source a packaged realm runs on: files off the device, the platform's
+ * image decode, and manifest-driven ref resolution. Identical for every packaged
+ * realm — the platform layer is what differs, and it is already abstracted.
+ */
+export function createPackagedAssetSource(index: PackagedAssetIndex): RuntimeAssetSource {
+ return {
+ backend: new FileSystemBackend(),
+ decodePixels: (path) => platformLoadImagePixels(path),
+ resolveRef: index.resolvePath,
+ listAssetPaths: index.assetPaths,
};
}
diff --git a/sdk/src/platform/native/hostBridge.ts b/sdk/src/platform/native/hostBridge.ts
new file mode 100644
index 000000000..f6218e3b0
--- /dev/null
+++ b/sdk/src/platform/native/hostBridge.ts
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file hostBridge.ts
+ * @brief Build a {@link NativeBridge} from the primitives a native host installs
+ * on the JS global.
+ * @details The host's job is the small, unavoidable part — reading a packaged
+ * file, decoding an image, persisting a key — as `es_*` functions it
+ * binds from C++. Assembling those into the bridge the SDK consumes is
+ * the SDK's job, and belongs here rather than in a JS string inside the
+ * host: typed against the interface it must satisfy, checked by the
+ * compiler, and identical on every platform the host runs on.
+ */
+
+import { log } from '../../logger';
+import type { NativeBridge, NativeInputListener } from './bridge';
+import { assertHostEnvironment } from './hostEnvironment';
+
+/** Touch phases the host reports, matching the order it dispatches. */
+const TOUCH_START = 0;
+const TOUCH_MOVE = 1;
+const TOUCH_END = 2;
+
+/** The `es_*` primitives a native host binds. Required unless marked optional. */
+export interface NativeHostBindings {
+ /** A packaged file's bytes, or null when it is not in the package. */
+ es_readAsset(path: string): ArrayBuffer | null;
+ /** Decode a packaged image to top-first RGBA, or null on failure. */
+ es_loadImagePixels(path: string): { width: number; height: number; pixels: ArrayBuffer } | null;
+ /** A writable byte store (the host's cache dir). Optional: without it there
+ * is no offline hot-update cache and no persistence for storage. */
+ es_readCacheFile?(key: string): ArrayBuffer | null;
+ es_writeCacheFile?(key: string, bytes: ArrayBuffer | Uint8Array | string): boolean;
+ /** Native key-value store, when the host has one (NSUserDefaults /
+ * SharedPreferences). Absent hosts persist through es_writeCacheFile. */
+ es_getStorageItem?(key: string): string | null;
+ es_setStorageItem?(key: string, value: string): void;
+ es_removeStorageItem?(key: string): void;
+ es_storageKeys?(): string[];
+ /** Screen scale (1 when the host reports surface pixels directly). */
+ es_devicePixelRatio?(): number;
+}
+
+/**
+ * Assemble the bridge from a host's bindings. The returned object also installs
+ * `es_onNativeTouch` on @p scope — the entry point the host calls per touch,
+ * which fans out to whatever input sink the engine registered.
+ *
+ * @throws if a required binding is missing, naming it — a native boot should fail
+ * at the seam rather than somewhere deep in an asset load.
+ */
+export function createHostBridge(
+ scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
+): NativeBridge {
+ // Both halves of the contract, checked at the seam: the JS environment the
+ // host had to install, then its own es_* primitives.
+ assertHostEnvironment(scope);
+ const bindings = scope as unknown as NativeHostBindings;
+ for (const name of ['es_readAsset', 'es_loadImagePixels'] as const) {
+ if (typeof bindings[name] !== 'function') {
+ throw new Error(`[native] host binding ${name}() is missing — the shell must install it before booting`);
+ }
+ }
+
+ let listener: NativeInputListener | null = null;
+ scope.es_onNativeTouch = (type: number, id: number, x: number, y: number): void => {
+ if (!listener) return;
+ if (type === TOUCH_START) listener.onTouchStart(id, x, y);
+ else if (type === TOUCH_MOVE) listener.onTouchMove(id, x, y);
+ else if (type === TOUCH_END) listener.onTouchEnd(id);
+ else listener.onTouchCancel(id);
+ };
+
+ const storage = hostStorage(bindings);
+
+ return {
+ readFile: (path) => {
+ const bytes = bindings.es_readAsset(path);
+ return bytes ? Promise.resolve(bytes) : Promise.reject(new Error(`asset not found: ${path}`));
+ },
+ fileExists: (path) => Promise.resolve(bindings.es_readAsset(path) != null),
+ // Networking is the shell's to add (NSURLSession / OkHttp); until then a
+ // packaged game is offline and remote groups simply do not resolve.
+ fetch: () => Promise.resolve({ ok: false, status: 404 }),
+ loadImagePixels: (path) => {
+ const decoded = bindings.es_loadImagePixels(path);
+ return decoded
+ ? Promise.resolve({
+ width: decoded.width,
+ height: decoded.height,
+ pixels: new Uint8Array(decoded.pixels),
+ })
+ : Promise.reject(new Error(`image decode failed: ${path}`));
+ },
+ ...storage,
+ ...(bindings.es_readCacheFile && bindings.es_writeCacheFile
+ ? {
+ readCacheFile: (key: string) => Promise.resolve(bindings.es_readCacheFile!(key)),
+ writeCacheFile: (key: string, bytes: ArrayBuffer) => {
+ bindings.es_writeCacheFile!(key, bytes);
+ return Promise.resolve();
+ },
+ }
+ : {}),
+ registerInput: (sink) => {
+ listener = sink;
+ return () => { listener = null; };
+ },
+ devicePixelRatio: () => bindings.es_devicePixelRatio?.() ?? 1,
+ };
+}
+
+/** Where storage lands when the host has no native key-value store. */
+const STORAGE_FILE = 'estella-storage.json';
+
+/**
+ * Key-value storage, best available: the host's own store, else a JSON file in
+ * its writable cache dir, else memory for the session. The API is synchronous
+ * (localStorage's shape), so the file variant keeps the map in memory and writes
+ * through on every mutation — storage holds saves and settings, not bulk data.
+ */
+function hostStorage(bindings: NativeHostBindings): Pick<
+ NativeBridge, 'getStorageItem' | 'setStorageItem' | 'removeStorageItem' | 'storageKeys'
+> {
+ if (typeof bindings.es_getStorageItem === 'function') {
+ return {
+ getStorageItem: (key) => bindings.es_getStorageItem!(key),
+ setStorageItem: (key, value) => bindings.es_setStorageItem?.(key, value),
+ removeStorageItem: (key) => bindings.es_removeStorageItem?.(key),
+ storageKeys: () => bindings.es_storageKeys?.() ?? [],
+ };
+ }
+
+ const entries = new Map<string, string>();
+ const persistent = typeof bindings.es_readCacheFile === 'function'
+ && typeof bindings.es_writeCacheFile === 'function';
+ if (!persistent) {
+ log.warn('native', 'host has no storage or cache bindings — saves last only for this session');
+ } else {
+ const bytes = bindings.es_readCacheFile!(STORAGE_FILE);
+ if (bytes) {
+ try {
+ for (const [k, v] of Object.entries(JSON.parse(new TextDecoder().decode(bytes)) as Record<string, string>)) {
+ entries.set(k, v);
+ }
+ } catch {
+ log.warn('native', 'stored data was unreadable — starting empty');
+ }
+ }
+ }
+ const flush = (): void => {
+ if (!persistent) return;
+ // A string, not encoded bytes: the host writes UTF-8 itself, and a native
+ // JS engine has no TextEncoder to reach for.
+ bindings.es_writeCacheFile!(STORAGE_FILE, JSON.stringify(Object.fromEntries(entries)));
+ };
+ return {
+ getStorageItem: (key) => entries.get(key) ?? null,
+ setStorageItem: (key, value) => { entries.set(key, value); flush(); },
+ removeStorageItem: (key) => { entries.delete(key); flush(); },
+ storageKeys: () => [...entries.keys()],
+ };
+}
diff --git a/sdk/src/platform/native/hostEnvironment.ts b/sdk/src/platform/native/hostEnvironment.ts
new file mode 100644
index 000000000..4154ba0a8
--- /dev/null
+++ b/sdk/src/platform/native/hostEnvironment.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file hostEnvironment.ts
+ * @brief What a native host's JS engine must provide beyond the language.
+ * @details A native host embeds a bare JS engine (QuickJS, JavaScriptCore): it
+ * implements ECMAScript and nothing else. `console`, timers, a clock and
+ * `TextDecoder` are *host* APIs a browser happens to supply — the SDK
+ * uses all four, and on a native host something has to install them.
+ *
+ * Without a declared contract each omission is found the hard way, at
+ * the moment some code path first reaches for it: an asset load that
+ * rejects with "setTimeout is not defined", silently, because there is
+ * no console either. This is the checklist, verified at boot so a
+ * missing global is named at the seam instead.
+ */
+
+/** A host global the SDK requires, and what breaks without it. */
+interface RequiredGlobal {
+ name: string;
+ /** Nested member that must be callable (e.g. `performance.now`). */
+ member?: string;
+ used_for: string;
+}
+
+const REQUIRED: RequiredGlobal[] = [
+ { name: 'console', member: 'error', used_for: 'reporting failures — without it every error is silent' },
+ { name: 'setTimeout', used_for: 'the asset cache and any deferred work' },
+ { name: 'clearTimeout', used_for: 'cancelling deferred work' },
+ { name: 'performance', member: 'now', used_for: 'frame and profiling timings' },
+ { name: 'TextDecoder', used_for: 'reading packaged JSON (manifests, scenes, config)' },
+];
+
+/**
+ * Verify the host installed everything the SDK needs, before anything uses it.
+ *
+ * @throws naming the first missing global and what it is needed for.
+ */
+export function assertHostEnvironment(
+ scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
+): void {
+ for (const { name, member, used_for } of REQUIRED) {
+ const value = scope[name];
+ const present = member
+ ? typeof (value as Record<string, unknown> | undefined)?.[member] === 'function'
+ : typeof value === 'function';
+ if (present) continue;
+ const what = member ? `${name}.${member}()` : `${name}()`;
+ throw new Error(
+ `[native] the host has not installed ${what} — the SDK needs it for ${used_for}. `
+ + 'A native host must supply the browser globals its JS engine lacks.',
+ );
+ }
+}
diff --git a/sdk/src/platform/native/index.ts b/sdk/src/platform/native/index.ts
index b53ae4650..f32139d76 100644
--- a/sdk/src/platform/native/index.ts
+++ b/sdk/src/platform/native/index.ts
@@ -11,3 +11,6 @@
export { NativePlatformAdapter, installNativePlatform } from './adapter';
export type { NativeBridge, NativeInputListener, NativeFetchResult } from './bridge';
+export { createHostBridge } from './hostBridge';
+export { assertHostEnvironment } from './hostEnvironment';
+export type { NativeHostBindings } from './hostBridge';
diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.ts
index 59fe64896..a6184a483 100644
--- a/sdk/src/wechatRuntime.ts
+++ b/sdk/src/wechatRuntime.ts
@@ -16,7 +16,7 @@ import type { RuntimeAssetSource } from './runtimeAssets';
import { FileSystemBackend } from './asset/Backend';
import { applyBuildRuntimeConfig, type RuntimeBuildConfig } from './defaults';
import { platformReadTextFile, platformInstantiateWasm, platformLoadImagePixels } from './platform';
-import { loadPackagedAssetIndex } from './packagedRuntime';
+import { loadPackagedAssetIndex, createPackagedAssetSource } from './packagedRuntime';
import { createWeChatSideModuleHost, type WeChatSideModuleFactories } from './sideModules';
import type { Vec2 } from './types';
import type { SceneData } from './scene';
@@ -93,7 +93,8 @@ export interface WeChatRuntimeConfig {
export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<void> {
// The packaged-realm asset assembly, shared with the native runtime: read the
// addressable manifest off the device, index it, build the catalog.
- const { manifest, model: manifestModel, catalog, resolvePath } = await loadPackagedAssetIndex();
+ const index = await loadPackagedAssetIndex();
+ const { model: manifestModel, catalog } = index;
const canvas = wx.createCanvas();
const info = wx.getSystemInfoSync();
@@ -135,15 +136,7 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<vo
// Canonical asset source: WeChat filesystem backend, wx image decode, manifest
// ref resolution (bare-uuid → build path).
- const source: RuntimeAssetSource = {
- backend: new FileSystemBackend(),
- decodePixels: (path) => platformLoadImagePixels(path),
- resolveRef: resolvePath,
- // Logical addresses where present (content-addressed packs rename the
- // staged file), else the staged path — either keeps the extension the
- // .eslocale discovery filters on.
- listAssetPaths: () => manifestModel.allAssets().map((a) => a.address ?? a.path),
- };
+ const source = createPackagedAssetSource(index);
// The first scene loads eagerly (the game boots into it); every other
// registers lazily by path — SceneManager fetches scenes/<name>.json
diff --git a/sdk/tests/native-host-bridge.test.ts b/sdk/tests/native-host-bridge.test.ts
new file mode 100644
index 000000000..bd9a13537
--- /dev/null
+++ b/sdk/tests/native-host-bridge.test.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The native host contract. A host embeds a bare JS engine and installs
+ * two things: the browser globals its engine lacks, and its own `es_*`
+ * primitives. Both are checked at the seam — a native boot should name
+ * what is missing, not fail later somewhere unrelated.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { createHostBridge, assertHostEnvironment } from '../src/platform/native';
+
+/** The globals a real host installs (console, timers, clock, decoder). */
+function hostGlobals(): Record<string, unknown> {
+ return {
+ console: { log: () => {}, error: () => {}, warn: () => {} },
+ setTimeout: () => 0,
+ clearTimeout: () => {},
+ performance: { now: () => 0 },
+ TextDecoder,
+ };
+}
+
+function hostScope(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ ...hostGlobals(),
+ es_readAsset: () => new ArrayBuffer(4),
+ es_loadImagePixels: () => ({ width: 1, height: 1, pixels: new ArrayBuffer(4) }),
+ ...overrides,
+ };
+}
+
+describe('assertHostEnvironment', () => {
+ it('names the missing global and what needs it', () => {
+ const scope = hostGlobals();
+ delete scope.setTimeout;
+ expect(() => assertHostEnvironment(scope)).toThrow(/setTimeout\(\).*asset cache/s);
+ });
+
+ it('catches a global present but not callable', () => {
+ expect(() => assertHostEnvironment({ ...hostGlobals(), performance: {} }))
+ .toThrow(/performance\.now\(\)/);
+ });
+
+ it('passes on a fully-equipped host', () => {
+ expect(() => assertHostEnvironment(hostGlobals())).not.toThrow();
+ });
+});
+
+describe('createHostBridge', () => {
+ it('refuses to build without a required primitive, naming it', () => {
+ const scope = hostScope();
+ delete scope.es_loadImagePixels;
+ expect(() => createHostBridge(scope)).toThrow(/es_loadImagePixels/);
+ });
+
+ it('routes host touches to the registered input sink', () => {
+ const scope = hostScope();
+ const bridge = createHostBridge(scope);
+ const sink = { onTouchStart: vi.fn(), onTouchMove: vi.fn(), onTouchEnd: vi.fn(), onTouchCancel: vi.fn() };
+ const stop = bridge.registerInput(sink);
+
+ const dispatch = scope.es_onNativeTouch as (t: number, i: number, x: number, y: number) => void;
+ dispatch(0, 1, 10, 20);
+ dispatch(1, 1, 11, 21);
+ dispatch(2, 1, 11, 21);
+ expect(sink.onTouchStart).toHaveBeenCalledWith(1, 10, 20);
+ expect(sink.onTouchMove).toHaveBeenCalledWith(1, 11, 21);
+ expect(sink.onTouchEnd).toHaveBeenCalledWith(1);
+
+ // Unsubscribing must actually detach: a host keeps dispatching regardless.
+ stop();
+ dispatch(0, 1, 0, 0);
+ expect(sink.onTouchStart).toHaveBeenCalledTimes(1);
+ });
+
+ it('persists storage through the host cache file', () => {
+ const files = new Map<string, string>();
+ const scope = hostScope({
+ es_readCacheFile: (key: string) => {
+ const text = files.get(key);
+ return text === undefined ? null : new TextEncoder().encode(text).buffer;
+ },
+ es_writeCacheFile: (key: string, bytes: string) => { files.set(key, bytes); return true; },
+ });
+
+ createHostBridge(scope).setStorageItem('save', '{"level":3}');
+ // A fresh bridge (the next launch) reads what the previous one wrote.
+ expect(createHostBridge(scope).getStorageItem('save')).toBe('{"level":3}');
+ });
+
+ it('degrades to session storage when the host has no cache, without throwing', () => {
+ const bridge = createHostBridge(hostScope());
+ bridge.setStorageItem('k', 'v');
+ expect(bridge.getStorageItem('k')).toBe('v');
+ expect(bridge.storageKeys()).toEqual(['k']);
+ });
+
+ it('prefers a native key-value store over the file fallback', () => {
+ const native = new Map<string, string>([['seen', 'yes']]);
+ const bridge = createHostBridge(hostScope({
+ es_getStorageItem: (k: string) => native.get(k) ?? null,
+ es_setStorageItem: (k: string, v: string) => { native.set(k, v); },
+ es_removeStorageItem: (k: string) => { native.delete(k); },
+ es_storageKeys: () => [...native.keys()],
+ }));
+ expect(bridge.getStorageItem('seen')).toBe('yes');
+ bridge.setStorageItem('x', '1');
+ expect(native.get('x')).toBe('1');
+ });
+});