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.

fix(export): cook a mini-game against its own import settings, not WeChat's

yhh129b8f6a99c2
diff --git a/desktop/electron/exportMiniGame.ts b/desktop/electron/exportMiniGame.ts
index 3064a6e25..1c4cf77a8 100644
--- a/desktop/electron/exportMiniGame.ts
+++ b/desktop/electron/exportMiniGame.ts
@@ -39,7 +39,7 @@ import type { OnExportProgress } from './exportProgress';
import { esengineAlias } from './esengineResolve';
import {
sceneUsesPhysics, sceneUsesVideo, detectSpineVersion, detectSpineVersionJson,
- spineModuleId, SIDE_MODULE_FILE, WECHAT_MODULE_BUILD_TARGET,
+ spineModuleId, SIDE_MODULE_FILE,
} from './sideModuleScan';
import type { MiniGameExportProfile, MiniGameVendor } from './miniGameExportProfile';
@@ -103,6 +103,7 @@ function packIncludeSuffixes(entries: CookManifest['entries'], nativeSuffixes: R
* is a HARD error — the package would otherwise ship silently broken (same
* contract as the playable exporter's collectSideModules). */
async function scanSideModules(
+ profile: MiniGameExportProfile,
sceneDatas: unknown[],
cookEntries: CookManifest['entries'],
absOut: string,
@@ -139,7 +140,7 @@ async function scanSideModules(
for (const id of ids) {
const file = SIDE_MODULE_FILE[id];
if (file && existsSync(path.join(wasmDir, `${file}.js`))) present.push({ id, file });
- else errors.push(`scene needs "${id}" but ${file}.js is not in the mini-game wasm dir — build it with \`node build-tools/cli.js build -t ${WECHAT_MODULE_BUILD_TARGET[id] ?? id}\` and re-export.`);
+ else errors.push(`scene needs "${id}" but ${file}.js is not in the ${profile.id} wasm dir — build it with \`node build-tools/cli.js build -t ${profile.sideModuleBuildTargets[id] ?? id}\` and re-export.`);
}
return present;
}
@@ -198,10 +199,15 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
const engineGlueFile = profile.engineGlueCandidates
.find((f) => existsSync(path.join(opts.wasmDir, f)));
if (!engineGlueFile) {
+ // The optional-module targets come off the profile, so the guidance names
+ // THIS vendor's builds rather than a hardcoded WeChat pair.
+ const moduleTargets = [...new Set(Object.values(profile.sideModuleBuildTargets))];
errors.push(
`${profile.id} engine runtime not found in ${opts.wasmDir} — ` +
- `build it with \`node build-tools/cli.js build -t ${profile.wasmBuildHint}\` ` +
- '(add -t physics-wechat / -t spine-wechat if the project uses physics or Spine)',
+ `build it with \`node build-tools/cli.js build -t ${profile.wasmBuildHint}\`` +
+ (moduleTargets.length > 0
+ ? ` (optional modules build separately: ${moduleTargets.map((t) => `-t ${t}`).join(' / ')})`
+ : ''),
);
return { ok: false, platform: profile.id, outDir: absOut, included: 0, warnings, errors };
}
@@ -219,7 +225,9 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
// manifest. KTX2 textures are fine here: the scan below sees the staged
// .ktx2 files and ships the Basis transcoder side module with them.
progress({ phase: 'Cooking assets' });
- const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: absOut, contentAddressed: opts.contentAddressed, compressTextures: opts.compressTextures, compressAudio: opts.compressAudio, atlasTextures: opts.atlasTextures, transcodeVideo: true, platform: 'wechat' });
+ // `platform: profile.id` — the cook reads each texture's per-platform Import
+ // Settings under this key, so a vendor must cook against ITS OWN overrides.
+ const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: absOut, contentAddressed: opts.contentAddressed, compressTextures: opts.compressTextures, compressAudio: opts.compressAudio, atlasTextures: opts.atlasTextures, transcodeVideo: true, platform: profile.id });
warnings.push(...cook.warnings);
// 1a. Restage for the vendor's code-package suffix whitelist (WeChat has no
@@ -266,7 +274,7 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
// the generated entry requires exactly those — the export-time half of
// the runtime's self-gating. A dynamically switched scene must find its
// modules present, so the union over ALL shipped scenes counts.
- const sideModules = await scanSideModules([...sceneRawByName.values()], cookEntries, absOut, opts.wasmDir, errors);
+ const sideModules = await scanSideModules(profile, [...sceneRawByName.values()], cookEntries, absOut, opts.wasmDir, errors);
const sceneRaw = sceneRawByName.get(sceneName) ?? null;
if (!sceneRaw) errors.push(`entry scene "${opts.entryScene}" was not staged by the cook`);
diff --git a/desktop/electron/miniGameExportProfile.ts b/desktop/electron/miniGameExportProfile.ts
index 0219d9600..1bb18cdea 100644
--- a/desktop/electron/miniGameExportProfile.ts
+++ b/desktop/electron/miniGameExportProfile.ts
@@ -11,8 +11,16 @@
*
* Adding a vendor = one profile object, not a fork of the pipeline.
*/
+import { WECHAT_MODULE_BUILD_TARGET } from './sideModuleScan';
-export type MiniGameVendor = 'wechat' | 'douyin';
+/**
+ * A mini-game vendor's id. Open on purpose: the value is identity — the cook's
+ * per-platform Import Settings key, the export result's `platform`, diagnostics
+ * — and nothing in the pipeline branches on it, so a vendor the editor does not
+ * ship can still be exported by handing {@link exportMiniGame} a profile.
+ * Mirrors the SDK's `MiniGameVendor` (sdk/src/platform/minigame/api.ts).
+ */
+export type MiniGameVendor = 'wechat' | 'douyin' | (string & {});
/** Vendor-neutral facts the pipeline computes, handed to the config emitter. */
export interface MiniGameConfigContext {
@@ -46,6 +54,10 @@ export interface MiniGameExportProfile {
readonly esTarget: 'es2017' | 'es2019' | 'es2020';
/** Build-target name woven into "runtime not found" errors (`build -t <hint>`). */
readonly wasmBuildHint: string;
+ /** side-module id → the `build -t <target>` that produces it for THIS vendor.
+ * The optional modules (physics/basis/videodec/spine) are built per vendor
+ * runtime, so the "module missing" guidance cannot be a shared constant. */
+ readonly sideModuleBuildTargets: Readonly<Record<string, string>>;
/** Extensions the packer handles natively (no packOptions.include needed). */
readonly nativeSuffixes: ReadonlySet<string>;
/** Custom extensions the packer denies unless restaged to `<ext>.bin`. */
@@ -75,6 +87,7 @@ export const wechatExportProfile: MiniGameExportProfile = {
// accepts it; es2017 down-levels those while keeping async/await.
esTarget: 'es2017',
wasmBuildHint: 'wechat',
+ sideModuleBuildTargets: WECHAT_MODULE_BUILD_TARGET,
// Script + config WeChat's packer compiles itself; every OTHER staged custom
// extension needs a packOptions.include rule (fs reads are otherwise denied).
nativeSuffixes: new Set(['.js', '.json']),
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index d521a7f73..27d0ee1e4 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -127,6 +127,7 @@ export default defineConfig({
{ label: 'Building & Exporting', translations: { 'zh-CN': '构建与导出' }, slug: 'guides/build-export' },
{ label: 'Hot Update', translations: { 'zh-CN': '热更新' }, slug: 'guides/hot-update' },
{ label: 'WeChat MiniGame', translations: { 'zh-CN': '微信小游戏' }, slug: 'guides/wechat' },
+ { label: 'Mini-Game Platforms', translations: { 'zh-CN': '小游戏平台' }, slug: 'guides/minigame-platforms' },
{ label: 'Networking', translations: { 'zh-CN': '联网' }, slug: 'guides/networking' },
{ label: 'AI Agents (MCP)', translations: { 'zh-CN': 'AI 代理 (MCP)' }, slug: 'guides/mcp' },
],
diff --git a/docs/astro/src/content/docs/guides/minigame-platforms.mdx b/docs/astro/src/content/docs/guides/minigame-platforms.mdx
new file mode 100644
index 000000000..49523e9bd
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/minigame-platforms.mdx
@@ -0,0 +1,170 @@
+---
+title: Mini-Game Platforms
+description: How the mini-game platform family works, and how to bring up a vendor Estella does not ship.
+---
+
+import { Steps, Aside } from '@astrojs/starlight/components';
+
+WeChat MiniGame is not a special case in Estella — it is one **profile** of a
+platform *family*. Mini-game hosts (WeChat's `wx`, Douyin's `tt`, and the rest)
+expose a near-identical API: no DOM, a packaged filesystem, subpackages, touch
+input, key-value storage. Estella implements that model **once** and describes
+each vendor as data.
+
+This guide is for bringing up a vendor Estella does not ship. If you are
+shipping to WeChat, you want [WeChat MiniGame](/guides/wechat) instead.
+
+<Aside type="caution">
+ **Pre-1.0.** The profile contract is `@beta`: it may gain fields as vendors
+ beyond WeChat are brought up against real devices.
+</Aside>
+
+## What a vendor costs
+
+A profile is **three facts and, at most, one method**:
+
+```ts
+import { installMiniGamePlatform } from 'esengine/minigame';
+
+declare const myHost: any; // the host global, e.g. `tt`
+
+installMiniGamePlatform({
+ id: 'myvendor',
+ hostLabel: 'MyVendor',
+ get global() { return myHost; },
+});
+```
+
+That is a complete platform. Filesystem, `fetch`, canvas, image decode, touch and
+key input, storage, subpackages, memory-pressure signals, device pixel ratio and
+language all come from the normalized host global. So do **audio**
+(`createInnerAudioContext`) and **sockets** (`connectSocket`). Video uses the
+engine's own wasm MPEG-1 decoder, which is portable to every host.
+
+Read `global` through a getter, as above: the host global is ambient at runtime,
+and a getter means importing your profile in a bundler or a test never touches an
+undefined binding.
+
+### The one genuine divergence
+
+WASM instantiation. WeChat routes it through `WXWebAssembly.instantiate(path)`
+rather than the standard `WebAssembly`, so its profile overrides one method:
+
+```ts
+{
+ id: 'wechat',
+ hostLabel: 'WeChat',
+ get global() { return wx as unknown as MiniGameGlobal; },
+ instantiateWasm(pathOrBuffer, imports) { /* WXWebAssembly */ },
+}
+```
+
+If your host uses standard `WebAssembly`, omit it — the family reads the binary
+through the packaged filesystem and instantiates it.
+
+`createAudioBackend`, `createVideoBackend` and `createSocket` are optional the
+same way. Override one only where the host genuinely differs; the defaults are
+`MiniGameAudioBackend`, the wasm video decoder, and `MiniGameSocket`, all
+exported from `esengine/minigame` so you can wrap rather than rewrite.
+
+## What the host must provide
+
+Your `global` has to satisfy `MiniGameGlobal`. Required:
+
+| Member | Used for |
+| --- | --- |
+| `createCanvas()` | display surface (first call) + offscreen 2D |
+| `createImage()` | image decode |
+| `getFileSystemManager()` | `readFileSync` / `readFile` / `access` / `accessSync` / `writeFile` |
+| `request(opts)` | the `fetch` polyfill |
+| `createInnerAudioContext()` | audio playback |
+| `connectSocket(opts)` | `GameSocket` / replication |
+| `getSystemInfoSync()` | viewport size, pixel ratio, language |
+| `onTouchStart/Move/End` + `off*` | pointer input |
+| `getStorageSync` / `setStorageSync` / `removeStorageSync` / `getStorageInfoSync` | save data, hot-update bookkeeping |
+
+Optional — the adapter probes for these and degrades gracefully when a host
+lacks one: `onTouchCancel`/`offTouchCancel`, `onKeyDown`/`onKeyUp` (+ `off*`),
+`loadSubpackage`, `onMemoryWarning`/`offMemoryWarning`, `onShow`/`onHide`.
+
+<Aside type="note">
+ `isMiniGame()` reads the adapter's declared **family**, not a list of vendor
+ names — so your platform gets every mini-game code path (packaged reads,
+ subpackage groups, no-DOM branches) the moment it is installed. `isWeChat()`
+ stays false, as it should: it is a vendor check, not a capability check.
+</Aside>
+
+## Booting the game
+
+The shipped package's entry calls the family runtime:
+
+```js
+// game.js — the host runs this
+const engineFactory = require('./wasm/esengine.js');
+const bundle = require('./game-bundle.js');
+bundle.boot(engineFactory, { /* side module factories */ });
+```
+
+```ts
+// bundled with your game
+import { installMiniGamePlatform, initMiniGameRuntime } from 'esengine/minigame';
+import { myProfile } from './myProfile';
+
+export function boot(engineFactory, sideModuleFactories) {
+ installMiniGamePlatform(myProfile);
+ return initMiniGameRuntime({
+ engineFactory,
+ engineWasmPath: 'wasm/esengine.wasm',
+ sceneNames: ['Main'],
+ firstScene: 'Main',
+ sideModuleFactories,
+ });
+}
+```
+
+`initMiniGameRuntime` takes the display canvas from the adapter, registers its
+GL context with the engine module, loads the addressable manifest, and runs the
+app — the same sequence WeChat boots through. `initWeChatRuntime` is this
+function with WeChat's staged wasm name filled in, and nothing else.
+
+<Aside type="note">
+ Install the platform **before** `initMiniGameRuntime`; it throws with the fix
+ in the message if you don't. The first `createCanvas()` of the process is the
+ display surface on every mini-game host, so nothing may create a canvas before
+ the runtime does.
+</Aside>
+
+## Packaging
+
+The export pipeline (`exportMiniGame`) is shared the same way: cook → manifest →
+scene transform → side-module scan → bundle → config/entry → runtime copy. A
+vendor is a `MiniGameExportProfile` describing what varies:
+
+| Field | What it says |
+| --- | --- |
+| `id` | vendor identity — also the **Import Settings key** the cook reads per texture |
+| `sdkEntryFile` | SDK dist entry `esengine` is aliased to |
+| `runtimeInit` | the boot function the generated entry imports |
+| `engineGlueCandidates` | engine glue filenames to look for, in preference order |
+| `esTarget` | syntax floor for the bundle and the down-leveled glue |
+| `wasmBuildHint` / `sideModuleBuildTargets` | the `build -t …` names in error guidance |
+| `nativeSuffixes` / `binRestageExts` | the packer's suffix policy |
+| `subpackageDir` | where lazy groups stage |
+| `emitConfigFiles` / `emitEntry` | the vendor's config files and `game.js` |
+
+<Aside type="caution">
+ **The export side lives in the editor, not in the SDK.** Adding a vendor to
+ *Package Project* means editing the engine: a profile in
+ `desktop/electron/miniGameExportProfile.ts`, a case in `exportGame.ts`, a card
+ in the Build dialog, and a wasm target in `build-tools/build.config.js` if the
+ host needs its own engine build. The runtime side above needs none of that —
+ you can ship to an unsupported host today by driving `initMiniGameRuntime`
+ from your own packaging script.
+</Aside>
+
+## Does the host need its own engine build?
+
+Only if it cannot load the web engine's wasm. WeChat needs one (`-t wechat`,
+`ES_BUILD_WXGAME`) because of `WXWebAssembly` and because it has no WebGPU. A
+host with standard `WebAssembly` and WebGL2 can ship the web build's glue —
+`engineGlueCandidates` already falls back to `esengine.js` for exactly this case.
diff --git a/docs/astro/src/content/docs/zh-cn/guides/minigame-platforms.mdx b/docs/astro/src/content/docs/zh-cn/guides/minigame-platforms.mdx
new file mode 100644
index 000000000..77bbe9c44
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/guides/minigame-platforms.mdx
@@ -0,0 +1,160 @@
+---
+title: 小游戏平台
+description: 小游戏平台家族的工作方式,以及如何接入一个 Estella 未内置的平台。
+---
+
+import { Steps, Aside } from '@astrojs/starlight/components';
+
+微信小游戏在 Estella 里不是特例,它只是平台**家族**的一个 **profile**。各家小游戏宿主
+(微信的 `wx`、抖音的 `tt` 等)暴露的 API 高度相似:没有 DOM、打包式文件系统、分包、
+触摸输入、键值存储。Estella 把这套模型**只实现一次**,每个平台厂商用数据来描述。
+
+本指南面向「接入 Estella 未内置的平台」。如果你的目标是微信,请看
+[微信小游戏](/zh-cn/guides/wechat)。
+
+<Aside type="caution">
+ **1.0 之前。** profile 契约标记为 `@beta`:随着微信之外的平台在真机上跑通,它可能
+ 还会增加字段。
+</Aside>
+
+## 接入一个平台的成本
+
+一个 profile 就是**三个事实,外加至多一个方法**:
+
+```ts
+import { installMiniGamePlatform } from 'esengine/minigame';
+
+declare const myHost: any; // 宿主全局对象,例如 `tt`
+
+installMiniGamePlatform({
+ id: 'myvendor',
+ hostLabel: 'MyVendor',
+ get global() { return myHost; },
+});
+```
+
+这就是一个完整的平台。文件系统、`fetch`、canvas、图片解码、触摸与按键输入、存储、
+分包、内存告警、设备像素比、语言,全部来自归一化后的宿主全局对象。**音频**
+(`createInnerAudioContext`)和 **socket**(`connectSocket`)也一样。视频走引擎自带的
+wasm MPEG-1 解码器,对任何宿主都可移植。
+
+`global` 要像上面那样用 getter 读取:宿主全局在运行时才存在,用 getter 才能保证在打包
+工具或测试里 import 你的 profile 时不会碰到未定义的绑定。
+
+### 唯一真正的分歧
+
+WASM 实例化。微信走 `WXWebAssembly.instantiate(path)` 而不是标准 `WebAssembly`,
+所以它的 profile 覆盖了这一个方法:
+
+```ts
+{
+ id: 'wechat',
+ hostLabel: 'WeChat',
+ get global() { return wx as unknown as MiniGameGlobal; },
+ instantiateWasm(pathOrBuffer, imports) { /* WXWebAssembly */ },
+}
+```
+
+如果你的宿主用标准 `WebAssembly`,就不用写它——家族会通过打包文件系统读出二进制并
+实例化。
+
+`createAudioBackend`、`createVideoBackend`、`createSocket` 同样是可选的。只在宿主
+**确实**不同的地方覆盖;默认实现是 `MiniGameAudioBackend`、wasm 视频解码器和
+`MiniGameSocket`,它们都从 `esengine/minigame` 导出,你可以包装而不必重写。
+
+## 宿主需要提供什么
+
+你的 `global` 需要满足 `MiniGameGlobal`。必需成员:
+
+| 成员 | 用途 |
+| --- | --- |
+| `createCanvas()` | 上屏画布(第一次调用)+ 离屏 2D |
+| `createImage()` | 图片解码 |
+| `getFileSystemManager()` | `readFileSync` / `readFile` / `access` / `accessSync` / `writeFile` |
+| `request(opts)` | `fetch` polyfill |
+| `createInnerAudioContext()` | 音频播放 |
+| `connectSocket(opts)` | `GameSocket` / 状态同步 |
+| `getSystemInfoSync()` | 视口尺寸、像素比、语言 |
+| `onTouchStart/Move/End` + `off*` | 指针输入 |
+| `getStorageSync` / `setStorageSync` / `removeStorageSync` / `getStorageInfoSync` | 存档、热更新记账 |
+
+可选成员——适配器会探测,宿主缺失时优雅降级:`onTouchCancel`/`offTouchCancel`、
+`onKeyDown`/`onKeyUp`(及 `off*`)、`loadSubpackage`、
+`onMemoryWarning`/`offMemoryWarning`、`onShow`/`onHide`。
+
+<Aside type="note">
+ `isMiniGame()` 读的是适配器声明的**家族**,而不是平台名字清单——所以你的平台一装上,
+ 就自动走到所有小游戏代码路径(打包读取、分包组、无 DOM 分支)。`isWeChat()` 仍然返回
+ false,这是对的:它是厂商判断,不是能力判断。
+</Aside>
+
+## 启动游戏
+
+发布包的入口调用家族 runtime:
+
+```js
+// game.js —— 宿主执行这个文件
+const engineFactory = require('./wasm/esengine.js');
+const bundle = require('./game-bundle.js');
+bundle.boot(engineFactory, { /* side module 工厂 */ });
+```
+
+```ts
+// 与游戏一起打包
+import { installMiniGamePlatform, initMiniGameRuntime } from 'esengine/minigame';
+import { myProfile } from './myProfile';
+
+export function boot(engineFactory, sideModuleFactories) {
+ installMiniGamePlatform(myProfile);
+ return initMiniGameRuntime({
+ engineFactory,
+ engineWasmPath: 'wasm/esengine.wasm',
+ sceneNames: ['Main'],
+ firstScene: 'Main',
+ sideModuleFactories,
+ });
+}
+```
+
+`initMiniGameRuntime` 从适配器取上屏画布,把它的 GL 上下文注册到引擎模块,加载可寻址
+manifest,然后跑起 app——和微信走的是同一条序列。`initWeChatRuntime` 就是这个函数
+填上微信构建产物的 wasm 文件名,没有别的。
+
+<Aside type="note">
+ 必须**先**装平台再调 `initMiniGameRuntime`;漏了会抛错,错误信息里直接给出改法。
+ 在所有小游戏宿主上,进程里第一次 `createCanvas()` 返回的就是上屏画布,所以在 runtime
+ 之前不能有任何代码创建画布。
+</Aside>
+
+## 打包
+
+导出管线(`exportMiniGame`)以同样的方式共享:cook → manifest → 场景变换 →
+side-module 扫描 → 打包 → 配置/入口 → 拷贝运行时。一个平台就是一个
+`MiniGameExportProfile`,描述有差异的部分:
+
+| 字段 | 含义 |
+| --- | --- |
+| `id` | 平台身份——同时是 cook 逐纹理读取的**导入设置键** |
+| `sdkEntryFile` | `esengine` 被 alias 到的 SDK dist 入口 |
+| `runtimeInit` | 生成的入口所 import 的启动函数 |
+| `engineGlueCandidates` | 按优先级查找的引擎 glue 文件名 |
+| `esTarget` | 游戏包与降级后 glue 的语法下限 |
+| `wasmBuildHint` / `sideModuleBuildTargets` | 错误提示里的 `build -t …` 名字 |
+| `nativeSuffixes` / `binRestageExts` | 打包器的后缀策略 |
+| `subpackageDir` | 懒加载分组落盘的位置 |
+| `emitConfigFiles` / `emitEntry` | 该平台的配置文件与 `game.js` |
+
+<Aside type="caution">
+ **导出侧在编辑器里,不在 SDK 里。** 要让一个平台出现在「打包项目」中,需要改引擎:
+ 在 `desktop/electron/miniGameExportProfile.ts` 加 profile、在 `exportGame.ts` 加分派、
+ 在构建弹窗加卡片,如果宿主需要自己的引擎构建,还要在
+ `build-tools/build.config.js` 加 wasm 目标。上面的运行时侧不需要这些——你今天就可以
+ 用自己的打包脚本驱动 `initMiniGameRuntime`,发布到未内置的宿主。
+</Aside>
+
+## 宿主需要单独的引擎构建吗?
+
+只有当它加载不了 web 引擎的 wasm 时才需要。微信需要(`-t wechat`,`ES_BUILD_WXGAME`),
+因为它有 `WXWebAssembly` 且没有 WebGPU。一个支持标准 `WebAssembly` 和 WebGL2 的宿主
+可以直接用 web 构建的 glue——`engineGlueCandidates` 里已经有回退到 `esengine.js` 的
+分支,正是为这种情况准备的。