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: a project can ship its own native module

yhhc7a8c3b1f46f
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index e82e67cfb..83658f2a3 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -46,6 +46,7 @@ import { debugSigningKey, type SigningKey } from '../../build-tools/utils/androi
import { isNativePlatform, type ExportPlatform } from '../src/project/platforms';
import type { SizeBudget } from '../src/project/sizeBudget';
import { measureBuild, type BuildSizeReport } from './sizeReport';
+import { loadProjectModules, sideModuleDeclarations, stageProjectModules } from './projectModules';
import { collectSubsystems, subsystemGapWarnings, targetGaps, type Subsystem } from '../src/project/targetSupport';
export type { ExportPlatform };
@@ -652,6 +653,10 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
// container directly and keep it. Without this a device shows a blank frame: it
// cannot decode an .mp4.
const transcodeVideo = isNativePlatform(platform) || platform === 'wechat';
+ // Optional native modules the PROJECT supplies (.esengine/modules/<id>/), resolved
+ // for this target before anything is staged — their ids ride game.config.json, so
+ // the runtime can acquire them exactly like the engine's own.
+ const projectModules = await loadProjectModules(opts.root, platform);
const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: payloadDir, contentAddressed: opts.contentAddressed ?? true, compressTextures: opts.compressTextures, compressAudio: opts.compressAudio, atlasTextures: opts.atlasTextures, transcodeVideo, platform });
warnings.push(...cook.warnings);
warnings.push(...await unsupportedContentWarnings(opts.root, cook.includedPaths, platform));
@@ -718,6 +723,12 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
else errors.push(`wasm runtime dir not found: ${opts.wasmDir}`);
}
+ // The project's own modules go beside the engine's, so every transport finds
+ // all of them in the one place it already looks. Outside the branch above
+ // because a native target must still be TOLD its modules cannot ship there —
+ // it stages nothing and says so.
+ warnings.push(...await stageProjectModules(projectModules, path.join(payloadDir, 'wasm'), platform));
+
// 5. Host page + entry-scene config. Web pins orientation (rotate-to-fit overlay);
// desktop omits it — the Electron shell sizes its own window to the orientation.
progress({ phase: 'Writing host page' });
@@ -734,6 +745,8 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
...(opts.uiTheme === 'light' ? { uiTheme: opts.uiTheme } : {}),
...(opts.uiThemeColors && Object.keys(opts.uiThemeColors).length > 0 ? { uiThemeColors: opts.uiThemeColors } : {}),
...(hotUpdate ? { hotUpdate } : {}),
+ ...(sideModuleDeclarations(projectModules, platform).length > 0
+ ? { sideModules: sideModuleDeclarations(projectModules, platform) } : {}),
};
await writeFile(path.join(payloadDir, 'game.config.json'), JSON.stringify(gameConfig, null, 2) + '\n');
diff --git a/desktop/electron/exportMiniGame.ts b/desktop/electron/exportMiniGame.ts
index 1a539be6f..82ee0d003 100644
--- a/desktop/electron/exportMiniGame.ts
+++ b/desktop/electron/exportMiniGame.ts
@@ -42,6 +42,7 @@ import {
spineModuleId, SIDE_MODULE_FILE,
} from './sideModuleScan';
import { OPEN_DATA_DIR } from './miniGameExportProfile';
+import { loadProjectModules, sideModuleDeclarations, stageProjectModules } from './projectModules';
import type { MiniGameExportProfile, MiniGameVendor } from './miniGameExportProfile';
export interface ExportMiniGameResult {
@@ -276,7 +277,17 @@ 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(profile, [...sceneRawByName.values()], cookEntries, absOut, opts.wasmDir, errors);
+ const engineSideModules = await scanSideModules(profile, [...sceneRawByName.values()], cookEntries, absOut, opts.wasmDir, errors);
+ // …plus the ones the PROJECT supplies. They are not scanned for: a project put
+ // them in `.esengine/modules/` in order to use them, and unlike physics or
+ // spine there is no component in the scene the engine could recognize as the
+ // thing that needs one. Staged and required by the same code path, so a
+ // third-party runtime loads on a device exactly like a built-in.
+ const projectModules = await loadProjectModules(opts.root, profile.id);
+ const sideModules = [
+ ...engineSideModules,
+ ...projectModules.filter((m) => m.buildDir).map((m) => ({ id: m.id, file: m.file })),
+ ];
const sceneRaw = sceneRawByName.get(sceneName) ?? null;
if (!sceneRaw) errors.push(`entry scene "${opts.entryScene}" was not staged by the cook`);
@@ -303,13 +314,18 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
// this the package would build fine and then throw on the device, which is
// the worst place to learn that the two halves of a vendor were never joined.
const installsPlatform = !!profile.runtimeProfileModule;
+ // A mini-game does not read game.config.json — its configuration IS this
+ // generated call — so the project modules' artifact names ride it here. The
+ // factories arrive separately (game.js require()s the glue); this is what tells
+ // the runtime where each binary sits in the package.
+ const projectDeclarations = sideModuleDeclarations(projectModules, profile.id);
const entrySrc =
`import { ${profile.runtimeInit}${installsPlatform ? ', installMiniGamePlatform' : ''}${themeColors ? ', parseThemeOverrides' : ''} } from 'esengine';\n` +
(installsPlatform ? `import __platformProfile from ${JSON.stringify(profile.runtimeProfileModule)};\n` : '') +
(scriptsAbs && existsSync(scriptsAbs) ? `import ${JSON.stringify(scriptsAbs)};\n` : '') +
`export function boot(engineFactory, sideModuleFactories) {\n` +
(installsPlatform ? ` installMiniGamePlatform(__platformProfile);\n` : '') +
- ` return ${profile.runtimeInit}({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}, sideModuleFactories, sceneNames: ${JSON.stringify(scenes.map((s) => s.name))}, firstScene: ${JSON.stringify(sceneName)}${opts.ySortLayers ? `, ySortLayers: ${opts.ySortLayers >>> 0}` : ''}${opts.colorSpace === 'linear' ? `, colorSpace: 'linear'` : ''}${opts.screenFit && opts.screenFit.scaleMode >= 0 ? `, screenFit: ${JSON.stringify(opts.screenFit)}` : ''}${opts.uiTheme === 'light' ? `, uiTheme: 'light'` : ''}${themeColors ? `, uiThemeOverrides: parseThemeOverrides(${JSON.stringify(themeColors)})` : ''} });\n` +
+ ` return ${profile.runtimeInit}({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}, sideModuleFactories, sceneNames: ${JSON.stringify(scenes.map((s) => s.name))}, firstScene: ${JSON.stringify(sceneName)}${opts.ySortLayers ? `, ySortLayers: ${opts.ySortLayers >>> 0}` : ''}${opts.colorSpace === 'linear' ? `, colorSpace: 'linear'` : ''}${opts.screenFit && opts.screenFit.scaleMode >= 0 ? `, screenFit: ${JSON.stringify(opts.screenFit)}` : ''}${opts.uiTheme === 'light' ? `, uiTheme: 'light'` : ''}${themeColors ? `, uiThemeOverrides: parseThemeOverrides(${JSON.stringify(themeColors)})` : ''}${projectDeclarations.length > 0 ? `, sideModules: ${JSON.stringify(projectDeclarations)}` : ''} });\n` +
`}\n`;
progress({ phase: 'Bundling game' });
try {
@@ -410,10 +426,12 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
const wasmOut = path.join(absOut, 'wasm');
await rm(wasmOut, { recursive: true, force: true });
await mkdir(wasmOut, { recursive: true });
+ // Engine artifacts only — the project's own come from `.esengine/modules/`,
+ // not from the engine runtime dir, and are staged below.
const runtimeFiles = [
engineGlueFile,
engineGlueFile.replace(/\.js$/, '.wasm'),
- ...sideModules.flatMap((m) => [`${m.file}.js`, `${m.file}.wasm`]),
+ ...engineSideModules.flatMap((m) => [`${m.file}.js`, `${m.file}.wasm`]),
];
const { transform } = await loadEsbuild();
for (const f of runtimeFiles) {
@@ -432,6 +450,10 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
await cp(src, dest);
}
}
+ // The project's own modules land in the same wasm/ dir, with the same glue
+ // down-level applied — game.js require()s them by the same path.
+ warnings.push(...await stageProjectModules(projectModules, wasmOut, profile.id,
+ async (code) => (await transform(code, { target: profile.esTarget, loader: 'js' })).code));
return { ok: errors.length === 0, platform: profile.id, outDir: absOut, included: cook.included.length, warnings, errors };
}
diff --git a/desktop/electron/projectModules.ts b/desktop/electron/projectModules.ts
new file mode 100644
index 000000000..4d552e428
--- /dev/null
+++ b/desktop/electron/projectModules.ts
@@ -0,0 +1,194 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Optional native modules a PROJECT supplies — the third-party half of
+ * `sdk/src/sideModules/registry.ts`.
+ *
+ * The engine ships a handful of these (physics, basis, the spine
+ * runtimes) and they get real treatment everywhere: acquired through one
+ * host, staged into the package, required by name on a mini-game, inlined
+ * as base64 in a playable. A third-party runtime — a vector-animation
+ * player, another solver — had none of that. It could be fetched by hand
+ * on the web, which is exactly the platform where doing it by hand is
+ * easiest and least necessary; on a mini-game there is no `fetch` and the
+ * binary has to be IN the package, and a playable has no files at all.
+ *
+ * So a project declares its modules the way it declares its own export
+ * platforms (`.esengine/platforms/<id>.mjs`), and from there they are
+ * ordinary side modules:
+ *
+ * .esengine/modules/<id>/
+ * module.json { "file": "rive", "globalName": "RiveModule" }
+ * web/rive.js rive.wasm ← web, desktop, playable
+ * wechat/rive.js rive.wasm ← every mini-game vendor
+ *
+ * Per-platform directories rather than one build, because that is the
+ * actual shape of the problem: a mini-game needs its own emscripten build
+ * (WXWebAssembly glue, a different es-target), which is why the engine's
+ * own modules are built twice too. A module with no build for the target
+ * being exported is a WARNING, not a failure — the package is otherwise
+ * correct and the game can degrade, the same way it degrades when a
+ * capability is absent.
+ *
+ * Pure Node (fs). Read by the exporters; the ids they stage are written
+ * into game.config.json, which is how the runtime learns them.
+ */
+import { readFile, readdir, cp, mkdir, writeFile } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { isNativePlatform, type ExportPlatform } from '../src/project/platforms';
+
+/** Where a project keeps them. */
+export const PROJECT_MODULES_DIR = path.join('.esengine', 'modules');
+
+/** A project module, as declared and located. */
+export interface ProjectModule {
+ /** Directory name = the `SideModuleId` a game passes to `acquire`. */
+ id: string;
+ /** Artifact base name: the glue is `<file>.js`, the binary `<file>.wasm`. */
+ file: string;
+ /** Global the emscripten glue assigns its factory to (`EXPORT_NAME`); absent
+ * when the glue is an ES module whose default export is the factory. */
+ globalName?: string;
+ /** Absolute directory holding the build for the platform asked about, or null
+ * when this module has no build for it. */
+ buildDir: string | null;
+}
+
+/**
+ * Which build directory serves a target.
+ *
+ * `web` covers desktop and playable too — all three run the same web glue in the
+ * same JS engine. Mini-game vendors share `wechat`, which is where the engine's
+ * own WXWebAssembly builds already live; a vendor whose runtime genuinely
+ * differs can be given its own directory by id, checked first.
+ */
+function buildDirNames(platform: ExportPlatform): string[] {
+ if (platform === 'web' || platform === 'desktop' || platform === 'playable') return ['web'];
+ if (platform === 'wechat') return ['wechat'];
+ // A project's own mini-game vendor: its id first, then the WeChat build,
+ // which is what every mini-game host's toolchain is a variant of.
+ return [platform, 'wechat', 'web'];
+}
+
+interface ModuleManifest {
+ file?: string;
+ globalName?: string;
+}
+
+/**
+ * Every module a project declares, with the build that serves `platform`
+ * resolved (or null). Returns empty when the project declares none, which is
+ * every project that never asked for this.
+ */
+export async function loadProjectModules(root: string, platform: ExportPlatform): Promise<ProjectModule[]> {
+ const dir = path.join(root, PROJECT_MODULES_DIR);
+ if (!existsSync(dir)) return [];
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ const modules: ProjectModule[] = [];
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ const moduleDir = path.join(dir, entry.name);
+ let manifest: ModuleManifest = {};
+ try {
+ manifest = JSON.parse(await readFile(path.join(moduleDir, 'module.json'), 'utf8')) as ModuleManifest;
+ } catch {
+ // No manifest, or unreadable: the directory name is still the id and
+ // the artifact base defaults to it, so a module whose files follow
+ // the convention needs no manifest at all.
+ }
+ const file = typeof manifest.file === 'string' && manifest.file !== '' ? manifest.file : entry.name;
+ const buildDir = buildDirNames(platform)
+ .map((name) => path.join(moduleDir, name))
+ .find((candidate) => existsSync(path.join(candidate, `${file}.js`))) ?? null;
+ const module: ProjectModule = { id: entry.name, file, buildDir };
+ if (typeof manifest.globalName === 'string' && manifest.globalName !== '') {
+ module.globalName = manifest.globalName;
+ }
+ modules.push(module);
+ }
+ return modules;
+}
+
+/**
+ * What goes into `game.config.json` so the runtime can resolve these ids.
+ *
+ * Takes the platform to hold one invariant: a module is declared only if it was
+ * STAGED. A declaration for a binary that is not in the package is worse than no
+ * declaration — `acquire` would resolve the id, try to load a file that does not
+ * exist, and report a missing artifact instead of an unsupported target.
+ */
+export function sideModuleDeclarations(
+ modules: readonly ProjectModule[],
+ platform: ExportPlatform,
+): Array<{ id: string; file: string; globalName?: string }> {
+ if (isNativePlatform(platform)) return [];
+ return modules
+ .filter((m) => m.buildDir)
+ .map((m) => (m.globalName ? { id: m.id, file: m.file, globalName: m.globalName } : { id: m.id, file: m.file }));
+}
+
+/**
+ * Stage each module's glue + binary into the package's `wasm/` directory —
+ * beside the engine's own, because every transport already looks there and a
+ * second location would be a second thing to get right per realm.
+ *
+ * Returns warnings for modules with no build for this target, named, since the
+ * failure they cause otherwise happens at runtime on a device.
+ */
+export async function stageProjectModules(
+ modules: readonly ProjectModule[],
+ wasmOutDir: string,
+ platform: ExportPlatform,
+ /**
+ * Rewrite the glue on the way in. Mini-game hosts reject syntax emscripten
+ * emits by default (`?.`, `??`), and the export already down-levels the
+ * engine's own glue for exactly that reason — a project module's glue is the
+ * same kind of file and needs the same treatment, so the vendor's rule is
+ * injected here rather than reimplemented.
+ */
+ transformJs?: (code: string) => Promise<string>,
+): Promise<string[]> {
+ const warnings: string[] = [];
+ const staged = modules.filter((m) => m.buildDir);
+ if (isNativePlatform(platform)) {
+ // Native links its modules into the host binary at build time; there is no
+ // load path for one that arrives with the content. Say so and stage
+ // nothing, rather than shipping files that fail to load on a device.
+ if (modules.length > 0) {
+ warnings.push(`Project modules (${modules.map((m) => m.id).join(', ')}) are not packaged for `
+ + 'native targets — the native host links its modules into the app binary, so one shipped '
+ + 'with the content has no way to load. Build it into your native host instead.');
+ }
+ return warnings;
+ }
+ if (staged.length > 0) await mkdir(wasmOutDir, { recursive: true });
+ for (const m of modules) {
+ if (!m.buildDir) {
+ warnings.push(`The project module "${m.id}" has no build for ${platform} `
+ + `(looked for ${buildDirNames(platform).map((d) => `${d}/${m.file}.js`).join(' or ')} under `
+ + `${PROJECT_MODULES_DIR}/${m.id}/) — it was not packaged, and acquiring it will fail at runtime.`);
+ continue;
+ }
+ for (const ext of ['.js', '.wasm']) {
+ const from = path.join(m.buildDir, `${m.file}${ext}`);
+ if (!existsSync(from)) {
+ // The glue is what the lookup keyed on, so a missing .wasm is the
+ // real case here: an emscripten build with the binary embedded in
+ // the glue is legal, so this is not fatal.
+ if (ext === '.wasm') continue;
+ warnings.push(`The project module "${m.id}" is missing ${m.file}${ext} in ${m.buildDir}.`);
+ continue;
+ }
+ const to = path.join(wasmOutDir, `${m.file}${ext}`);
+ if (ext === '.js' && transformJs) await writeFile(to, await transformJs(await readFile(from, 'utf8')));
+ else await cp(from, to);
+ }
+ }
+ return warnings;
+}
diff --git a/desktop/src/gameHost.ts b/desktop/src/gameHost.ts
index 53746b2a4..fe265f3b0 100644
--- a/desktop/src/gameHost.ts
+++ b/desktop/src/gameHost.ts
@@ -14,7 +14,7 @@
import {
createWebApp, setEditorMode, setPlayMode, parseThemeOverrides, Assets,
indexPackagedManifest, createPackagedAssetSource, applyAssetRefResolvers, initRuntime,
- HttpBackend, fetchDecodePixels,
+ HttpBackend, fetchDecodePixels, registerPackagedSideModules,
} from 'esengine';
import type { ESEngineModule, SceneData, AddressableManifest, PackagedGameConfig } from 'esengine';
@@ -42,6 +42,9 @@ async function boot(): Promise<void> {
}
const cfg = (await (await fetch('./game.config.json')).json()) as PackagedGameConfig;
+ // Before anything acquires: the project's own modules were staged into wasm/
+ // beside the engine's, and this is what makes their ids resolvable.
+ registerPackagedSideModules(cfg);
// The addressable manifest is the asset index — the same one the WeChat and
// native runtimes read. It resolves every ref spelling to its staged path and
// carries the atlas metadata the catalog needs, so there is one asset model
diff --git a/desktop/tests/export-game.test.ts b/desktop/tests/export-game.test.ts
index 86a63a71a..2503410a6 100644
--- a/desktop/tests/export-game.test.ts
+++ b/desktop/tests/export-game.test.ts
@@ -1,254 +1,316 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file Game export orchestration (REARCH_EDITOR_REALM Phase S). Asserts
- * exportGame produces a self-contained web build: cooked assets + manifest,
- * the esbuild'd game host (esengine inlined, not external), the copied wasm
- * runtime, index.html, and the entry-scene config. (The host RENDERING is
- * proven separately by play:verify — gameHost reuses initPlayRealmRuntime.)
- */
-import { describe, it, expect, beforeAll, afterAll } from 'vitest';
-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, copyFileSync } from 'node:fs';
-import { createHash } from 'node:crypto';
-import { tmpdir } from 'node:os';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { exportGame } from '../electron/exportGame';
-
-const HERE = path.dirname(fileURLToPath(import.meta.url));
-const GAME_HOST = path.join(HERE, '..', 'src', 'gameHost.ts');
-
-let root: string;
-let out: string;
-const TEX = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
-const SCN = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
-const meta = (uuid: string, type: string) => JSON.stringify({ uuid, version: '2.0', type, importer: {} });
-
-beforeAll(async () => {
- root = mkdtempSync(path.join(tmpdir(), 'estella-export-'));
- // A texture asset + sidecar.
- mkdirSync(path.join(root, 'assets'), { recursive: true });
- // A real PNG so the content-addressed + KTX2-compress export path has valid input.
- copyFileSync(path.resolve(HERE, '..', '..', 'examples', 'hello-world', 'assets', 'textures', 'logo.png'),
- path.join(root, 'assets', 'hero.png'));
- writeFileSync(path.join(root, 'assets', 'hero.png.meta'), meta(TEX, 'texture'));
- // A scene that references the texture by @uuid: + its sidecar.
- mkdirSync(path.join(root, 'scenes'), { recursive: true });
- writeFileSync(
- path.join(root, 'scenes', 'main.esscene'),
- 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 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');
-
- out = path.join(root, 'dist-game');
-}, 60_000);
-
-afterAll(() => rmSync(root, { recursive: true, force: true }));
-
-
-/** Every asset in an addressable manifest, paired with its uuid key. */
-function manifestAssets(manifest: unknown): Array<[string, { type: string; path: string; address?: string; compressedFormats?: string[] }]> {
- const groups = (manifest as { groups: Record<string, { assets: Record<string, never> }> }).groups;
- return Object.values(groups).flatMap((g) => Object.entries(g.assets)) as never;
-}
-
-describe('exportGame', () => {
- 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',
- });
-
- expect(res.ok).toBe(true);
- expect(res.errors).toEqual([]);
- // Reachability pulled the scene + its referenced texture into the build.
- expect(res.included).toBe(2);
-
- 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);
- // The flat manifest is a build-time intermediate — only the addressable one ships.
- expect(has('assets.manifest.json')).toBe(false);
- expect(has('asset-manifest.json')).toBe(true);
- expect(has('scenes/main.esscene')).toBe(true);
- // Content-addressing is on by default now: the texture ships as assets/<hash>.png.
- const m = JSON.parse(readFileSync(path.join(out, 'asset-manifest.json'), 'utf8'));
- const tex = manifestAssets(m).find(([, a]) => a.type === 'texture')![1];
- expect(tex.path).toMatch(/^assets\/[0-9a-f]{16}\.png$/);
- expect(has(tex.path)).toBe(true);
- expect(has('wasm/esengine.js')).toBe(true);
-
- // 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).toBeLessThan(100_000);
- expect(readFileSync(path.join(out, 'scripts.mjs'), 'utf8')).toMatch(/from\s*["']esengine["']/);
-
- // 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');
- // Web pins orientation (default landscape ⇒ rotate-to-fit overlay + best-effort lock).
- expect(html).toContain('id="rotate-hint"');
- expect(html).toContain('Rotate your device to landscape');
- expect(html).toMatch(/screen\.orientation[\s\S]*lock\("landscape"\)/);
- expect(JSON.parse(readFileSync(path.join(out, 'game.config.json'), 'utf8')).entryScene).toBe('scenes/main.esscene');
- }, 60_000);
-
- it('lists every inline script in the page CSP, for either orientation', async () => {
- for (const orientation of ['landscape', 'portrait'] as const) {
- const cspOut = path.join(root, `dist-game-csp-${orientation}`);
- 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: cspOut, orientation,
- });
- expect(res.ok).toBe(true);
-
- const html = readFileSync(path.join(cspOut, 'index.html'), 'utf8');
- const csp = /http-equiv="Content-Security-Policy"\s*\n?\s*content="([^"]+)"/.exec(html)?.[1];
- expect(csp).toBeTruthy();
- // A hash the policy omits means the browser blocks that script — which is how
- // the orientation lock came to be dead in a shipped build.
- const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/g)].map((m) => m[1]);
- expect(inline.length).toBe(2); // the import map + the orientation lock
- for (const body of inline) {
- expect(csp).toContain(`sha256-${createHash('sha256').update(body).digest('base64')}`);
- }
- }
- }, 60_000);
-
- it('writes the project camera fit into game.config.json (only when opted in)', async () => {
- const fitOut = path.join(root, 'dist-game-fit');
- 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: fitOut, title: 'Fit Game',
- screenFit: { designWidth: 1080, designHeight: 1920, scaleMode: 2, matchWidthOrHeight: 0.5 },
- });
- expect(res.ok).toBe(true);
- const cfg = JSON.parse(readFileSync(path.join(fitOut, 'game.config.json'), 'utf8'));
- expect(cfg.screenFit).toEqual({ designWidth: 1080, designHeight: 1920, scaleMode: 2, matchWidthOrHeight: 0.5 });
-
- // Off (scaleMode -1) ⇒ no screenFit key, so an unconfigured game's config is unchanged.
- const offOut = path.join(root, 'dist-game-fitoff');
- 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: offOut,
- screenFit: { designWidth: 1920, designHeight: 1080, scaleMode: -1, matchWidthOrHeight: 0.5 },
- });
- expect(JSON.parse(readFileSync(path.join(offOut, 'game.config.json'), 'utf8')).screenFit).toBeUndefined();
- }, 60_000);
-
- it('content-addresses + KTX2-compresses cooked assets when opted in', async () => {
- const out2 = path.join(root, 'dist-game-ca');
- 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: out2,
- title: 'CA Game',
- contentAddressed: true,
- compressTextures: true,
- });
- expect(res.ok).toBe(true);
- expect(res.errors).toEqual([]);
-
- const manifest = JSON.parse(readFileSync(path.join(out2, 'asset-manifest.json'), 'utf8'));
- const tex = manifestAssets(manifest).find(([uuid]) => uuid.toLowerCase() === TEX)![1];
- // The PNG was encoded to KTX2 and named by content hash; refs stay uuid-based.
- expect(tex.path).toMatch(/^assets\/[0-9a-f]{16}\.ktx2$/);
- expect(tex.compressedFormats).toEqual(['astc-4x4', 'etc2-rgba8', 's3tc-dxt5']);
- const bytes = readFileSync(path.join(out2, tex.path));
- const magic = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
- expect(magic.every((b, i) => bytes[i] === b)).toBe(true);
-
- // The scene keeps its logical name and the whole build still assembled.
- expect(existsSync(path.join(out2, 'scenes/main.esscene'))).toBe(true);
- expect(existsSync(path.join(out2, 'game.js'))).toBe(true);
- }, 60_000);
-
- it('ships every scene in the scenes dir, listed in game.config.json', async () => {
- const LV2SCN = '77777777-7777-7777-7777-777777777777';
- writeFileSync(
- path.join(root, 'scenes', 'level2.esscene'),
- JSON.stringify({ version: '1.0', name: 'Level2', entities: [] }),
- );
- writeFileSync(path.join(root, 'scenes', 'level2.esscene.meta'), meta(LV2SCN, 'scene'));
- const outMulti = path.join(root, 'dist-game-multi');
- 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: outMulti,
- title: 'My Game',
- });
- expect(res.ok).toBe(true);
- // Both scenes staged (web serves .esscene as-is) and listed for the host's
- // SceneManager registration — entry eager, the rest lazy by path.
- expect(existsSync(path.join(outMulti, 'scenes/level2.esscene'))).toBe(true);
- const cfg = JSON.parse(readFileSync(path.join(outMulti, 'game.config.json'), 'utf8'));
- expect(cfg.scenes).toContainEqual({ name: 'main', path: 'scenes/main.esscene' });
- expect(cfg.scenes).toContainEqual({ name: 'level2', path: 'scenes/level2.esscene' });
- expect(cfg.scenes[0]).toEqual({ name: 'main', path: 'scenes/main.esscene' }); // entry first
- }, 60_000);
-
- it('excludeScenes drops a scene from the build; the entry is immune', async () => {
- const outEx = path.join(root, 'dist-game-excluded');
- 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: outEx,
- title: 'My Game',
- // level2 excluded; excluding the entry must be ignored — it boots the game.
- excludeScenes: ['scenes/level2.esscene', 'scenes/main.esscene'],
- });
- expect(res.ok).toBe(true);
- const cfg = JSON.parse(readFileSync(path.join(outEx, 'game.config.json'), 'utf8'));
- expect(cfg.scenes).toEqual([{ name: 'main', path: 'scenes/main.esscene' }]);
- expect(existsSync(path.join(outEx, 'scenes/level2.esscene'))).toBe(false);
- }, 60_000);
-
- it('fails when the wasm runtime is missing — the build cannot boot without it', async () => {
- const out3 = path.join(root, 'dist-game-nowasm');
- 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, '_no-such-wasm'),
- outDir: out3,
- title: 'My Game',
- });
- expect(res.ok).toBe(false);
- expect(res.errors.some((e) => e.includes('wasm runtime dir not found'))).toBe(true);
- }, 60_000);
-});
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Game export orchestration (REARCH_EDITOR_REALM Phase S). Asserts
+ * exportGame produces a self-contained web build: cooked assets + manifest,
+ * the esbuild'd game host (esengine inlined, not external), the copied wasm
+ * runtime, index.html, and the entry-scene config. (The host RENDERING is
+ * proven separately by play:verify — gameHost reuses initPlayRealmRuntime.)
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, copyFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { exportGame } from '../electron/exportGame';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const GAME_HOST = path.join(HERE, '..', 'src', 'gameHost.ts');
+
+let root: string;
+let out: string;
+const TEX = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+const SCN = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
+const meta = (uuid: string, type: string) => JSON.stringify({ uuid, version: '2.0', type, importer: {} });
+
+beforeAll(async () => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-export-'));
+ // A texture asset + sidecar.
+ mkdirSync(path.join(root, 'assets'), { recursive: true });
+ // A real PNG so the content-addressed + KTX2-compress export path has valid input.
+ copyFileSync(path.resolve(HERE, '..', '..', 'examples', 'hello-world', 'assets', 'textures', 'logo.png'),
+ path.join(root, 'assets', 'hero.png'));
+ writeFileSync(path.join(root, 'assets', 'hero.png.meta'), meta(TEX, 'texture'));
+ // A scene that references the texture by @uuid: + its sidecar.
+ mkdirSync(path.join(root, 'scenes'), { recursive: true });
+ writeFileSync(
+ path.join(root, 'scenes', 'main.esscene'),
+ 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 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');
+
+ out = path.join(root, 'dist-game');
+}, 60_000);
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+
+/** Every asset in an addressable manifest, paired with its uuid key. */
+function manifestAssets(manifest: unknown): Array<[string, { type: string; path: string; address?: string; compressedFormats?: string[] }]> {
+ const groups = (manifest as { groups: Record<string, { assets: Record<string, never> }> }).groups;
+ return Object.values(groups).flatMap((g) => Object.entries(g.assets)) as never;
+}
+
+describe('exportGame', () => {
+ 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',
+ });
+
+ expect(res.ok).toBe(true);
+ expect(res.errors).toEqual([]);
+ // Reachability pulled the scene + its referenced texture into the build.
+ expect(res.included).toBe(2);
+
+ 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);
+ // The flat manifest is a build-time intermediate — only the addressable one ships.
+ expect(has('assets.manifest.json')).toBe(false);
+ expect(has('asset-manifest.json')).toBe(true);
+ expect(has('scenes/main.esscene')).toBe(true);
+ // Content-addressing is on by default now: the texture ships as assets/<hash>.png.
+ const m = JSON.parse(readFileSync(path.join(out, 'asset-manifest.json'), 'utf8'));
+ const tex = manifestAssets(m).find(([, a]) => a.type === 'texture')![1];
+ expect(tex.path).toMatch(/^assets\/[0-9a-f]{16}\.png$/);
+ expect(has(tex.path)).toBe(true);
+ expect(has('wasm/esengine.js')).toBe(true);
+
+ // 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).toBeLessThan(100_000);
+ expect(readFileSync(path.join(out, 'scripts.mjs'), 'utf8')).toMatch(/from\s*["']esengine["']/);
+
+ // 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');
+ // Web pins orientation (default landscape ⇒ rotate-to-fit overlay + best-effort lock).
+ expect(html).toContain('id="rotate-hint"');
+ expect(html).toContain('Rotate your device to landscape');
+ expect(html).toMatch(/screen\.orientation[\s\S]*lock\("landscape"\)/);
+ expect(JSON.parse(readFileSync(path.join(out, 'game.config.json'), 'utf8')).entryScene).toBe('scenes/main.esscene');
+ }, 60_000);
+
+ it('lists every inline script in the page CSP, for either orientation', async () => {
+ for (const orientation of ['landscape', 'portrait'] as const) {
+ const cspOut = path.join(root, `dist-game-csp-${orientation}`);
+ 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: cspOut, orientation,
+ });
+ expect(res.ok).toBe(true);
+
+ const html = readFileSync(path.join(cspOut, 'index.html'), 'utf8');
+ const csp = /http-equiv="Content-Security-Policy"\s*\n?\s*content="([^"]+)"/.exec(html)?.[1];
+ expect(csp).toBeTruthy();
+ // A hash the policy omits means the browser blocks that script — which is how
+ // the orientation lock came to be dead in a shipped build.
+ const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/g)].map((m) => m[1]);
+ expect(inline.length).toBe(2); // the import map + the orientation lock
+ for (const body of inline) {
+ expect(csp).toContain(`sha256-${createHash('sha256').update(body).digest('base64')}`);
+ }
+ }
+ }, 60_000);
+
+ it('writes the project camera fit into game.config.json (only when opted in)', async () => {
+ const fitOut = path.join(root, 'dist-game-fit');
+ 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: fitOut, title: 'Fit Game',
+ screenFit: { designWidth: 1080, designHeight: 1920, scaleMode: 2, matchWidthOrHeight: 0.5 },
+ });
+ expect(res.ok).toBe(true);
+ const cfg = JSON.parse(readFileSync(path.join(fitOut, 'game.config.json'), 'utf8'));
+ expect(cfg.screenFit).toEqual({ designWidth: 1080, designHeight: 1920, scaleMode: 2, matchWidthOrHeight: 0.5 });
+
+ // Off (scaleMode -1) ⇒ no screenFit key, so an unconfigured game's config is unchanged.
+ const offOut = path.join(root, 'dist-game-fitoff');
+ 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: offOut,
+ screenFit: { designWidth: 1920, designHeight: 1080, scaleMode: -1, matchWidthOrHeight: 0.5 },
+ });
+ expect(JSON.parse(readFileSync(path.join(offOut, 'game.config.json'), 'utf8')).screenFit).toBeUndefined();
+ }, 60_000);
+
+ it('content-addresses + KTX2-compresses cooked assets when opted in', async () => {
+ const out2 = path.join(root, 'dist-game-ca');
+ 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: out2,
+ title: 'CA Game',
+ contentAddressed: true,
+ compressTextures: true,
+ });
+ expect(res.ok).toBe(true);
+ expect(res.errors).toEqual([]);
+
+ const manifest = JSON.parse(readFileSync(path.join(out2, 'asset-manifest.json'), 'utf8'));
+ const tex = manifestAssets(manifest).find(([uuid]) => uuid.toLowerCase() === TEX)![1];
+ // The PNG was encoded to KTX2 and named by content hash; refs stay uuid-based.
+ expect(tex.path).toMatch(/^assets\/[0-9a-f]{16}\.ktx2$/);
+ expect(tex.compressedFormats).toEqual(['astc-4x4', 'etc2-rgba8', 's3tc-dxt5']);
+ const bytes = readFileSync(path.join(out2, tex.path));
+ const magic = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
+ expect(magic.every((b, i) => bytes[i] === b)).toBe(true);
+
+ // The scene keeps its logical name and the whole build still assembled.
+ expect(existsSync(path.join(out2, 'scenes/main.esscene'))).toBe(true);
+ expect(existsSync(path.join(out2, 'game.js'))).toBe(true);
+ }, 60_000);
+
+ it('ships every scene in the scenes dir, listed in game.config.json', async () => {
+ const LV2SCN = '77777777-7777-7777-7777-777777777777';
+ writeFileSync(
+ path.join(root, 'scenes', 'level2.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Level2', entities: [] }),
+ );
+ writeFileSync(path.join(root, 'scenes', 'level2.esscene.meta'), meta(LV2SCN, 'scene'));
+ const outMulti = path.join(root, 'dist-game-multi');
+ 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: outMulti,
+ title: 'My Game',
+ });
+ expect(res.ok).toBe(true);
+ // Both scenes staged (web serves .esscene as-is) and listed for the host's
+ // SceneManager registration — entry eager, the rest lazy by path.
+ expect(existsSync(path.join(outMulti, 'scenes/level2.esscene'))).toBe(true);
+ const cfg = JSON.parse(readFileSync(path.join(outMulti, 'game.config.json'), 'utf8'));
+ expect(cfg.scenes).toContainEqual({ name: 'main', path: 'scenes/main.esscene' });
+ expect(cfg.scenes).toContainEqual({ name: 'level2', path: 'scenes/level2.esscene' });
+ expect(cfg.scenes[0]).toEqual({ name: 'main', path: 'scenes/main.esscene' }); // entry first
+ }, 60_000);
+
+ it('excludeScenes drops a scene from the build; the entry is immune', async () => {
+ const outEx = path.join(root, 'dist-game-excluded');
+ 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: outEx,
+ title: 'My Game',
+ // level2 excluded; excluding the entry must be ignored — it boots the game.
+ excludeScenes: ['scenes/level2.esscene', 'scenes/main.esscene'],
+ });
+ expect(res.ok).toBe(true);
+ const cfg = JSON.parse(readFileSync(path.join(outEx, 'game.config.json'), 'utf8'));
+ expect(cfg.scenes).toEqual([{ name: 'main', path: 'scenes/main.esscene' }]);
+ expect(existsSync(path.join(outEx, 'scenes/level2.esscene'))).toBe(false);
+ }, 60_000);
+
+ it('fails when the wasm runtime is missing — the build cannot boot without it', async () => {
+ const out3 = path.join(root, 'dist-game-nowasm');
+ 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, '_no-such-wasm'),
+ outDir: out3,
+ title: 'My Game',
+ });
+ expect(res.ok).toBe(false);
+ expect(res.errors.some((e) => e.includes('wasm runtime dir not found'))).toBe(true);
+ }, 60_000);
+
+ // A third-party runtime (a vector-animation player, another solver) as an
+ // ordinary side module: staged beside the engine's own and declared in the
+ // config, which is the whole difference between `acquire('rive')` working and
+ // a game having to fetch and instantiate a wasm by hand.
+ it("ships a project's own native module and declares it for the runtime", async () => {
+ const modDir = path.join(root, '.esengine', 'modules', 'rive');
+ mkdirSync(path.join(modDir, 'web'), { recursive: true });
+ writeFileSync(path.join(modDir, 'module.json'), JSON.stringify({ file: 'rive', globalName: 'RiveModule' }));
+ writeFileSync(path.join(modDir, 'web', 'rive.js'), 'var RiveModule = () => Promise.resolve({});');
+ writeFileSync(path.join(modDir, 'web', 'rive.wasm'), '\0asm');
+
+ const outMod = path.join(root, 'dist-game-module');
+ 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: outMod,
+ title: 'My Game',
+ });
+ expect(res.ok).toBe(true);
+
+ // Beside the engine's own artifacts — one place, so every transport finds it.
+ expect(existsSync(path.join(outMod, 'wasm', 'rive.js'))).toBe(true);
+ expect(existsSync(path.join(outMod, 'wasm', 'rive.wasm'))).toBe(true);
+ expect(existsSync(path.join(outMod, 'wasm', 'esengine.js'))).toBe(true);
+
+ const cfg = JSON.parse(readFileSync(path.join(outMod, 'game.config.json'), 'utf8'));
+ expect(cfg.sideModules).toEqual([{ id: 'rive', file: 'rive', globalName: 'RiveModule' }]);
+
+ rmSync(path.join(root, '.esengine'), { recursive: true, force: true });
+ }, 60_000);
+
+ it('says so when a project module has no build for the target, rather than shipping a broken package', async () => {
+ const modDir = path.join(root, '.esengine', 'modules', 'rive');
+ mkdirSync(path.join(modDir, 'web'), { recursive: true });
+ writeFileSync(path.join(modDir, 'web', 'rive.js'), 'export default () => Promise.resolve({});');
+
+ const outMod = path.join(root, 'dist-game-module-android');
+ 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: outMod,
+ platform: 'android',
+ title: 'My Game',
+ });
+ expect(res.ok).toBe(true);
+ expect(res.warnings.join('\n')).toContain('app binary');
+ // Not declared, because it was not staged: a declaration whose binary is
+ // absent reports a missing file instead of an unsupported target.
+ const cfg = JSON.parse(readFileSync(path.join(outMod, 'game.config.json'), 'utf8'));
+ expect(cfg.sideModules).toBeUndefined();
+
+ rmSync(path.join(root, '.esengine'), { recursive: true, force: true });
+ }, 60_000);
+});
diff --git a/desktop/tests/export-wechat.test.ts b/desktop/tests/export-wechat.test.ts
index 43c1d6fea..7fa7e2998 100644
--- a/desktop/tests/export-wechat.test.ts
+++ b/desktop/tests/export-wechat.test.ts
@@ -188,6 +188,77 @@ describe('exportGame (wechat)', () => {
.toBe(20 * 1024 * 1024);
}, 60_000);
+ // The platform this matters most on: a mini-game has no `fetch`, so a
+ // third-party runtime cannot be loaded by hand at all — the binary has to be
+ // in the package and the glue has to be require()d by the generated entry.
+ it("packages a project's own native module and requires it from game.js", async () => {
+ const modDir = path.join(root, '.esengine', 'modules', 'rive');
+ rmSync(path.join(root, '.esengine'), { recursive: true, force: true });
+ mkdirSync(path.join(modDir, 'wechat'), { recursive: true });
+ writeFileSync(path.join(modDir, 'module.json'), JSON.stringify({ file: 'rive', globalName: 'RiveModule' }));
+ // `?.` is exactly what a real-device host rejects — it must not survive.
+ writeFileSync(path.join(modDir, 'wechat', 'rive.js'), 'var RiveModule = (o) => Promise.resolve(o?.x);');
+ writeFileSync(path.join(modDir, 'wechat', 'rive.wasm'), 'wasmbytes');
+
+ const outWx = path.join(root, 'dist-wechat-module');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wxwasm'),
+ outDir: outWx,
+ platform: 'wechat',
+ });
+ expect(res.ok).toBe(true);
+
+ // Staged beside the engine's runtime, in the dir game.js require()s from.
+ expect(existsSync(path.join(outWx, 'wasm', 'rive.js'))).toBe(true);
+ expect(existsSync(path.join(outWx, 'wasm', 'rive.wasm'))).toBe(true);
+ // The generated entry hands its factory in by id, like a built-in module.
+ const gameJs = readFileSync(path.join(outWx, 'game.js'), 'utf8');
+ expect(gameJs).toContain(`"rive": asFactory(require('./wasm/rive.js'))`);
+ // A mini-game does not read game.config.json — its config IS the boot call,
+ // so the artifact name rides there or the runtime cannot find the binary.
+ // Matched loosely: the bundler re-prints the object literal.
+ const bundle = readFileSync(path.join(outWx, 'game-bundle.js'), 'utf8');
+ const declaration = bundle.match(/sideModules:\s*\[[^\]]*\]/)?.[0] ?? '(no sideModules in the boot call)';
+ expect(declaration).toContain('"rive"');
+ expect(declaration).toContain('RiveModule');
+ // Down-levelled like the engine's own glue.
+ expect(readFileSync(path.join(outWx, 'wasm', 'rive.js'), 'utf8')).not.toContain('?.');
+
+ rmSync(path.join(root, '.esengine'), { recursive: true, force: true });
+ }, 60_000);
+
+ it('refuses to substitute a web build for a mini-game one', async () => {
+ // Serving the web glue would produce a package that builds clean and dies on
+ // a device — the failure this whole per-platform layout exists to prevent.
+ const modDir = path.join(root, '.esengine', 'modules', 'rive');
+ rmSync(path.join(root, '.esengine'), { recursive: true, force: true });
+ mkdirSync(path.join(modDir, 'web'), { recursive: true });
+ writeFileSync(path.join(modDir, 'web', 'rive.js'), 'export default () => Promise.resolve({});');
+
+ const outWx = path.join(root, 'dist-wechat-module-webonly');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wxwasm'),
+ outDir: outWx,
+ platform: 'wechat',
+ });
+ expect(res.ok).toBe(true);
+ expect(res.warnings.join('\n')).toContain('wechat/rive.js');
+ expect(existsSync(path.join(outWx, 'wasm', 'rive.js'))).toBe(false);
+ expect(readFileSync(path.join(outWx, 'game.js'), 'utf8')).not.toContain('rive');
+
+ rmSync(path.join(root, '.esengine'), { recursive: true, force: true });
+ }, 60_000);
+
it('fails fast when the -t wechat engine runtime is missing', async () => {
const outMissing = path.join(root, 'dist-wechat-missing');
const res = await exportGame({
diff --git a/desktop/tests/project-modules.test.ts b/desktop/tests/project-modules.test.ts
new file mode 100644
index 000000000..89ca5a88f
--- /dev/null
+++ b/desktop/tests/project-modules.test.ts
@@ -0,0 +1,164 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Optional native modules a project supplies.
+ *
+ * The engine's own side modules (physics, basis, the spine runtimes) get real
+ * treatment on every target: acquired through one host, staged into the package,
+ * required by name on a mini-game. A third-party runtime had none of it, and the
+ * platform where doing it by hand is impossible — a mini-game, with no `fetch`
+ * and a binary that must be IN the package — is the platform this engine targets
+ * first.
+ *
+ * The invariant that matters most here is the boring one: a module is DECLARED
+ * only if it was STAGED. A declaration whose binary is not in the package turns
+ * "this target doesn't support it" into "the file 404'd", which is a much harder
+ * thing to understand from a device.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, rm, writeFile, mkdir, readFile, readdir } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import {
+ loadProjectModules, sideModuleDeclarations, stageProjectModules, PROJECT_MODULES_DIR,
+} from '../electron/projectModules';
+
+let root: string;
+
+/** A module directory as a project would lay one out. */
+async function writeModule(id: string, opts: {
+ manifest?: Record<string, unknown> | null;
+ builds?: Record<string, string[]>;
+} = {}): Promise<void> {
+ const dir = path.join(root, PROJECT_MODULES_DIR, id);
+ await mkdir(dir, { recursive: true });
+ if (opts.manifest !== null) {
+ await writeFile(path.join(dir, 'module.json'), JSON.stringify(opts.manifest ?? { file: id }));
+ }
+ for (const [platform, files] of Object.entries(opts.builds ?? {})) {
+ await mkdir(path.join(dir, platform), { recursive: true });
+ for (const f of files) await writeFile(path.join(dir, platform, f), `/* ${f} */`);
+ }
+}
+
+beforeEach(async () => { root = await mkdtemp(path.join(tmpdir(), 'es-modules-')); });
+afterEach(async () => { await rm(root, { recursive: true, force: true }); });
+
+describe('discovery', () => {
+ it('finds nothing in a project that declares nothing', async () => {
+ expect(await loadProjectModules(root, 'web')).toEqual([]);
+ });
+
+ it('takes the directory name as the id, and the manifest for the rest', async () => {
+ await writeModule('rive', {
+ manifest: { file: 'rive_runtime', globalName: 'RiveModule' },
+ builds: { web: ['rive_runtime.js', 'rive_runtime.wasm'] },
+ });
+ const [m] = await loadProjectModules(root, 'web');
+ expect(m.id).toBe('rive');
+ expect(m.file).toBe('rive_runtime');
+ expect(m.globalName).toBe('RiveModule');
+ expect(m.buildDir).toContain(path.join('rive', 'web'));
+ });
+
+ it('needs no manifest when the files follow the convention', async () => {
+ await writeModule('lottie', { manifest: null, builds: { web: ['lottie.js', 'lottie.wasm'] } });
+ const [m] = await loadProjectModules(root, 'web');
+ expect(m).toMatchObject({ id: 'lottie', file: 'lottie' });
+ expect(m.buildDir).not.toBeNull();
+ });
+
+ it('serves desktop and playable from the web build — same glue, same engine', async () => {
+ await writeModule('rive', { builds: { web: ['rive.js', 'rive.wasm'] } });
+ for (const platform of ['web', 'desktop', 'playable'] as const) {
+ expect((await loadProjectModules(root, platform))[0].buildDir).not.toBeNull();
+ }
+ });
+
+ it('will not serve a mini-game from the web build', async () => {
+ // WeChat needs its own emscripten build (WXWebAssembly glue, a different
+ // es-target) — which is why the engine builds its own modules twice too.
+ // Substituting the web one produces a package that fails on a device.
+ await writeModule('rive', { builds: { web: ['rive.js', 'rive.wasm'] } });
+ expect((await loadProjectModules(root, 'wechat'))[0].buildDir).toBeNull();
+ });
+
+ it('lets a project vendor use its own directory, else the wechat build', async () => {
+ await writeModule('rive', { builds: { wechat: ['rive.js'], 'acme-play': ['rive.js'] } });
+ expect((await loadProjectModules(root, 'acme-play'))[0].buildDir).toContain('acme-play');
+ await rm(path.join(root, PROJECT_MODULES_DIR, 'rive', 'acme-play'), { recursive: true });
+ expect((await loadProjectModules(root, 'acme-play'))[0].buildDir).toContain('wechat');
+ });
+});
+
+describe('declarations', () => {
+ it('declares only what was staged', async () => {
+ await writeModule('has-build', { builds: { web: ['has-build.js'] } });
+ await writeModule('no-build', {});
+ const modules = await loadProjectModules(root, 'web');
+ expect(sideModuleDeclarations(modules, 'web').map((d) => d.id)).toEqual(['has-build']);
+ });
+
+ it('declares nothing for native, which cannot load one', async () => {
+ await writeModule('rive', { builds: { web: ['rive.js'] } });
+ const modules = await loadProjectModules(root, 'android');
+ expect(sideModuleDeclarations(modules, 'android')).toEqual([]);
+ });
+
+ it('carries globalName only when there is one', async () => {
+ await writeModule('a', { manifest: { file: 'a', globalName: 'AModule' }, builds: { web: ['a.js'] } });
+ await writeModule('b', { builds: { web: ['b.js'] } });
+ const decls = sideModuleDeclarations(await loadProjectModules(root, 'web'), 'web');
+ expect(decls.find((d) => d.id === 'a')).toEqual({ id: 'a', file: 'a', globalName: 'AModule' });
+ expect(decls.find((d) => d.id === 'b')).toEqual({ id: 'b', file: 'b' });
+ });
+});
+
+describe('staging', () => {
+ let out: string;
+ beforeEach(async () => { out = await mkdtemp(path.join(tmpdir(), 'es-wasm-')); });
+ afterEach(async () => { await rm(out, { recursive: true, force: true }); });
+
+ it('puts glue and binary where every transport already looks', async () => {
+ await writeModule('rive', { builds: { web: ['rive.js', 'rive.wasm'] } });
+ const warnings = await stageProjectModules(await loadProjectModules(root, 'web'), out, 'web');
+ expect(warnings).toEqual([]);
+ expect((await readdir(out)).sort()).toEqual(['rive.js', 'rive.wasm']);
+ });
+
+ it('tolerates a build whose binary is embedded in the glue', async () => {
+ await writeModule('rive', { builds: { web: ['rive.js'] } });
+ const warnings = await stageProjectModules(await loadProjectModules(root, 'web'), out, 'web');
+ expect(warnings).toEqual([]);
+ expect(await readdir(out)).toEqual(['rive.js']);
+ });
+
+ it('names the module and where it looked when there is no build for the target', async () => {
+ await writeModule('rive', { builds: { web: ['rive.js'] } });
+ const warnings = await stageProjectModules(await loadProjectModules(root, 'wechat'), out, 'wechat');
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toContain('"rive"');
+ expect(warnings[0]).toContain('wechat/rive.js');
+ expect(existsSync(path.join(out, 'rive.js'))).toBe(false);
+ });
+
+ it('stages nothing on native, and says why', async () => {
+ await writeModule('rive', { builds: { web: ['rive.js'] } });
+ const warnings = await stageProjectModules(await loadProjectModules(root, 'android'), out, 'android');
+ expect(warnings.join('\n')).toContain('app binary');
+ expect(await readdir(out)).toEqual([]);
+ });
+
+ it('rewrites the glue when the vendor demands it', async () => {
+ // Mini-game hosts reject syntax emscripten emits by default; the export
+ // already down-levels the engine's glue, and a project module's glue is the
+ // same kind of file.
+ await writeModule('rive', { builds: { wechat: ['rive.js', 'rive.wasm'] } });
+ await stageProjectModules(await loadProjectModules(root, 'wechat'), out, 'wechat',
+ async (code) => `${code}// down-levelled`);
+ expect(await readFile(path.join(out, 'rive.js'), 'utf8')).toContain('// down-levelled');
+ // …and leaves the binary alone.
+ expect(await readFile(path.join(out, 'rive.wasm'), 'utf8')).not.toContain('down-levelled');
+ });
+});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2a38a581b..5cb373d0b 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: 1419 stable · 17 beta · 1 deprecated
+Symbols: 1426 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -1217,6 +1217,11 @@ label: string
source: string
```
+## BuiltinSideModuleId — type
+```
+'physics' | 'basis' | 'videodec' | 'dragonbones' | `spine:${SpineVersion}`
+```
+
## BundleMode — type
```
'local' | 'lazy' | 'remote'
@@ -4538,6 +4543,7 @@ entryScene: string
hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+sideModules: { id: string; file: string; globalName?: string; }[] | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
ySortLayers: number | undefined
@@ -5926,7 +5932,7 @@ ComponentDef<{}>
## SIDE_MODULES — const
```
-Record<SideModuleId, SideModuleDescriptor>
+Record<BuiltinSideModuleId, SideModuleDescriptor>
```
## SPINE_VERSIONS — const
@@ -6393,6 +6399,12 @@ static prototype: ShareAPI
PlatformShareOptions
```
+## SideModuleDescriptor — interface
+```
+file: string
+globalName: string | undefined
+```
+
## SideModuleHost — interface
```
acquire: (id: SideModuleId) => Promise<SideModule | null>
@@ -6400,7 +6412,7 @@ acquire: (id: SideModuleId) => Promise<SideModule | null>
## SideModuleId — type
```
-'physics' | 'basis' | 'videodec' | 'dragonbones' | `spine:${SpineVersion}`
+BuiltinSideModuleId | (string & {})
```
## Signal — interface
@@ -8798,6 +8810,11 @@ BtPlugin
(): void
```
+## clearProjectSideModules — function
+```
+(): void
+```
+
## clearTilemapSourceCache — function
```
(): void
@@ -10088,6 +10105,11 @@ PrefabsPlugin
(register: () => Promise<void>): Promise<ProbedRegistrations>
```
+## projectSideModuleIds — function
+```
+(): string[]
+```
+
## px — const
```
(n: number) => Dimension
@@ -10168,6 +10190,11 @@ PrefabsPlugin
(key: string, def: FsmDefinition): CompiledFsm
```
+## registerPackagedSideModules — function
+```
+(config: Pick<PackagedGameConfig, "sideModules">): void
+```
+
## registerPreSceneDrawCallback — function
```
(id: string, fn: PreSceneDrawCallback): void
@@ -10178,6 +10205,11 @@ PrefabsPlugin
(type: string, codec: SceneComponentCodec): void
```
+## registerSideModule — function
+```
+(id: string, descriptor: SideModuleDescriptor): void
+```
+
## registerTilemapSource — function
```
(path: string, data: LoadedTilemapSource): void
@@ -10593,6 +10625,11 @@ ServicesPlugin
(): void
```
+## sideModuleDescriptor — function
+```
+(id: SideModuleId): SideModuleDescriptor | undefined
+```
+
## signal — function
```
<T>(initial: T): Signal<T>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 179969a86..aca24b30e 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: 1438 stable · 22 beta · 1 deprecated
+Symbols: 1445 stable · 22 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -1217,6 +1217,11 @@ label: string
source: string
```
+## BuiltinSideModuleId — type
+```
+'physics' | 'basis' | 'videodec' | 'dragonbones' | `spine:${SpineVersion}`
+```
+
## BundleMode — type
```
'local' | 'lazy' | 'remote'
@@ -4698,6 +4703,7 @@ entryScene: string
hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+sideModules: { id: string; file: string; globalName?: string; }[] | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
ySortLayers: number | undefined
@@ -6096,7 +6102,7 @@ ComponentDef<{}>
## SIDE_MODULES — const
```
-Record<SideModuleId, SideModuleDescriptor>
+Record<BuiltinSideModuleId, SideModuleDescriptor>
```
## SPINE_VERSIONS — const
@@ -6563,6 +6569,12 @@ static prototype: ShareAPI
PlatformShareOptions
```
+## SideModuleDescriptor — interface
+```
+file: string
+globalName: string | undefined
+```
+
## SideModuleHost — interface
```
acquire: (id: SideModuleId) => Promise<SideModule | null>
@@ -6570,7 +6582,7 @@ acquire: (id: SideModuleId) => Promise<SideModule | null>
## SideModuleId — type
```
-'physics' | 'basis' | 'videodec' | 'dragonbones' | `spine:${SpineVersion}`
+BuiltinSideModuleId | (string & {})
```
## Signal — interface
@@ -8983,6 +8995,11 @@ BtPlugin
(): void
```
+## clearProjectSideModules — function
+```
+(): void
+```
+
## clearTilemapSourceCache — function
```
(): void
@@ -10308,6 +10325,11 @@ PrefabsPlugin
(register: () => Promise<void>): Promise<ProbedRegistrations>
```
+## projectSideModuleIds — function
+```
+(): string[]
+```
+
## px — const
```
(n: number) => Dimension
@@ -10388,6 +10410,11 @@ PrefabsPlugin
(key: string, def: FsmDefinition): CompiledFsm
```
+## registerPackagedSideModules — function
+```
+(config: Pick<PackagedGameConfig, "sideModules">): void
+```
+
## registerPreSceneDrawCallback — function
```
(id: string, fn: PreSceneDrawCallback): void
@@ -10398,6 +10425,11 @@ PrefabsPlugin
(type: string, codec: SceneComponentCodec): void
```
+## registerSideModule — function
+```
+(id: string, descriptor: SideModuleDescriptor): void
+```
+
## registerTilemapSource — function
```
(path: string, data: LoadedTilemapSource): void
@@ -10813,6 +10845,11 @@ ServicesPlugin
(): void
```
+## sideModuleDescriptor — function
+```
+(id: SideModuleId): SideModuleDescriptor | undefined
+```
+
## signal — function
```
<T>(initial: T): Signal<T>
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 2783ae7ad..6f8355341 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: 1418 stable · 19 beta · 1 deprecated
+Symbols: 1425 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -1212,6 +1212,11 @@ label: string
source: string
```
+## BuiltinSideModuleId — type
+```
+'physics' | 'basis' | 'videodec' | 'dragonbones' | `spine:${SpineVersion}`
+```
+
## BundleMode — type
```
'local' | 'lazy' | 'remote'
@@ -4533,6 +4538,7 @@ entryScene: string
hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+sideModules: { id: string; file: string; globalName?: string; }[] | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
ySortLayers: number | undefined
@@ -5921,7 +5927,7 @@ ComponentDef<{}>
## SIDE_MODULES — const
```
-Record<SideModuleId, SideModuleDescriptor>
+Record<BuiltinSideModuleId, SideModuleDescriptor>
```
## SPINE_VERSIONS — const
@@ -6388,6 +6394,12 @@ static prototype: ShareAPI
PlatformShareOptions
```
+## SideModuleDescriptor — interface
+```
+file: string
+globalName: string | undefined
+```
+
## SideModuleHost — interface
```
acquire: (id: SideModuleId) => Promise<SideModule | null>
@@ -6395,7 +6407,7 @@ acquire: (id: SideModuleId) => Promise<SideModule | null>
## SideModuleId — type
```
-'physics' | 'basis' | 'videodec' | 'dragonbones' | `spine:${SpineVersion}`
+BuiltinSideModuleId | (string & {})
```
## Signal — interface
@@ -8793,6 +8805,11 @@ BtPlugin
(): void
```
+## clearProjectSideModules — function
+```
+(): void
+```
+
## clearTilemapSourceCache — function
```
(): void
@@ -10093,6 +10110,11 @@ PrefabsPlugin
(register: () => Promise<void>): Promise<ProbedRegistrations>
```
+## projectSideModuleIds — function
+```
+(): string[]
+```
+
## px — const
```
(n: number) => Dimension
@@ -10173,6 +10195,11 @@ PrefabsPlugin
(key: string, def: FsmDefinition): CompiledFsm
```
+## registerPackagedSideModules — function
+```
+(config: Pick<PackagedGameConfig, "sideModules">): void
+```
+
## registerPreSceneDrawCallback — function
```
(id: string, fn: PreSceneDrawCallback): void
@@ -10183,6 +10210,11 @@ PrefabsPlugin
(type: string, codec: SceneComponentCodec): void
```
+## registerSideModule — function
+```
+(id: string, descriptor: SideModuleDescriptor): void
+```
+
## registerTilemapSource — function
```
(path: string, data: LoadedTilemapSource): void
@@ -10598,6 +10630,11 @@ ServicesPlugin
(): void
```
+## sideModuleDescriptor — function
+```
+(id: SideModuleId): SideModuleDescriptor | undefined
+```
+
## signal — function
```
<T>(initial: T): Signal<T>
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index dce2664d9..8e338d1fb 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1439 stable · 17 beta · 1 deprecated
+Symbols: 1446 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -1212,6 +1212,11 @@ label: string
source: string
```
+## BuiltinSideModuleId — type
+```
+'physics' | 'basis' | 'videodec' | 'dragonbones' | `spine:${SpineVersion}`
+```
+
## BundleMode — type
```
'local' | 'lazy' | 'remote'
@@ -4448,6 +4453,7 @@ runtimeConfig: RuntimeBuildConfig | undefined
sceneNames: string[]
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
sideModuleFactories: Partial<Record<SideModuleId, EmscriptenFactory>> | undefined
+sideModules: { id: string; file: string; globalName?: string; }[] | undefined
uiTheme: "dark" | "light" | undefined
uiThemeOverrides: ThemeOverrides | undefined
ySortLayers: number | undefined
@@ -4775,6 +4781,7 @@ entryScene: string
hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+sideModules: { id: string; file: string; globalName?: string; }[] | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
ySortLayers: number | undefined
@@ -6163,7 +6170,7 @@ ComponentDef<{}>
## SIDE_MODULES — const
```
-Record<SideModuleId, SideModuleDescriptor>
+Record<BuiltinSideModuleId, SideModuleDescriptor>
```
## SPINE_VERSIONS — const
@@ -6630,6 +6637,12 @@ static prototype: ShareAPI
PlatformShareOptions
```
+## SideModuleDescriptor — interface
+```
+file: string
+globalName: string | undefined
+```
+
## SideModuleHost — interface
```
acquire: (id: SideModuleId) => Promise<SideModule | null>
@@ -6637,7 +6650,7 @@ acquire: (id: SideModuleId) => Promise<SideModule | null>
## SideModuleId — type
```
-'physics' | 'basis' | 'videodec' | 'dragonbones' | `spine:${SpineVersion}`
+BuiltinSideModuleId | (string & {})
```
## Signal — interface
@@ -9035,6 +9048,11 @@ BtPlugin
(): void
```
+## clearProjectSideModules — function
+```
+(): void
+```
+
## clearTilemapSourceCache — function
```
(): void
@@ -10340,6 +10358,11 @@ PrefabsPlugin
(register: () => Promise<void>): Promise<ProbedRegistrations>
```
+## projectSideModuleIds — function
+```
+(): string[]
+```
+
## px — const
```
(n: number) => Dimension
@@ -10420,6 +10443,11 @@ PrefabsPlugin
(key: string, def: FsmDefinition): CompiledFsm
```
+## registerPackagedSideModules — function
+```
+(config: Pick<PackagedGameConfig, "sideModules">): void
+```
+
## registerPreSceneDrawCallback — function
```
(id: string, fn: PreSceneDrawCallback): void
@@ -10430,6 +10458,11 @@ PrefabsPlugin
(type: string, codec: SceneComponentCodec): void
```
+## registerSideModule — function
+```
+(id: string, descriptor: SideModuleDescriptor): void
+```
+
## registerTilemapSource — function
```
(path: string, data: LoadedTilemapSource): void
@@ -10845,6 +10878,11 @@ ServicesPlugin
(): void
```
+## sideModuleDescriptor — function
+```
+(id: SideModuleId): SideModuleDescriptor | undefined
+```
+
## signal — function
```
<T>(initial: T): Signal<T>
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index fb9a67063..19c2f4d6f 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: 1429 stable · 17 beta · 1 deprecated
+Symbols: 1436 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -1212,6 +1212,11 @@ label: string
source: string
```
+## BuiltinSideModuleId — type
+```
+'physics' | 'basis' | 'videodec' | 'dragonbones' | `spine:${SpineVersion}`
+```
+
## BundleMode — type
```
'local' | 'lazy' | 'remote'
@@ -4540,6 +4545,7 @@ entryScene: string
hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+sideModules: { id: string; file: string; globalName?: string; }[] | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
ySortLayers: number | undefined
@@ -5928,7 +5934,7 @@ ComponentDef<{}>
## SIDE_MODULES — const
```
-Record<SideModuleId, SideModuleDescriptor>
+Record<BuiltinSideModuleId, SideModuleDescriptor>
```
## SPINE_VERSIONS — const
@@ -6395,6 +6401,12 @@ static prototype: ShareAPI
PlatformShareOptions
```
+## SideModuleDescriptor — interface
+```
+file: string
+globalName: string | undefined
+```
+
## SideModuleHost — interface
```
acquire: (id: SideModuleId) => Promise<SideModule | null>
@@ -6402,7 +6414,7 @@ acquire: (id: SideModuleId) => Promise<SideModule | null>
## SideModuleId — type
```
-'physics' | 'basis' | 'videodec' | 'dragonbones' | `spine:${SpineVersion}`
+BuiltinSideModuleId | (string & {})
```
## Signal — interface
@@ -8351,6 +8363,7 @@ runtimeConfig: RuntimeBuildConfig | undefined
sceneNames: string[]
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
sideModuleFactories: Partial<Record<SideModuleId, EmscriptenFactory>> | undefined
+sideModules: { id: string; file: string; globalName?: string; }[] | undefined
uiTheme: "dark" | "light" | undefined
uiThemeOverrides: ThemeOverrides | undefined
ySortLayers: number | undefined
@@ -8817,6 +8830,11 @@ BtPlugin
(): void
```
+## clearProjectSideModules — function
+```
+(): void
+```
+
## clearTilemapSourceCache — function
```
(): void
@@ -10112,6 +10130,11 @@ PrefabsPlugin
(register: () => Promise<void>): Promise<ProbedRegistrations>
```
+## projectSideModuleIds — function
+```
+(): string[]
+```
+
## px — const
```
(n: number) => Dimension
@@ -10192,6 +10215,11 @@ PrefabsPlugin
(key: string, def: FsmDefinition): CompiledFsm
```
+## registerPackagedSideModules — function
+```
+(config: Pick<PackagedGameConfig, "sideModules">): void
+```
+
## registerPreSceneDrawCallback — function
```
(id: string, fn: PreSceneDrawCallback): void
@@ -10202,6 +10230,11 @@ PrefabsPlugin
(type: string, codec: SceneComponentCodec): void
```
+## registerSideModule — function
+```
+(id: string, descriptor: SideModuleDescriptor): void
+```
+
## registerTilemapSource — function
```
(path: string, data: LoadedTilemapSource): void
@@ -10617,6 +10650,11 @@ ServicesPlugin
(): void
```
+## sideModuleDescriptor — function
+```
+(id: SideModuleId): SideModuleDescriptor | undefined
+```
+
## signal — function
```
<T>(initial: T): Signal<T>
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index e59b70209..2dbd1c29f 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -250,6 +250,7 @@ export {
catalogFromManifest,
createPackagedAssetSource,
applyAssetRefResolvers,
+ registerPackagedSideModules,
type PackagedAssetIndex,
type PackagedAssetSourceOptions,
type PackagedGameConfig,
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index d1f837c28..26215ea83 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -227,8 +227,14 @@ export {
SIDE_MODULES,
SPINE_VERSIONS,
spineModuleId,
+ registerSideModule,
+ sideModuleDescriptor,
+ projectSideModuleIds,
+ clearProjectSideModules,
type SideModuleHost,
type SideModuleId,
+ type BuiltinSideModuleId,
+ type SideModuleDescriptor,
type EmbeddedSideModuleEntry,
type EmbeddedSideModuleRegistry,
type WeChatSideModuleFactories,
diff --git a/sdk/src/runtime/miniGameRuntime.ts b/sdk/src/runtime/miniGameRuntime.ts
index aee0ed859..bfaec0a7d 100644
--- a/sdk/src/runtime/miniGameRuntime.ts
+++ b/sdk/src/runtime/miniGameRuntime.ts
@@ -22,7 +22,10 @@ import type { ThemeOverrides } from '../ui';
import { applyBuildRuntimeConfig, type RuntimeBuildConfig } from '../defaults';
import { getPlatform, platformReadTextFile, platformInstantiateWasm } from '../platform';
import { MiniGamePlatformAdapter } from '../platform/minigame';
-import { loadPackagedAssetIndex, createPackagedAssetSource, applyAssetRefResolvers } from './packagedRuntime';
+import {
+ loadPackagedAssetIndex, createPackagedAssetSource, applyAssetRefResolvers,
+ registerPackagedSideModules,
+} from './packagedRuntime';
import { createMiniGameSideModuleHost, type MiniGameSideModuleFactories } from '../sideModules';
import type { Vec2 } from '../types';
import type { SceneData } from '../scene/scene';
@@ -96,9 +99,22 @@ export interface MiniGameRuntimeConfig {
* game.js supplies exactly the modules the scene needs. Physics + spine
* self-gate off these via {@link createMiniGameSideModuleHost}. */
sideModuleFactories?: MiniGameSideModuleFactories;
+ /**
+ * Project-supplied modules (`.esengine/modules/<id>/`) the export staged, so
+ * their ids resolve to an artifact name.
+ *
+ * Separate from the factories above because they answer different questions:
+ * a factory is the glue `game.js` already require()'d, this is where the
+ * BINARY sits — and a mini-game instantiates from a package path, so without
+ * it an acquired module has a factory and nowhere to load from. Built-in ids
+ * need no entry; the engine's table already has them.
+ */
+ sideModules?: Array<{ id: string; file: string; globalName?: string }>;
}
export async function initMiniGameRuntime(config: MiniGameRuntimeConfig): Promise<void> {
+ // Before the app exists, so a plugin that acquires during build finds them.
+ registerPackagedSideModules({ sideModules: config.sideModules });
// The family adapter owns the host global; boot refuses to guess at one.
const adapter = getPlatform();
if (!(adapter instanceof MiniGamePlatformAdapter)) {
diff --git a/sdk/src/runtime/packagedRuntime.ts b/sdk/src/runtime/packagedRuntime.ts
index 5b328012c..3743e9455 100644
--- a/sdk/src/runtime/packagedRuntime.ts
+++ b/sdk/src/runtime/packagedRuntime.ts
@@ -23,6 +23,7 @@ import { Audio } from '../audio/Audio';
import { VideoPlayer } from '../video/VideoAPI';
import type { App } from '../app/app';
import type { RuntimeAssetSource } from './runtimeAssets';
+import { registerSideModule } from '../sideModules/registry';
/**
* `game.config.json` — what an export bakes about the project, and the contract
@@ -48,6 +49,16 @@ export interface PackagedGameConfig {
/** 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 };
+ /**
+ * Optional native modules this project supplied itself, staged beside the
+ * engine's own (see `.esengine/modules/<id>/`).
+ *
+ * The declaration ships rather than being discovered, because discovery is not
+ * possible where it matters: a mini-game cannot list a directory and a
+ * playable has no directory at all. The export knows what it staged, so it
+ * says so, and every transport resolves these ids exactly like a built-in.
+ */
+ sideModules?: Array<{ id: string; file: string; globalName?: string }>;
}
/** The packaged realm's resolved asset index — manifest, catalog, resolution. */
@@ -75,6 +86,22 @@ export interface PackagedAssetIndex {
* a catalog buildPath. Atlas-packed frames additionally register frame/uv, keyed
* by every ref spelling a scene can use.
*/
+/**
+ * Register the project modules this build staged, so `sideModules.acquire(id)`
+ * resolves them the way it resolves the engine's own.
+ *
+ * Every realm calls this after reading its config and before anything acquires —
+ * one line each rather than one clever shared boot, because the four realms do
+ * not share a boot: the web fetches its config, native reads it off disk, a
+ * mini-game requires it, and a playable has it inlined.
+ */
+export function registerPackagedSideModules(config: Pick<PackagedGameConfig, 'sideModules'>): void {
+ for (const m of config.sideModules ?? []) {
+ if (!m?.id || !m.file) continue;
+ registerSideModule(m.id, m.globalName ? { file: m.file, globalName: m.globalName } : { file: m.file });
+ }
+}
+
export function catalogFromManifest(manifest: AddressableManifest): Catalog | undefined {
const entries: Record<string, CatalogEntry> = {};
for (const group of Object.values(manifest.groups)) {
diff --git a/sdk/src/sideModules/host.ts b/sdk/src/sideModules/host.ts
index 24b76369f..7d06d46a1 100644
--- a/sdk/src/sideModules/host.ts
+++ b/sdk/src/sideModules/host.ts
@@ -12,7 +12,7 @@
* / WeChat transports live in sibling files.
*/
import { log } from '../util/logger';
-import { SIDE_MODULES, type SideModuleDescriptor, type SideModuleId } from './registry';
+import { SIDE_MODULES, sideModuleDescriptor, type SideModuleDescriptor, type SideModuleId } from './registry';
/** The instantiated emscripten module. Consumers cwrap their own `_*` exports. */
export type SideModule = Record<string, unknown>;
@@ -37,27 +37,42 @@ export function createSideModuleHost(instantiate: SideModuleInstantiator): SideM
acquire(id: SideModuleId): Promise<SideModule | null> {
const cached = cache.get(id);
if (cached) return cached;
- const descriptor = SIDE_MODULES[id];
+ const descriptor = sideModuleDescriptor(id);
const pending: Promise<SideModule | null> = descriptor
? instantiate(descriptor, id).catch((e) => {
- // A 404 here is almost always a missing local build artifact,
- // not a code failure — say how to produce it.
- log.error(
- 'sidemodule',
- `failed to load "${id}" (${descriptor.file}) — likely not built ` +
- `locally: run the matching wasm build (spine 4.2 = \`pnpm build -t spine\`, ` +
- `others match their file name, \`-t all\` builds everything), then rebuild the editor`,
- e,
- );
+ log.error('sidemodule', `failed to load "${id}" (${descriptor.file}) — ${howToFix(id)}`, e);
return null;
})
- : Promise.resolve(null);
+ // Unknown ids used to be impossible (the type was closed) and so
+ // returned null in silence. Now that a project can name its own,
+ // silence is how a typo becomes "this runtime just doesn't work".
+ : (log.warn('sidemodule', `no module named "${id}" is registered — a built-in id, or one `
+ + 'declared in .esengine/modules/<id>/module.json and picked up by the export'),
+ Promise.resolve(null));
cache.set(id, pending);
return pending;
},
};
}
+/**
+ * What to do about a module that would not load, which differs by who built it.
+ *
+ * For an engine module a 404 is almost always a missing local build artifact, so
+ * the advice is the build command. For a project's own module the engine has no
+ * idea how it is produced — pointing someone at `pnpm build -t rive` would be a
+ * command that does not exist — so it says where the export looked instead.
+ */
+function howToFix(id: SideModuleId): string {
+ if (id in SIDE_MODULES) {
+ return 'likely not built locally: run the matching wasm build (spine 4.2 = '
+ + '`pnpm build -t spine`, others match their file name, `-t all` builds '
+ + 'everything), then rebuild the editor';
+ }
+ return `this is a project module: check that .esengine/modules/${id}/ carries a build for `
+ + 'this platform, and that the export staged it';
+}
+
/** A factory produced by an emscripten `MODULARIZE` glue. */
export type EmscriptenFactory = (opts: Record<string, unknown>) => Promise<SideModule>;
diff --git a/sdk/src/sideModules/index.ts b/sdk/src/sideModules/index.ts
index 7d24330ea..6962563f6 100644
--- a/sdk/src/sideModules/index.ts
+++ b/sdk/src/sideModules/index.ts
@@ -11,7 +11,12 @@ export {
SIDE_MODULES,
SPINE_VERSIONS,
spineModuleId,
+ registerSideModule,
+ sideModuleDescriptor,
+ projectSideModuleIds,
+ clearProjectSideModules,
type SideModuleId,
+ type BuiltinSideModuleId,
type SideModuleDescriptor,
type SpineVersion,
} from './registry';
diff --git a/sdk/src/sideModules/registry.ts b/sdk/src/sideModules/registry.ts
index 9b3209ca9..4ac81a599 100644
--- a/sdk/src/sideModules/registry.ts
+++ b/sdk/src/sideModules/registry.ts
@@ -13,12 +13,31 @@
* and the exporters agree on, so a module can never be referenced by one
* and shipped under a different name by another.
*/
+import { log } from '../util/logger';
/** Spine skeleton format versions Estella ships a dedicated runtime for. */
export type SpineVersion = '2.1' | '3.8' | '4.1' | '4.2' | '4.3';
-/** Identifies an optional native module across every realm and transport. */
-export type SideModuleId = 'physics' | 'basis' | 'videodec' | 'dragonbones' | `spine:${SpineVersion}`;
+/** The modules the engine itself builds and ships. */
+export type BuiltinSideModuleId =
+ 'physics' | 'basis' | 'videodec' | 'dragonbones' | `spine:${SpineVersion}`;
+
+/**
+ * Identifies an optional native module across every realm and transport.
+ *
+ * OPEN, like `ExportPlatform` and `MiniGameVendor`: the built-ins are named for
+ * completion, but a project can drop its own module in `.esengine/modules/<id>/`
+ * and that id flows through acquisition, the export and every transport exactly
+ * like a built-in one. Nothing here branches on the value — it is identity.
+ *
+ * This is what lets a third-party runtime (a vector-animation player, another
+ * physics engine) be a MODULE rather than something a game has to fetch and
+ * instantiate for itself. Doing it by hand works on the web and falls apart
+ * everywhere else: a mini-game has no `fetch` and needs its binary staged into
+ * the package, and a playable needs it inlined as base64. Those are the
+ * transports below, and they are the whole reason to be in this table.
+ */
+export type SideModuleId = BuiltinSideModuleId | (string & {});
export interface SideModuleDescriptor {
/** Artifact base name: the glue is `<file>.js`, the binary `<file>.wasm`. */
@@ -32,7 +51,7 @@ export interface SideModuleDescriptor {
globalName?: string;
}
-export const SIDE_MODULES: Record<SideModuleId, SideModuleDescriptor> = {
+export const SIDE_MODULES: Record<BuiltinSideModuleId, SideModuleDescriptor> = {
physics: { file: 'physics' },
// Basis Universal KTX2 transcoder — compressed textures decode to a
// GPU format on demand. MODULARIZE glue with a named EXPORT_NAME, like spine.
@@ -56,3 +75,40 @@ export const SPINE_VERSIONS: readonly SpineVersion[] = ['2.1', '3.8', '4.1', '4.
export function spineModuleId(version: SpineVersion): SideModuleId {
return `spine:${version}`;
}
+
+/** Modules a project supplied, keyed by id. Separate from the built-in table so
+ * a project can never redefine `physics` out from under the engine. */
+const projectModules = new Map<string, SideModuleDescriptor>();
+
+/**
+ * Declare a module the engine did not build.
+ *
+ * Called by the runtime from the packaged game's config (which the export writes
+ * from `.esengine/modules/`), so a game never registers by hand — but it is
+ * public, because a host embedding the engine may know its modules some other
+ * way. Registering an id the engine owns is refused: `physics` meaning two
+ * different binaries depending on load order is not a capability.
+ */
+export function registerSideModule(id: string, descriptor: SideModuleDescriptor): void {
+ if (id in SIDE_MODULES) {
+ log.warn('sidemodule', `ignoring a project module named "${id}" — that id belongs to the engine`);
+ return;
+ }
+ projectModules.set(id, descriptor);
+}
+
+/** How every transport and the exporters resolve an id. Built-ins win. */
+export function sideModuleDescriptor(id: SideModuleId): SideModuleDescriptor | undefined {
+ return SIDE_MODULES[id as BuiltinSideModuleId] ?? projectModules.get(id);
+}
+
+/** The ids a project declared — what an editor or a diagnostic lists. */
+export function projectSideModuleIds(): string[] {
+ return [...projectModules.keys()];
+}
+
+/** Drop every project-declared module. Realm teardown: a reloaded play session
+ * must not inherit the previous project's modules. */
+export function clearProjectSideModules(): void {
+ projectModules.clear();
+}
diff --git a/sdk/tests/side-module-registry.test.ts b/sdk/tests/side-module-registry.test.ts
new file mode 100644
index 000000000..49820645e
--- /dev/null
+++ b/sdk/tests/side-module-registry.test.ts
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Side-module identity, now that a project can name its own.
+ *
+ * The id used to be a closed union, so "unknown id" was unreachable and the host
+ * returned null for it in silence. Opening the type makes that reachable — a
+ * typo, a module the export did not stage — and silence is how either becomes
+ * "this runtime just doesn't work on my phone" with nothing in the log.
+ */
+import { describe, it, expect, afterEach, vi } from 'vitest';
+import {
+ registerSideModule, sideModuleDescriptor, projectSideModuleIds, clearProjectSideModules,
+ createSideModuleHost, SIDE_MODULES,
+} from '../src/sideModules';
+import { registerPackagedSideModules } from '../src/runtime/packagedRuntime';
+
+afterEach(() => {
+ clearProjectSideModules();
+ vi.restoreAllMocks();
+});
+
+describe('identity', () => {
+ it('resolves a project module by id, like a built-in', () => {
+ registerSideModule('rive', { file: 'rive', globalName: 'RiveModule' });
+ expect(sideModuleDescriptor('rive')).toEqual({ file: 'rive', globalName: 'RiveModule' });
+ expect(sideModuleDescriptor('physics')).toEqual(SIDE_MODULES.physics);
+ expect(projectSideModuleIds()).toEqual(['rive']);
+ });
+
+ it('refuses to let a project redefine an engine module', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ registerSideModule('physics', { file: 'not-physics' });
+ expect(sideModuleDescriptor('physics')).toEqual(SIDE_MODULES.physics);
+ expect(warn).toHaveBeenCalled();
+ // `physics` meaning two different binaries depending on load order is not
+ // a capability, so this is refused rather than last-wins.
+ expect(projectSideModuleIds()).toEqual([]);
+ });
+
+ it('forgets project modules on teardown, so a reloaded realm starts clean', () => {
+ registerSideModule('rive', { file: 'rive' });
+ clearProjectSideModules();
+ expect(sideModuleDescriptor('rive')).toBeUndefined();
+ expect(sideModuleDescriptor('basis')).toBeDefined();
+ });
+});
+
+describe('acquisition', () => {
+ it('hands the registered descriptor to the transport', async () => {
+ registerSideModule('rive', { file: 'rive_runtime', globalName: 'RiveModule' });
+ const seen: Array<{ file: string; id: string }> = [];
+ const host = createSideModuleHost(async (descriptor, id) => {
+ seen.push({ file: descriptor.file, id });
+ return {} as never;
+ });
+ await host.acquire('rive');
+ expect(seen).toEqual([{ file: 'rive_runtime', id: 'rive' }]);
+ });
+
+ it('says something about an id nobody registered', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const host = createSideModuleHost(async () => ({} as never));
+ expect(await host.acquire('rvie')).toBeNull();
+ expect(warn.mock.calls.flat().join(' ')).toContain('rvie');
+ });
+
+ it('caches per id, including the null — a missing artifact is not refetched every frame', async () => {
+ let calls = 0;
+ registerSideModule('rive', { file: 'rive' });
+ const host = createSideModuleHost(async () => { calls++; throw new Error('404'); });
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ expect(await host.acquire('rive')).toBeNull();
+ expect(await host.acquire('rive')).toBeNull();
+ expect(calls).toBe(1);
+ expect(error).toHaveBeenCalled();
+ });
+
+ it('points a failed project module at the project, not at a build command that does not exist', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ registerSideModule('rive', { file: 'rive' });
+ const host = createSideModuleHost(async () => { throw new Error('404'); });
+ await host.acquire('rive');
+ const said = error.mock.calls.flat().join(' ');
+ expect(said).toContain('.esengine/modules/rive/');
+ expect(said).not.toContain('build -t');
+ });
+
+ it('still tells an engine module how to be built', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const host = createSideModuleHost(async () => { throw new Error('404'); });
+ await host.acquire('spine:4.2');
+ expect(error.mock.calls.flat().join(' ')).toContain('build -t spine');
+ });
+});
+
+describe('the packaged declaration', () => {
+ it('registers what the export staged', () => {
+ registerPackagedSideModules({
+ sideModules: [{ id: 'rive', file: 'rive', globalName: 'RiveModule' }, { id: 'lottie', file: 'lottie' }],
+ });
+ expect(sideModuleDescriptor('rive')).toEqual({ file: 'rive', globalName: 'RiveModule' });
+ expect(sideModuleDescriptor('lottie')).toEqual({ file: 'lottie' });
+ });
+
+ it('is a no-op for a build that declared none', () => {
+ registerPackagedSideModules({});
+ expect(projectSideModuleIds()).toEqual([]);
+ });
+
+ it('skips a malformed entry rather than registering a module with no artifact', () => {
+ registerPackagedSideModules({
+ sideModules: [{ id: '', file: 'x' }, { id: 'y', file: '' }] as never,
+ });
+ expect(projectSideModuleIds()).toEqual([]);
+ });
+});