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(export): a web package ships the subsystems it uses

esengine4c21d4c26983
diff --git a/desktop b/desktop
index 948edb90d..c122dcab4 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 948edb90d1f1c9f1c906b888f5b294d048516a3f
+Subproject commit c122dcab4ee5ec6b477a2a1eca524691250683c0
diff --git a/docs/astro/src/content/docs/publishing/overview.mdx b/docs/astro/src/content/docs/publishing/overview.mdx
index db516a27a..21f10f7f1 100644
--- a/docs/astro/src/content/docs/publishing/overview.mdx
+++ b/docs/astro/src/content/docs/publishing/overview.mdx
@@ -344,6 +344,25 @@ That split is read from the same manifest the runtime loads, so what the report
and what the game does cannot disagree. Moving a level behind a subpackage genuinely
removes it from the main package, and the report shows it the moment you do.
+### What the engine costs
+
+A package carries the engine subsystems its project uses, and not the others. What
+counts as "uses" is evidence the export already has: a component in a scene or prefab,
+an asset extension (`.esgraph`, `.esfsm`, `.esbt`), the wasm a side-module scan finds,
+and any `esengine/*` your own scripts import.
+
+So a game with no tilemap ships no tilemap parser, and one that never opens a session
+ships no replication protocol. If you reach a subsystem from code that the content does
+not mention — building a tilemap by hand, opening a socket — import its subpath and the
+export follows you:
+
+```ts
+import { Tilemap } from 'esengine/tilemap';
+```
+
+One subsystem has no subpath yet: a project using **Video** takes the whole engine, with
+every optional subsystem in it. Nothing else changes — the API is identical either way.
+
### Limits
Where a platform publishes a limit, the build is judged against it and the meter says
diff --git a/docs/astro/src/content/docs/zh-cn/publishing/overview.mdx b/docs/astro/src/content/docs/zh-cn/publishing/overview.mdx
index a8f59c61e..bedbf213c 100644
--- a/docs/astro/src/content/docs/zh-cn/publishing/overview.mdx
+++ b/docs/astro/src/content/docs/zh-cn/publishing/overview.mdx
@@ -273,6 +273,23 @@ which a block-compressed texture must be
这个划分读自运行时加载的同一份清单,所以报告说的和游戏做的不可能对不上。把一个关卡挪进分包是真的把它移出了主包,报告在你操作后立刻反映出来。
+### 引擎本身占多少
+
+包里只带这个项目用到的引擎子系统,用不到的不带。「用到」由导出时已有的证据判定:场景或
+预制体里的组件、资产扩展名(`.esgraph`、`.esfsm`、`.esbt`)、side-module 扫描找到的 wasm,
+以及你自己脚本里 import 的 `esengine/*`。
+
+所以没有瓦片地图的游戏不会带瓦片地图解析器,从不开会话的游戏不会带复制协议。如果你是从
+代码而不是内容里用到某个子系统——手写构建 tilemap、自己开 socket——import 它的子路径,导出
+会跟着走:
+
+```ts
+import { Tilemap } from 'esengine/tilemap';
+```
+
+只有一个子系统暂时没有子路径:用到 **Video** 的项目会拿整份引擎,包含全部可选子系统。其他
+什么都不变——两种情况下 API 完全一样。
+
### 上限
凡是平台公布了上限的目标,构建都会被对照判定,并且会说明是哪一条、数字从哪来——原文引用,好让你去核对该平台当前的文档,而不是相信我们:
diff --git a/pipeline/src/bundle/engineInstalls.ts b/pipeline/src/bundle/engineInstalls.ts
new file mode 100644
index 000000000..2301fd61b
--- /dev/null
+++ b/pipeline/src/bundle/engineInstalls.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Which engine modules a package installs — the one answer both exports use.
+ *
+ * A lean entry carries no optional subsystem; a package gets each one back by
+ * importing its subpath. What a project needs is evidence, collected from four
+ * places because a subsystem leaves its trace in whichever of them fits it:
+ * a component in a scene, an asset extension, a wasm side module, or an import
+ * the game's own scripts wrote.
+ *
+ * The mini-game export and the web export ask the same question and must not
+ * answer it differently — a subsystem installed on one target and silently
+ * missing on the other is the packaging bug that only a boot reveals.
+ *
+ * Node-free: the web export calls it mid-bundle and the mini-game export before
+ * one, and neither wants a second copy of this table.
+ */
+import { SUBSYSTEM_INSTALL, type Subsystem } from '../project/targetSupport';
+import { ESENGINE_SUBPATHS } from './esengineResolve';
+
+/** A subsystem a document names by ASSET rather than by component: nothing in a
+ * scene says "script graph", the `.esgraph` it references does. */
+const ASSET_SUBPATH: Readonly<Record<string, string>> = {
+ '.esgraph': 'esengine/logic',
+ '.esfsm': 'esengine/ai',
+ '.esbt': 'esengine/ai',
+};
+
+/** …and the ones whose evidence is the wasm they pull in. Spine is keyed by
+ * prefix because its module id carries the runtime version. */
+const SIDE_MODULE_SUBPATH: Readonly<Record<string, string>> = {
+ physics: 'esengine/physics',
+ physics3d: 'esengine/physics3d',
+ dragonbones: 'esengine/dragonbones',
+};
+
+/** What a project's content and code say it needs. Each field is one kind of
+ * evidence; an export passes the ones it can see. */
+export interface EngineInstallEvidence {
+ /** Subsystems the cooked scenes and prefabs put in use. */
+ subsystems?: Iterable<Subsystem>;
+ /** Project-relative paths the cook included, read for their extensions. */
+ assetPaths?: Iterable<string>;
+ /** Side-module ids the wasm scan found. */
+ sideModuleIds?: Iterable<string>;
+ /** Bare `esengine/*` specifiers the game's own bundles import. */
+ scriptImports?: Iterable<string>;
+}
+
+/** What a package installs, and whether a lean entry can carry it. */
+export interface EngineInstallPlan {
+ /** True when every subsystem in use has a subpath that installs it. */
+ lean: boolean;
+ /** The subpaths to import, sorted. Empty when nothing optional is in use. */
+ subpaths: readonly string[];
+}
+
+function extensionOf(p: string): string {
+ const slash = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\'));
+ const dot = p.lastIndexOf('.');
+ return dot > slash ? p.slice(dot).toLowerCase() : '';
+}
+
+/**
+ * The engine modules this package installs. `lean` is false when something in
+ * use has no subpath to install it (video today): that project takes the whole
+ * entry, which carries everything, so the subpath list stops mattering.
+ */
+export function engineInstalls(evidence: EngineInstallEvidence): EngineInstallPlan {
+ const subpaths = new Set<string>();
+ let lean = true;
+ for (const subsystem of evidence.subsystems ?? []) {
+ const install = SUBSYSTEM_INSTALL[subsystem];
+ if (install === 'base') continue;
+ if (install === 'whole-entry') { lean = false; continue; }
+ subpaths.add(install);
+ }
+ for (const p of evidence.assetPaths ?? []) {
+ const subpath = ASSET_SUBPATH[extensionOf(p)];
+ if (subpath) subpaths.add(subpath);
+ }
+ for (const id of evidence.sideModuleIds ?? []) {
+ // Spine's module id names the runtime version it was built for.
+ const subpath = id.startsWith('spine:') ? 'esengine/spine' : SIDE_MODULE_SUBPATH[id];
+ if (subpath) subpaths.add(subpath);
+ }
+ for (const specifier of evidence.scriptImports ?? []) {
+ // A script may import a subpath no content mentions — the game opens a
+ // socket itself, or builds a tilemap in code. Its word is evidence too,
+ // and only the ones the SDK publishes are ours to stage.
+ if (specifier in ESENGINE_SUBPATHS) subpaths.add(specifier);
+ }
+ return { lean, subpaths: [...subpaths].sort() };
+}
diff --git a/pipeline/src/bundle/esengineResolve.ts b/pipeline/src/bundle/esengineResolve.ts
index 6e7083874..756c7ce87 100644
--- a/pipeline/src/bundle/esengineResolve.ts
+++ b/pipeline/src/bundle/esengineResolve.ts
@@ -7,7 +7,7 @@
*
* EXTERNAL (web / desktop) — esengine stays external, resolved at runtime
* by the page import map. The runtime side of this map lives in
- * buildPlayRealm.IMPORT_MAP; keep the subpath set there in sync.
+ * the export's import map; both read the table below.
* ALIASED + INLINED (wechat / playable) — no import map, so the bundle
* inlines the SDK; esbuild `alias` points esengine (+ subpaths) at dist.
*/
diff --git a/pipeline/src/bundle/importMap.ts b/pipeline/src/bundle/importMap.ts
index 2bda4eab6..b0e09d8f0 100644
--- a/pipeline/src/bundle/importMap.ts
+++ b/pipeline/src/bundle/importMap.ts
@@ -8,6 +8,12 @@
* Subpath exports are listed file by file: an import map does not append
* `/index.js` for a directory. The list is esengineResolve's, so the two
* strategies cannot name different subpaths.
+ *
+ * A shipped game gets the map for what IT installs, not for everything
+ * the engine has: the map is what the export derives its payload from, so
+ * a page that cannot reach a subsystem is also a package that does not
+ * carry it. The editor's play realm authors every subsystem and takes the
+ * whole map.
*/
import { createHash } from 'node:crypto';
import { ESENGINE_SUBPATHS } from './esengineResolve';
@@ -15,17 +21,49 @@ import { ESENGINE_SUBPATHS } from './esengineResolve';
/** Where the exporter stages the SDK, relative to the page. */
const STAGED = './sdk/';
-export const IMPORT_MAP = {
- imports: {
- esengine: `${STAGED}index.js`,
- ...Object.fromEntries(
- Object.entries(ESENGINE_SUBPATHS).map(([specifier, rel]) => [specifier, STAGED + rel]),
- ),
- } as Record<string, string>,
-};
+/** The engine entry a lean package aliases `esengine` to. */
+export const LEAN_ENTRY_FILE = 'index.lean.js';
+/** …and the one that carries every optional subsystem. */
+export const FULL_ENTRY_FILE = 'index.js';
-export const IMPORT_MAP_JSON = JSON.stringify(IMPORT_MAP);
+/** An import map, and what a page needs to carry it under a CSP. */
+export interface EngineImportMap {
+ imports: Record<string, string>;
+ json: string;
+ /** The inline `<script type=importmap>` is an inline script, so a page's CSP
+ * has to allow it by hash rather than by `unsafe-inline`. */
+ cspHash: string;
+ /** The entry bundles in sdk/dist this map names, relative to `dist`. */
+ entries: string[];
+}
-/** The inline `<script type=importmap>` is an inline script, so a page's CSP has
- * to allow it by hash rather than by `unsafe-inline`. */
-export const IMPORT_MAP_CSP_HASH = `sha256-${createHash('sha256').update(IMPORT_MAP_JSON).digest('base64')}`;
+function finish(imports: Record<string, string>): EngineImportMap {
+ const json = JSON.stringify({ imports });
+ return {
+ imports,
+ json,
+ cspHash: `sha256-${createHash('sha256').update(json).digest('base64')}`,
+ entries: Object.values(imports).map((t) => t.replace(/^\.\/sdk\//, '')),
+ };
+}
+
+/**
+ * The map for a package that installs `subpaths` on `entry`. `esengine/wasm` is
+ * always named: the runtime loads the engine module through it on every target.
+ */
+export function engineImportMap(entry: string, subpaths: Iterable<string>): EngineImportMap {
+ const imports: Record<string, string> = { esengine: STAGED + entry };
+ for (const specifier of ['esengine/wasm', ...subpaths]) {
+ const rel = ESENGINE_SUBPATHS[specifier];
+ if (rel) imports[specifier] = STAGED + rel;
+ }
+ return finish(imports);
+}
+
+/** Every subsystem the engine has, for a realm that authors all of them. */
+export const FULL_IMPORT_MAP: EngineImportMap = finish({
+ esengine: STAGED + FULL_ENTRY_FILE,
+ ...Object.fromEntries(
+ Object.entries(ESENGINE_SUBPATHS).map(([specifier, rel]) => [specifier, STAGED + rel]),
+ ),
+});
diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.ts
index 3ea63018c..cb8ff3165 100644
--- a/pipeline/src/export/exportGame.ts
+++ b/pipeline/src/export/exportGame.ts
@@ -33,7 +33,8 @@ import type { PackagedGameConfig } from 'esengine';
import {
DEFAULT_RUNTIME_CONFIG, packagedRuntimeFields, type RuntimeProjectConfig,
} from '../project/runtimeConfig';
-import { IMPORT_MAP, IMPORT_MAP_JSON, IMPORT_MAP_CSP_HASH } from '../bundle/importMap';
+import { engineImportMap, FULL_IMPORT_MAP, LEAN_ENTRY_FILE, FULL_ENTRY_FILE, type EngineImportMap } from '../bundle/importMap';
+import { engineInstalls, type EngineInstallPlan } from '../bundle/engineInstalls';
import { exportMiniGame } from './exportMiniGame';
import { wechatExportProfile, douyinExportProfile } from './miniGameExportProfile';
import type { MiniGameExportProfile } from './miniGameExportProfile';
@@ -46,7 +47,7 @@ const BUILTIN_MINIGAME_PROFILES: Readonly<Record<string, MiniGameExportProfile>>
import { exportPlayable } from './exportPlayable';
import { genericPlayableProfile, type PlayableAdProfile } from './playableAdProfile';
import type { OnExportProgress } from './exportProgress';
-import { ESENGINE_EXTERNAL } from '../bundle/esengineResolve';
+import { ESENGINE_EXTERNAL, ESENGINE_SUBPATHS } from '../bundle/esengineResolve';
import { buildCompiledSystems, type BuildMode } from '../bundle/buildCompiledSystems';
import { resolveEmcc, runEmcc } from '../bundle/emccPath';
import { findHostCC } from '../../../compiler/src/hostCC';
@@ -143,25 +144,16 @@ export async function discoverProjectScenes(root: string, entryScene: string, sc
return scenes;
}
-/**
- * Entry bundles in sdk/dist a BROWSER page can load, derived from the map that
- * names them — `dist` holds every target's output side by side.
- *
- * Derived, not enumerated: a listed set went stale the first time an entry was
- * added, and a web package shipped a WeChat SDK.
- */
-const BROWSER_ENTRIES = Object.values(IMPORT_MAP.imports).map((t) => t.replace(/^\.\/sdk\//, ''));
-
/** The build's own record of which chunks each entry reaches (sdk/rolldown.config.js). */
const CHUNK_MANIFEST = 'chunks.json';
/**
- * The files a browser package needs out of sdk/dist: the entries the import map
- * names, plus the chunks the SDK build says those entries reach. Eleven entries
- * share one chunk graph, and a `dist` can still hold an earlier build's output —
- * a directory copy ships both (412KB of dead chunks the day this was written).
+ * The files a browser package needs out of sdk/dist: the entries ITS import map
+ * names, plus the chunks the SDK build says those reach. Derived from the map,
+ * never enumerated: a listed set went stale the first time an entry was added,
+ * and a web package shipped a WeChat SDK's chunks.
*/
-function browserPayload(sdkDist: string): Set<string> {
+function browserPayload(sdkDist: string, entries: readonly string[]): Set<string> {
const manifest = path.join(sdkDist, CHUNK_MANIFEST);
if (!existsSync(manifest)) {
// Loud, because the quiet alternative is shipping every target's runtime.
@@ -169,7 +161,7 @@ function browserPayload(sdkDist: string): Set<string> {
}
const reach = JSON.parse(readFileSync(manifest, 'utf8')) as Record<string, readonly string[]>;
const want = new Set<string>();
- for (const entry of BROWSER_ENTRIES) {
+ for (const entry of entries) {
want.add(entry);
for (const chunk of reach[entry] ?? []) want.add(chunk);
}
@@ -181,8 +173,12 @@ function browserPayload(sdkDist: string): Set<string> {
* `sourceMaps` on or off — the maps a package carries are one decision and not
* one per producer. Declarations never ship: nothing at runtime reads a `.d.ts`.
*/
-export function shipsToBrowser(sourceMaps: boolean, sdkDist?: string): (src: string) => boolean {
- const want = sdkDist ? browserPayload(sdkDist) : undefined;
+export function shipsToBrowser(
+ sourceMaps: boolean,
+ sdkDist?: string,
+ entries: readonly string[] = FULL_IMPORT_MAP.entries,
+): (src: string) => boolean {
+ const want = sdkDist ? browserPayload(sdkDist, entries) : undefined;
const root = sdkDist ? path.resolve(sdkDist) : undefined;
return (src: string) => {
const base = path.basename(src);
@@ -274,6 +270,22 @@ export interface ExportGameResult {
size?: BuildSizeReport;
}
+/**
+ * The bare `esengine/*` specifiers a bundle left for the import map to resolve.
+ * The game host and a project's own scripts may each reach a subsystem no scene
+ * mentions — a game that opens a socket in code, or builds a tilemap by hand.
+ */
+function externalEngineImports(metafile: { outputs: Record<string, { imports?: { path: string; external?: boolean }[] }> } | undefined): string[] {
+ if (!metafile) return [];
+ const found = new Set<string>();
+ for (const out of Object.values(metafile.outputs)) {
+ for (const imp of out.imports ?? []) {
+ if (imp.external && imp.path.startsWith('esengine/')) found.add(imp.path);
+ }
+ }
+ return [...found];
+}
+
/** The page's ground, and what the start screen fades out over: the same colour on
* both sides, or the fade flashes through to white between them. */
const PAGE_BACKGROUND = '#0e121b';
@@ -281,9 +293,9 @@ const PAGE_BACKGROUND = '#0e121b';
/** The web host page. `orientation` pins the canvas to a screen orientation (rotate-
* to-fit overlay + best-effort lock) — set for the mobile-facing web target, omitted
* for desktop (the Electron shell sizes its own window). */
-function indexHtml(title: string, orientation?: ScreenOrientation): string {
+function indexHtml(title: string, map: EngineImportMap, orientation?: ScreenOrientation): string {
// Every inline script on this page needs its hash listed, or the browser blocks it.
- const inlineScripts = [IMPORT_MAP_CSP_HASH, ...(orientation ? [orientationLockCspHash(orientation)] : [])]
+ const inlineScripts = [map.cspHash, ...(orientation ? [orientationLockCspHash(orientation)] : [])]
.map((h) => `'${h}'`)
.join(' ');
return `<!doctype html>
@@ -296,7 +308,7 @@ function indexHtml(title: string, orientation?: ScreenOrientation): string {
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>${title}</title>
- <script type="importmap">${IMPORT_MAP_JSON}</script>
+ <script type="importmap">${map.json}</script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { width: 100%; height: 100%; overflow: hidden; background: ${PAGE_BACKGROUND}; }
@@ -724,6 +736,9 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
sourcemap: sourceMaps,
write: true,
logLevel: 'silent',
+ // A package installs the subpaths its own scripts import, and esbuild
+ // already knows which bare specifiers it left external.
+ metafile: true,
};
// 1. Cook reachable assets + manifest, from EVERY shippable scene as a root
@@ -761,6 +776,8 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
/** What the host must import, or null when this build has no project code. */
let scriptsFile: string | null = null;
+ /** The `esengine/*` specifiers the bundles above left for the import map. */
+ const scriptImports = new Set<string>();
// Also emit the AddressableManifest (v2.0) beside the flat one — the SAME
// model every target now shares, so `loadGroup` / remote-group / hot-update
@@ -788,19 +805,22 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
? { ...(remoteRoot ? { remoteRoot } : {}), ...(persistUpdateKey ? { persistUpdateKey } : {}) }
: undefined;
+ // What wasm this project's content pulls in — evidence for the plan below, and
+ // the filter the runtime tree is copied through further down.
+ const sideModuleIds = !nativeContent && existsSync(opts.wasmDir)
+ ? await scanSideModuleIds({
+ root: opts.root, includedPaths: cook.includedPaths, cookEntries,
+ stagedDir: payloadDir, physicsEnabled: runtime.physicsEnabled,
+ })
+ : [];
+ /** The subpaths this package installs, and whether a lean entry can carry it.
+ * Set on the browser path once the project's own imports are known. */
+ let plan: EngineInstallPlan = { lean: false, subpaths: [] };
try {
- // 2. Game host — esengine EXTERNAL (resolved by the index.html import map),
- // so the shipped game shares one SDK with the project bundle and runs
- // custom systems (same shape as the play realm).
const { build } = await loadEsbuild();
- if (!nativeContent) {
- progress({ phase: 'Bundling game host' });
- const host = await build({ ...common, entryPoints: [runtimeHostEntry(opts.hostsDir, 'gameHost')], outfile: path.join(payloadDir, 'game.js') });
- errors.push(...explainBundleErrors(host.errors));
- }
- // 3. Project bundle (defineComponent/defineSystem). ESM + esengine external on
- // the web (the import map resolves it); on native an IIFE the host evals,
- // where `esengine` is the globalThis.ESEngine the host installed.
+ // 2. Project bundle (defineComponent/defineSystem). ESM with `esengine`
+ // external on the web; on native an IIFE the host evals. Before the host,
+ // because what it imports is evidence for the plan below.
const scriptsAbs = opts.scriptsEntry ? path.join(opts.root, opts.scriptsEntry) : null;
if (scriptsAbs && existsSync(scriptsAbs)) {
scriptsFile = nativeContent ? 'scripts.js' : 'scripts.mjs';
@@ -812,6 +832,35 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
})
: await build({ ...common, entryPoints: [scriptsAbs], outfile: path.join(payloadDir, 'scripts.mjs') });
errors.push(...explainBundleErrors(proj.errors));
+ for (const spec of externalEngineImports(proj.metafile)) scriptImports.add(spec);
+ }
+ // 3. Game host — esengine EXTERNAL (resolved by the index.html import map),
+ // so the shipped game shares one SDK with the project bundle and runs
+ // custom systems (same shape as the play realm).
+ if (!nativeContent) {
+ plan = engineInstalls({
+ subsystems: (await contentSubsystems(opts.root, cook.includedPaths)).keys(),
+ assetPaths: cook.includedPaths,
+ sideModuleIds,
+ scriptImports,
+ });
+ progress({ phase: 'Bundling game host' });
+ // An entry that IMPORTS what this package installs, then the host. Staging
+ // a subpath only lets the page resolve it; a subsystem is installed by
+ // something importing it, and on a lean entry nothing else does.
+ const hostEntry = runtimeHostEntry(opts.hostsDir, 'gameHost');
+ const host = await build({
+ ...common,
+ stdin: {
+ contents: plan.subpaths.map((m) => `import ${JSON.stringify(m)};\n`).join('')
+ + `import ${JSON.stringify(hostEntry)};\n`,
+ resolveDir: path.dirname(hostEntry),
+ loader: 'js',
+ sourcefile: 'game-entry.js',
+ },
+ outfile: path.join(payloadDir, 'game.js'),
+ });
+ errors.push(...explainBundleErrors(host.errors));
}
} catch (err) {
@@ -863,24 +912,28 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
}
}
- // 4. SDK (import-map target) + wasm runtime. The import map and the game
- // host reference both unconditionally — a missing tree is not a degraded
- // export but a package that cannot boot, so it fails the export.
- // Filtered, because sdk/dist holds every platform's build side by side.
+ // 4. SDK (import-map target) + wasm runtime. A missing tree fails the export
+ // rather than degrading it. What ships is derived from THIS package's
+ // import map: a game with no tilemap ships no tilemap.
+ let engineMap = FULL_IMPORT_MAP;
if (!nativeContent) {
+ // Only when the SDK build actually produced one: a tree without it (an older
+ // dist, a test fixture) falls back to the whole entry rather than pointing
+ // `esengine` at a file that is not there.
+ const hasLean = existsSync(path.join(opts.sdkDistDir, LEAN_ENTRY_FILE));
+ engineMap = plan.lean && hasLean
+ ? engineImportMap(LEAN_ENTRY_FILE, plan.subpaths)
+ : engineImportMap(FULL_ENTRY_FILE, Object.keys(ESENGINE_SUBPATHS));
+
progress({ phase: 'Copying SDK + runtime' });
if (existsSync(opts.sdkDistDir)) {
await cp(opts.sdkDistDir, path.join(payloadDir, 'sdk'), {
- recursive: true, filter: shipsToBrowser(sourceMaps, opts.sdkDistDir),
+ recursive: true, filter: shipsToBrowser(sourceMaps, opts.sdkDistDir, engineMap.entries),
});
if (!sourceMaps) await dropSourceMapRefs(path.join(payloadDir, 'sdk'));
} else errors.push(`sdk dist not found: ${opts.sdkDistDir}`);
if (existsSync(opts.wasmDir)) {
- const ids = await scanSideModuleIds({
- root: opts.root, includedPaths: cook.includedPaths, cookEntries,
- stagedDir: payloadDir, physicsEnabled: runtime.physicsEnabled,
- });
- const { files, unknown } = sideModuleFiles(ids);
+ const { files, unknown } = sideModuleFiles(sideModuleIds);
for (const id of unknown) errors.push(`internal: no artifact mapping for side module "${id}"`);
for (const { id, file } of files) {
if (!existsSync(path.join(opts.wasmDir, `${file}.js`))) {
@@ -904,7 +957,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
// reports work nothing did.
if (!nativeContent) {
progress({ phase: 'Writing host page' });
- await writeFile(path.join(payloadDir, 'index.html'), indexHtml(title, platform === 'web' ? orientation : undefined));
+ await writeFile(path.join(payloadDir, 'index.html'), indexHtml(title, engineMap, platform === 'web' ? orientation : undefined));
}
// Typed against the SDK's contract, so a field the runtimes read can never be
// spelled differently here — the two sides share one declaration.
diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.ts
index 23996d213..c54c5cb09 100644
--- a/pipeline/src/export/exportMiniGame.ts
+++ b/pipeline/src/export/exportMiniGame.ts
@@ -52,7 +52,7 @@ import { buildCompiledSystems, type BuildMode } from '../bundle/buildCompiledSys
import { resolveEmcc, runEmcc } from '../bundle/emccPath';
import type { MiniGameExportProfile, MiniGameVendor } from './miniGameExportProfile';
import { contentSubsystems } from './contentSubsystems';
-import type { Subsystem } from '../project/targetSupport';
+import { engineInstalls } from '../bundle/engineInstalls';
@@ -454,45 +454,23 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
await cp(built.modulePath, path.join(absOut, 'aot', 'systems.wasm'));
aotArg = `, aot: ${JSON.stringify({ module: 'aot/systems.wasm', manifest: built.manifest })}`;
}
- // The scan's answer for wasm side modules, asked of their JS: the lean entry
- // plus the subpaths that install what this project uses. Video has no subpath,
- // so a project with video takes the whole entry.
- const OPTIONAL_SUBPATH: Record<string, string> = {
- physics: 'esengine/physics',
- physics3d: 'esengine/physics3d',
- dragonbones: 'esengine/dragonbones',
- };
- // A subsystem with no wasm of its own leaves no trace in the side-module scan,
- // so its evidence is the content: a scene holding a Tilemap is what says the
- // package needs the tilemap subpath.
- const CONTENT_SUBPATH: Partial<Record<Subsystem, string>> = {
- tilemap: 'esengine/tilemap',
- ai: 'esengine/ai',
- replication: 'esengine/replication',
- };
- /** …and the ones a document names by asset rather than by component. */
- const ASSET_SUBPATH: Readonly<Record<string, string>> = {
- '.esgraph': 'esengine/logic',
- '.esfsm': 'esengine/ai',
- '.esbt': 'esengine/ai',
- };
+ // What this project installs on a lean entry — the same answer the web export
+ // gets, from the same evidence, so a subsystem cannot be installed on one
+ // target and silently missing on the other.
const usedSubsystems = await contentSubsystems(opts.root, cook.includedPaths);
- const needed = new Set(sideModules.map((m) => m.id));
- const wantsVideo = needed.has('videodec');
+ const plan = engineInstalls({
+ subsystems: usedSubsystems.keys(),
+ assetPaths: cook.includedPaths,
+ sideModuleIds: sideModules.map((m) => m.id),
+ });
// Only when the SDK build actually produced one: a tree without it (an older
// dist, a test fixture) must fall back to the whole entry rather than alias
// `esengine` to a file that is not there.
const leanEntry = profile.sdkLeanEntryFile
&& existsSync(path.join(opts.sdkDir, profile.sdkLeanEntryFile))
? profile.sdkLeanEntryFile : null;
- const lean = !!leanEntry && !wantsVideo;
- const installs = lean
- ? [...new Set([
- ...[...needed].map((id) => (id.startsWith('spine:') ? 'esengine/spine' : OPTIONAL_SUBPATH[id] ?? '')),
- ...[...usedSubsystems.keys()].map((s) => CONTENT_SUBPATH[s] ?? ''),
- ...cook.includedPaths.map((p) => ASSET_SUBPATH[path.extname(p).toLowerCase()] ?? ''),
- ].filter(Boolean))].sort()
- : [];
+ const lean = !!leanEntry && plan.lean;
+ const installs = lean ? plan.subpaths : [];
const entrySrc =
installs.map((m) => `import ${JSON.stringify(m)};\n`).join('') +
diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.ts
index b9d339aec..8188fb9f7 100644
--- a/pipeline/src/project/targetSupport.ts
+++ b/pipeline/src/project/targetSupport.ts
@@ -66,6 +66,24 @@ export const SUBSYSTEM_LABEL: Readonly<Record<Subsystem, string>> = {
replication: 'Replication',
};
+/**
+ * What a package on a LEAN entry does to get this subsystem back: import the
+ * named specifier, nothing (`base`), or take the whole entry (`whole-entry` —
+ * no subpath installs it yet). Beside the components that put each subsystem in
+ * use, so adding one cannot leave the packaging question unanswered.
+ */
+export const SUBSYSTEM_INSTALL: Readonly<Record<Subsystem, string>> = {
+ text: 'base',
+ particles: 'base',
+ postprocess: 'base',
+ tilemap: 'esengine/tilemap',
+ physics: 'esengine/physics',
+ spine: 'esengine/spine',
+ video: 'whole-entry',
+ ai: 'esengine/ai',
+ replication: 'esengine/replication',
+};
+
/**
* The cmake option whose absence drops a subsystem from a build of the engine
* core (see `cmake/ESEngineSources.cmake`). The others ship as separate modules
diff --git a/pipeline/tests/engine-installs.test.ts b/pipeline/tests/engine-installs.test.ts
new file mode 100644
index 000000000..02c6232d7
--- /dev/null
+++ b/pipeline/tests/engine-installs.test.ts
@@ -0,0 +1,97 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a package installs on a lean engine entry.
+ *
+ * The failure this guards is silent by construction: a package whose page can
+ * resolve a subsystem but whose code never imports it boots, draws, and is
+ * simply missing physics. No test of the engine sees it, because the engine is
+ * fine — it was never installed.
+ */
+import { describe, it, expect } from 'vitest';
+import { engineInstalls } from '../src/bundle/engineInstalls';
+import { ESENGINE_SUBPATHS } from '../src/bundle/esengineResolve';
+import { SUBSYSTEM_INSTALL, type Subsystem } from '../src/project/targetSupport';
+
+describe('the engine modules a package installs', () => {
+ it('takes a subsystem from the components its content authored', () => {
+ expect(engineInstalls({ subsystems: ['tilemap', 'ai'] }))
+ .toEqual({ lean: true, subpaths: ['esengine/ai', 'esengine/tilemap'] });
+ });
+
+ it('takes one a document names by asset rather than by component', () => {
+ // Nothing in a scene says "script graph"; the .esgraph it references does.
+ expect(engineInstalls({ assetPaths: ['assets/logic/Door.esgraph'] }).subpaths)
+ .toEqual(['esengine/logic']);
+ });
+
+ it('takes one whose evidence is the wasm it pulls in', () => {
+ expect(engineInstalls({ sideModuleIds: ['physics', 'spine:4.2'] }).subpaths)
+ .toEqual(['esengine/physics', 'esengine/spine']);
+ });
+
+ it('takes the word of the game\'s own scripts, which no content mentions', () => {
+ expect(engineInstalls({ scriptImports: ['esengine/replication'] }).subpaths)
+ .toEqual(['esengine/replication']);
+ });
+
+ it('ignores a specifier the SDK does not publish', () => {
+ expect(engineInstalls({ scriptImports: ['esengine/nope', 'lodash'] }).subpaths).toEqual([]);
+ });
+
+ it('asks for nothing when everything in use is in the base entry', () => {
+ expect(engineInstalls({ subsystems: ['text', 'particles', 'postprocess'] }))
+ .toEqual({ lean: true, subpaths: [] });
+ });
+
+ // Video has no subpath to install it, so a project with video cannot be lean
+ // — and the whole entry carries everything, which is why the list stops
+ // mattering rather than having to be completed.
+ it('gives up on a lean entry when something in use has no subpath', () => {
+ expect(engineInstalls({ subsystems: ['video', 'tilemap'] }).lean).toBe(false);
+ });
+
+ it('says nothing twice, however many kinds of evidence name it', () => {
+ expect(engineInstalls({
+ subsystems: ['ai'], assetPaths: ['a.esbt'], scriptImports: ['esengine/ai'],
+ }).subpaths).toEqual(['esengine/ai']);
+ });
+});
+
+/**
+ * A subpath nothing can point at is one a package never installs, and the
+ * symptom is a subsystem that silently does nothing in an exported game. So
+ * every published subpath owes an answer here — including the two that are not
+ * subsystems at all, which say so by name.
+ */
+describe('every subpath the SDK publishes', () => {
+ /** Not subsystems: the engine module every target loads, and a platform
+ * adapter an entry picks rather than content asking for it. */
+ const NOT_A_SUBSYSTEM = new Set(['esengine/wasm', 'esengine/douyin']);
+
+ it('is named by something a project can be evidence of', () => {
+ const installable = new Set<string>();
+ for (const install of Object.values(SUBSYSTEM_INSTALL)) {
+ if (install !== 'base' && install !== 'whole-entry') installable.add(install);
+ }
+ // The two tables engineInstalls keeps for evidence content does not carry
+ // as a component — asked through it, so this cannot read a stale copy.
+ for (const ext of ['.esgraph', '.esfsm', '.esbt']) {
+ for (const s of engineInstalls({ assetPaths: [`x${ext}`] }).subpaths) installable.add(s);
+ }
+ for (const id of ['physics', 'physics3d', 'dragonbones', 'spine:4.2']) {
+ for (const s of engineInstalls({ sideModuleIds: [id] }).subpaths) installable.add(s);
+ }
+ const orphans = Object.keys(ESENGINE_SUBPATHS)
+ .filter((s) => !NOT_A_SUBSYSTEM.has(s) && !installable.has(s));
+ expect(orphans).toEqual([]);
+ });
+
+ it('that a subsystem names is one the SDK actually publishes', () => {
+ const unpublished = (Object.entries(SUBSYSTEM_INSTALL) as [Subsystem, string][])
+ .filter(([, install]) => install !== 'base' && install !== 'whole-entry')
+ .filter(([, install]) => !(install in ESENGINE_SUBPATHS))
+ .map(([subsystem]) => subsystem);
+ expect(unpublished).toEqual([]);
+ });
+});
diff --git a/pipeline/tests/export-engine-installs.test.ts b/pipeline/tests/export-engine-installs.test.ts
new file mode 100644
index 000000000..664c9338f
--- /dev/null
+++ b/pipeline/tests/export-engine-installs.test.ts
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A web package installs the subsystems its content uses, and no others.
+ *
+ * Two halves that must stay together. Staging a subpath only lets the PAGE
+ * resolve it; a subsystem is installed by something IMPORTING it, and on a lean
+ * entry nothing else does. A package with the first half and not the second
+ * boots, draws, and is quietly missing physics — which is how it shipped the
+ * first time.
+ */
+import { describe, it, expect } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { exportGame } from '../src/export/exportGame';
+import { writeFakeSdkDist } from './fixtures/fakeSdkDist';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const HOSTS = path.join(HERE, '..', 'src', 'runtime');
+const SCN = 'cccccccc-cccc-cccc-cccc-cccccccccccc';
+
+/** The entries a real dist publishes, enough of them to tell apart. */
+const SDK_FILES = {
+ 'index.js': 'export const full = 1;\n',
+ 'index.lean.js': 'export const lean = 1;\n',
+ 'wasm.js': 'export const wasm = 1;\n',
+ 'tilemap/index.js': 'export const tilemap = 1;\n',
+ 'ai/index.js': 'export const ai = 1;\n',
+ 'net/replication/index.js': 'export const repl = 1;\n',
+ 'shared/core.js': 'export const core = 1;\n',
+};
+
+function setup(components: string[]): { root: string; out: string } {
+ const root = mkdtempSync(path.join(tmpdir(), 'estella-installs-'));
+ mkdirSync(path.join(root, 'scenes'), { recursive: true });
+ writeFileSync(path.join(root, 'scenes', 'main.esscene'), JSON.stringify({
+ version: '1.0',
+ entities: [{ name: 'Root', components: components.map((type) => ({ type })) }],
+ }));
+ writeFileSync(path.join(root, 'scenes', 'main.esscene.meta'),
+ JSON.stringify({ uuid: SCN, version: '2.0', type: 'scene', importer: {} }));
+ writeFakeSdkDist(path.join(root, '_sdk'), SDK_FILES);
+ mkdirSync(path.join(root, '_wasm'), { recursive: true });
+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');
+ writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'ENGINE');
+ writeFileSync(path.join(root, '_wasm', 'wasm.manifest.json'), JSON.stringify({ schema: 1 }));
+ return { root, out: path.join(root, 'dist') };
+}
+
+const run = (f: { root: string; out: string }) => exportGame({
+ root: f.root, entryScene: 'scenes/main.esscene', hostsDir: HOSTS,
+ sdkDistDir: path.join(f.root, '_sdk'), wasmDir: path.join(f.root, '_wasm'),
+ outDir: f.out,
+});
+
+describe('a web package built on a lean entry', () => {
+ it('imports the subsystem its content uses, not only resolves it', async () => {
+ const f = setup(['Tilemap']);
+ try {
+ const res = await run(f);
+ expect(res.errors).toEqual([]);
+ const page = readFileSync(path.join(f.out, 'index.html'), 'utf8');
+ const game = readFileSync(path.join(f.out, 'game.js'), 'utf8');
+ expect(page).toContain('"esengine":"./sdk/index.lean.js"');
+ expect(page).toContain('"esengine/tilemap":"./sdk/tilemap/index.js"');
+ // The half a page cannot show: something has to IMPORT it.
+ expect(game).toContain('import "esengine/tilemap"');
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ });
+
+ it('carries the subpath it installs and leaves the rest behind', async () => {
+ const f = setup(['Tilemap']);
+ try {
+ await run(f);
+ const sdk = path.join(f.out, 'sdk');
+ expect(existsSync(path.join(sdk, 'tilemap', 'index.js'))).toBe(true);
+ expect(existsSync(path.join(sdk, 'index.lean.js'))).toBe(true);
+ // A game with no agents and no session pays for neither.
+ expect(existsSync(path.join(sdk, 'ai', 'index.js'))).toBe(false);
+ expect(existsSync(path.join(sdk, 'net', 'replication', 'index.js'))).toBe(false);
+ expect(existsSync(path.join(sdk, 'index.js'))).toBe(false);
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ });
+
+ it('installs nothing when the content needs nothing optional', async () => {
+ const f = setup(['Transform', 'Sprite']);
+ try {
+ await run(f);
+ const page = readFileSync(path.join(f.out, 'index.html'), 'utf8');
+ expect(page).toContain('"esengine":"./sdk/index.lean.js"');
+ expect(page).not.toContain('esengine/tilemap');
+ expect(readFileSync(path.join(f.out, 'game.js'), 'utf8')).not.toContain('import "esengine/');
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ });
+
+ // Video is installed by no subpath, so the project takes the whole entry —
+ // and then the page must name every subpath, because the whole entry has
+ // already carried every subsystem into the package.
+ it('falls back to the whole entry for a subsystem no subpath installs', async () => {
+ const f = setup(['Video']);
+ try {
+ await run(f);
+ const page = readFileSync(path.join(f.out, 'index.html'), 'utf8');
+ expect(page).toContain('"esengine":"./sdk/index.js"');
+ expect(page).toContain('"esengine/ai"');
+ expect(existsSync(path.join(f.out, 'sdk', 'index.js'))).toBe(true);
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ });
+
+ // A dist from before the split has no lean entry; pointing `esengine` at a
+ // file that is not there is a package that cannot boot at all.
+ it('takes the whole entry when the SDK build produced no lean one', async () => {
+ const f = setup(['Tilemap']);
+ try {
+ rmSync(path.join(f.root, '_sdk'), { recursive: true, force: true });
+ writeFakeSdkDist(path.join(f.root, '_sdk'),
+ Object.fromEntries(Object.entries(SDK_FILES).filter(([k]) => k !== 'index.lean.js')));
+ await run(f);
+ const page = readFileSync(path.join(f.out, 'index.html'), 'utf8');
+ expect(page).toContain('"esengine":"./sdk/index.js"');
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ });
+});
diff --git a/pipeline/tests/ships-to-browser.test.ts b/pipeline/tests/ships-to-browser.test.ts
index 9b0d74bae..1a919cbda 100644
--- a/pipeline/tests/ships-to-browser.test.ts
+++ b/pipeline/tests/ships-to-browser.test.ts
@@ -14,10 +14,10 @@ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { shipsToBrowser } from '../src/export/exportGame';
-import { IMPORT_MAP } from '../src/bundle/importMap';
+import { FULL_IMPORT_MAP } from '../src/bundle/importMap';
/** The shape of a real dist, small enough to read: entries, chunks, a manifest. */
-const ENTRIES = Object.values(IMPORT_MAP.imports).map((t) => t.replace('./sdk/', ''));
+const ENTRIES = FULL_IMPORT_MAP.entries;
const OTHER_HOSTS = [
'index.node.js', 'index.wechat.js', 'index.wechat.cjs.js', 'index.wechat.lean.js',
'index.minigame.js', 'index.native.js', 'index.native.bundled.js', 'index.bundled.js',
diff --git a/sdk/package.json b/sdk/package.json
index 32a555bfc..b4c1b4b20 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -6,6 +6,7 @@
"description": "Estella SDK - A fast 2D/3D game engine for Web, WeChat MiniGames and native platforms",
"sideEffects": [
"./dist/index.js",
+ "./dist/index.lean.js",
"./dist/wasm.js",
"./dist/index.wechat.js",
"./dist/index.wechat.lean.js",
diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.js
index d6b6f6b9e..ab1e58d5d 100644
--- a/sdk/rolldown.config.js
+++ b/sdk/rolldown.config.js
@@ -2,7 +2,10 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { defineConfig } from 'rolldown';
-const ENTRY_FILES = ['/index.ts', '/index.wechat.ts', '/index.wechat.lean.ts', '/index.minigame.ts', '/index.node.ts', '/index.native.ts'];
+// An entry's body runs; every other module is pure and its top-level statements
+// may be dropped. So an entry's prologue is a CALL it makes, never a statement
+// in a module it shares — see runtime/webEntry.ts.
+const ENTRY_FILES = ['/index.ts', '/index.lean.ts', '/index.wechat.ts', '/index.wechat.lean.ts', '/index.minigame.ts', '/index.node.ts', '/index.native.ts'];
const treeshake = {
moduleSideEffects: (id) => ENTRY_FILES.some(e => id.endsWith(e)),
};
@@ -84,6 +87,7 @@ export default defineConfig([
input: {
'index': 'src/index.ts',
'index.node': 'src/index.node.ts',
+ 'index.lean': 'src/index.lean.ts',
'index.wechat': 'src/index.wechat.ts',
'index.wechat.lean': 'src/index.wechat.lean.ts',
'index.minigame': 'src/index.minigame.ts',
diff --git a/sdk/src/index.base.ts b/sdk/src/index.base.ts
new file mode 100644
index 000000000..8a19d4064
--- /dev/null
+++ b/sdk/src/index.base.ts
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.base.ts
+ * @brief ESEngine SDK - Web entry, minus the optional subsystems
+ *
+ * `index` is this plus every optional subsystem; `index.lean` is this alone,
+ * for a package that imports back the subpaths its own content uses. The
+ * prologue both run is `installWebEntry`, which they CALL: this file is not one
+ * package.json declares side-effectful, so nothing here may have an effect.
+ */
+export * from './core';
+export * from './runtime/webAppFactory';
+
+// The component schema this bundle was generated from, so an embedding host
+// can compare it against the wasm it loads (desktop EngineGuard). The fatal
+// check is still the runtime bridge handshake's.
+export { ABI_LAYOUT_HASH } from './ecs/component.generated';
diff --git a/sdk/src/index.lean.ts b/sdk/src/index.lean.ts
new file mode 100644
index 000000000..c963486fb
--- /dev/null
+++ b/sdk/src/index.lean.ts
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.lean.ts
+ * @brief ESEngine SDK - Web entry with no optional subsystems
+ *
+ * Same engine as `index`, minus Spine, DragonBones, physics, 3D physics,
+ * tilemaps, script graphs, gameplay AI, replication and video. A package built
+ * on this imports the subpaths its own content needs (`esengine/tilemap`,
+ * `esengine/physics`, …), which is what installs them.
+ *
+ * A scene that needs one nobody imported loads without it and says so: what a
+ * lean build IS, is a build that ships less.
+ */
+import { installWebEntry } from './runtime/webEntry';
+
+installWebEntry();
+
+export * from './index.base';
diff --git a/sdk/src/index.ts b/sdk/src/index.ts
index bfe712b1a..158410484 100644
--- a/sdk/src/index.ts
+++ b/sdk/src/index.ts
@@ -3,34 +3,15 @@
/**
* @file index.ts
* @brief ESEngine SDK - Web entry point (auto-initializes Web platform)
+ *
+ * The whole entry: everything in index.base plus every optional subsystem.
+ * `index.lean` is the same base with none of them, for a package that imports
+ * back only what its project uses.
*/
-
-import { setPlatform, webAdapter } from './platform';
-import { ensureBuiltinComponentsRegistered, markEngineComponentBaseline } from './ecs/component';
-import { ensureBuiltinAiRegistrations } from './ai/builtins';
-setPlatform(webAdapter);
-
-// Register every engine component (COMPONENT_META) up front so a scene can never
-// silently drop a component that exists in the engine but lacks a typed const.
-ensureBuiltinComponentsRegistered();
-// Same for the built-in AI action/condition names, so editor palettes see them
-// even in an SDK instance that never builds the FSM/BT plugins.
-ensureBuiltinAiRegistrations();
-// All engine `defineComponent`s have run by now (their modules are dependencies of
-// this entry, evaluated before this statement); snapshot them so a project hot
-// reload can't wipe them (see seedEngineComponents).
-markEngineComponentBaseline();
-
-export * from './core';
-// Installs every optional subsystem on the apps this entry builds; a lean entry
-// does not call it and ships without their code.
import { installOptionalPlugins } from './runtime/optionalPlugins';
+import { installWebEntry } from './runtime/webEntry';
installOptionalPlugins();
-export * from './runtime/webAppFactory';
+installWebEntry();
-// ABI layout hash of the component schema this SDK bundle was generated from.
-// Exposed so an embedding host (e.g. the editor) can compare it against the
-// wasm build it loads — see desktop EngineGuard. The authoritative, fatal
-// layout check still happens inside the runtime bridge handshake.
-export { ABI_LAYOUT_HASH } from './ecs/component.generated';
+export * from './index.base';
diff --git a/sdk/src/runtime/webEntry.ts b/sdk/src/runtime/webEntry.ts
new file mode 100644
index 000000000..ca5d848c4
--- /dev/null
+++ b/sdk/src/runtime/webEntry.ts
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file webEntry.ts — what every web entry does before it hands the SDK over.
+ *
+ * A CALL, not a module side effect. `sideEffects` in package.json is a list of
+ * FILES, and which file a statement ends up in is the bundler's choice: put
+ * this in a module the entries share and it lands in a chunk nobody whitelisted,
+ * where tree-shaking drops it. The editor booted to "Platform not initialized".
+ */
+import { setPlatform, webAdapter } from '../platform';
+import { ensureBuiltinComponentsRegistered, markEngineComponentBaseline } from '../ecs/component';
+import { ensureBuiltinAiRegistrations } from '../ai/builtins';
+
+/** Idempotent: an entry that re-exports another still calls it exactly once. */
+export function installWebEntry(): void {
+ setPlatform(webAdapter);
+ // Every engine component (COMPONENT_META) up front, so a scene can never
+ // silently drop one that exists in the engine but lacks a typed const.
+ ensureBuiltinComponentsRegistered();
+ // Same for the built-in AI action/condition names, so editor palettes see
+ // them even in an SDK instance that never builds the FSM/BT plugins.
+ ensureBuiltinAiRegistrations();
+ // Every engine `defineComponent` has run by now, so a project hot reload
+ // cannot wipe them.
+ markEngineComponentBaseline();
+}
diff --git a/tools/check-entries-install-options.mjs b/tools/check-entries-install-options.mjs
index e8b629ac2..d4b3a525b 100644
--- a/tools/check-entries-install-options.mjs
+++ b/tools/check-entries-install-options.mjs
@@ -39,6 +39,10 @@ const LEAN = {
+ ' subpaths its own content uses',
'index.wechat.base.ts': 'not an entry anyone builds from — the shared half of'
+ ' index.wechat and index.wechat.lean',
+ 'index.lean.ts': 'ships no optional subsystem; a web package imports back the'
+ + ' subpaths its own content uses',
+ 'index.base.ts': 'not an entry anyone builds from — the shared half of'
+ + ' index and index.lean',
};
// Two dotted segments, not one: `index.wechat.lean.ts` did not match a
diff --git a/tools/check-entry-boots.mjs b/tools/check-entry-boots.mjs
new file mode 100644
index 000000000..e4406b36f
--- /dev/null
+++ b/tools/check-entry-boots.mjs
@@ -0,0 +1,81 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file check-entry-boots.mjs — an entry still installs its platform after a
+ * bundler has been through it.
+ *
+ * `sideEffects` in package.json is a list of FILES, and which file a statement
+ * ends up in is the BUNDLER's choice. Move an entry's prologue into a module the
+ * entries share and it lands in a chunk nobody whitelisted, where tree-shaking
+ * drops it — the code is still in `dist`, so every text probe says it shipped.
+ * It has cost two boots: a lean-entry WeChat package, and the editor, which came
+ * up on "Platform not initialized".
+ *
+ * So this bundles a CONSUMER the way one really resolves the package — through
+ * node_modules, so `sideEffects` applies — and RUNS it.
+ *
+ * node tools/check-entry-boots.mjs
+ */
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const SDK = path.join(ROOT, 'sdk');
+
+/** Each entry a consumer can resolve, and the platform it must have installed. */
+const ENTRIES = [
+ { specifier: 'esengine', platform: 'web' },
+ { specifier: 'esengine/lean', file: 'dist/index.lean.js', platform: 'web' },
+];
+
+const work = mkdtempSync(path.join(tmpdir(), 'estella-entry-boots-'));
+const fail = (message, detail) => {
+ console.error(`check-entry-boots: ${message}`);
+ if (detail) console.error(String(detail).trim());
+ rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ process.exit(1);
+};
+
+if (!existsSync(path.join(SDK, 'dist', 'index.js'))) {
+ fail('no SDK build at sdk/dist — build it first (pnpm --filter ./sdk build).');
+}
+
+mkdirSync(path.join(work, 'node_modules'), { recursive: true });
+symlinkSync(SDK, path.join(work, 'node_modules', 'esengine'), 'dir');
+
+const { build } = await import('esbuild');
+const results = [];
+for (const entry of ENTRIES) {
+ const name = entry.specifier.replace(/\W+/g, '-');
+ const src = path.join(work, `${name}.mjs`);
+ const out = path.join(work, `${name}.bundle.mjs`);
+ writeFileSync(src, `import { getPlatformType } from ${JSON.stringify(entry.specifier)};\n`
+ + `console.log(getPlatformType());\n`);
+ try {
+ await build({
+ entryPoints: [src], outfile: out, bundle: true, format: 'esm',
+ platform: 'node', logLevel: 'silent',
+ // A subpath the package does not publish still has to be reachable
+ // by the file it is: this asks what the BUILD produced.
+ ...(entry.file ? { alias: { [entry.specifier]: path.join(SDK, entry.file) } } : {}),
+ });
+ } catch (err) {
+ fail(`${entry.specifier} did not bundle.`, err?.message ?? err);
+ }
+ const run = spawnSync(process.execPath, [out], { encoding: 'utf8' });
+ const got = (run.stdout ?? '').trim();
+ if (run.status !== 0) fail(`${entry.specifier} threw on import.`, run.stderr);
+ if (got !== entry.platform) {
+ fail(`${entry.specifier} installed no platform after bundling — got ${got || '(nothing)'},`
+ + ` expected ${entry.platform}.\n\nIts prologue is a statement in a module the bundler`
+ + ' put in an unlisted chunk. Make it a call the entry makes (runtime/webEntry.ts),'
+ + ' or list that file in sdk/package.json "sideEffects".');
+ }
+ results.push(`${entry.specifier} → ${got}`);
+}
+
+rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+console.log(`check-entry-boots: ${results.length} entry(ies) bundled and run — ${results.join(', ')}.`);
diff --git a/tools/gates.mjs b/tools/gates.mjs
index 78a50972a..1e2e5cb9e 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -141,6 +141,9 @@ export const GATES = [
// …and the other half: an entry that forgets to install them ships an app whose
// Spine entities silently never animate.
{ id: 'entries-install-options', run: 'node tools/check-entries-install-options.mjs' },
+ // And the half no text probe can see: `sideEffects` lists FILES, so a prologue
+ // the bundler puts in an unlisted chunk is dropped while still sitting in dist.
+ { id: 'entry-boots', run: 'node tools/check-entry-boots.mjs' },
// Replication applies its inbox in arrival order, so reliable+ordered is a
// correctness condition. This compiles the claim: a transport that does not
// make it cannot reach replication.