Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(pipeline): a package that cannot load its own code says so

esenginef15928f39a4e
diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.ts
index d17a4c6d5..082266a5d 100644
--- a/pipeline/src/export/exportGame.ts
+++ b/pipeline/src/export/exportGame.ts
@@ -660,6 +660,9 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
errors.push(`cook manifest: ${err instanceof Error ? err.message : String(err)}`);
}
+ /** What the host must import, or null when this build has no project code. */
+ let scriptsFile: string | null = null;
+
// Also emit the AddressableManifest (v2.0) beside the flat one — the SAME
// model every target now shares, so `loadGroup` / remote-group / hot-update
// work on web + desktop too (not just mini-games). Additive: the eager boot
@@ -695,6 +698,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
// where `esengine` is the globalThis.ESEngine the host installed.
const scriptsAbs = opts.scriptsEntry ? path.join(opts.root, opts.scriptsEntry) : null;
if (scriptsAbs && existsSync(scriptsAbs)) {
+ scriptsFile = nativeContent ? 'scripts.js' : 'scripts.mjs';
progress({ phase: 'Bundling project scripts' });
const proj = nativeContent
? await build({
@@ -801,6 +805,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
// spelled differently here — the two sides share one declaration.
const gameConfig: PackagedGameConfig = {
entryScene: opts.entryScene, scenes,
+ ...(scriptsFile ? { scripts: scriptsFile } : {}),
...packagedRuntimeFields(runtime),
...(hotUpdate ? { hotUpdate } : {}),
...(sideModuleDeclarations(projectModules, platform).length > 0
diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.ts
index b53793e27..373dd1123 100644
--- a/pipeline/src/runtime/gameHost.ts
+++ b/pipeline/src/runtime/gameHost.ts
@@ -36,15 +36,26 @@ async function boot(): Promise<void> {
window.addEventListener('resize', resize);
resize();
- // Register the project's own components/systems first (side-effect import; its
- // `import 'esengine'` resolves through the page import map to the shared SDK).
- try {
- await import(/* @vite-ignore */ new URL('./scripts.mjs', import.meta.url).href);
- } catch {
- /* no project bundle — builtin-only */
- }
-
const cfg = (await (await fetch('./game.config.json')).json()) as PackagedGameConfig;
+
+ // The project's own components and systems. The config SAYS whether this build
+ // has any, so a load failure is a failure rather than a build that turned out
+ // not to have scripts — catching the difference boots an empty world.
+ if (cfg.scripts) {
+ const url = new URL(`./${cfg.scripts}`, import.meta.url).href;
+ try {
+ await import(/* @vite-ignore */ url);
+ } catch (err) {
+ const cause = err instanceof Error ? err : new Error(String(err));
+ // Logged as well as thrown: a rejected boot is observable to automation
+ // through either, and only one of them survives a host that awaits this.
+ console.error(`[estella] project scripts failed to load (${url})`, cause);
+ throw new Error(
+ `[estella] startup failed: project scripts "${cfg.scripts}" did not load — ${cause.message}`,
+ { cause },
+ );
+ }
+ }
// 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);
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 8a7c5e9ff..231ec6171 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5318,6 +5318,7 @@ physicsEnabled: boolean | undefined
renderBackend: "webgl2" | "webgpu" | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+scripts: string | undefined
sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 187a1cb5b..c8c0eaeec 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5501,6 +5501,7 @@ physicsEnabled: boolean | undefined
renderBackend: "webgl2" | "webgpu" | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+scripts: string | undefined
sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 70122b2c8..01cb063cf 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -5313,6 +5313,7 @@ physicsEnabled: boolean | undefined
renderBackend: "webgl2" | "webgpu" | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+scripts: string | undefined
sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 24c577262..cdff07604 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -5559,6 +5559,7 @@ physicsEnabled: boolean | undefined
renderBackend: "webgl2" | "webgpu" | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+scripts: string | undefined
sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 1913ca19b..8cb12419b 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -5320,6 +5320,7 @@ physicsEnabled: boolean | undefined
renderBackend: "webgl2" | "webgpu" | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
+scripts: string | undefined
sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
diff --git a/sdk/src/runtime/packagedRuntime.ts b/sdk/src/runtime/packagedRuntime.ts
index 0de2b5da2..28878eb8c 100644
--- a/sdk/src/runtime/packagedRuntime.ts
+++ b/sdk/src/runtime/packagedRuntime.ts
@@ -40,6 +40,13 @@ export interface PackagedGameConfig {
entryScene: string;
/** Every switchable scene (SceneManager name + cooked path); includes the entry. */
scenes?: Array<{ name: string; path: string }>;
+ /**
+ * The project's own bundled code, as a payload-relative file name. Absent
+ * means this build has none — which is how a host tells "no project script"
+ * from "the project script failed to load". Guessing between those with a
+ * catch runs the empty world and calls it a success.
+ */
+ scripts?: string;
/** Bitmask of render layers (0..31) that y-sort within the layer. */
ySortLayers?: number;
/** Bitmask of render layers (0..31) that resolve by real depth (2.5D). */
diff --git a/tools/check-script-failure.mjs b/tools/check-script-failure.mjs
new file mode 100644
index 000000000..bdec98054
--- /dev/null
+++ b/tools/check-script-failure.mjs
@@ -0,0 +1,131 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file check-script-failure.mjs — a packaged game does not hide its own boot.
+ *
+ * A build with no project code has nothing to import, and one whose module
+ * throws at load has something that failed. A host that cannot tell those apart
+ * boots an empty world, paints a frame and reports a healthy start — and every
+ * symptom after that points somewhere else.
+ *
+ * The package DECLARES whether it has scripts, so they are three cases. This
+ * drives a real package for each:
+ *
+ * declared and sound boots, systems run, no errors
+ * not declared boots, no import attempted, no errors
+ * declared and throwing startup fails, the original message is observable
+ *
+ * node tools/check-script-failure.mjs
+ */
+import { spawnSync } from 'node:child_process';
+import { cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { runElectron } from './lib/electronRun.mjs';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const WORK = path.join(ROOT, '.golden', 'script-failure');
+const SOURCE = path.join(ROOT, 'examples', 'hello-world');
+const LAUNCHER = path.join(ROOT, 'tools', 'launchers', 'launch-export.mjs');
+const MARKER = 'DOGFOOD_BOOT_FAILURE';
+
+const results = [];
+const check = (what, ok, detail) => {
+ results.push(ok);
+ console.log(`${ok ? '✓' : '✗'} ${what}${detail ? ` — ${detail}` : ''}`);
+};
+
+/** A copy of the fixture project, optionally with its entry made to throw. */
+function project(name, mutate) {
+ const dir = path.join(WORK, name);
+ rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ cpSync(SOURCE, dir, { recursive: true });
+ rmSync(path.join(dir, '.esengine'), { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ mutate?.(dir);
+ return dir;
+}
+
+function pack(dir, name) {
+ const out = path.join(WORK, `${name}-web`);
+ const r = spawnSync(process.execPath, [
+ path.join(ROOT, 'pipeline', 'bin', 'estella.mjs'), 'export', dir,
+ '--platform', 'web', '--out', out,
+ ], { encoding: 'utf8', cwd: ROOT });
+ if (r.status !== 0) {
+ console.error(`✗ ${name}: the package did not build`);
+ console.error((r.stderr || r.stdout || '').split('\n').slice(-6).join('\n'));
+ process.exit(1);
+ }
+ return out;
+}
+
+/** Boot it headless and report what the page said while doing so. */
+function boot(dir) {
+ const r = runElectron([
+ LAUNCHER, '--dir', dir, '--w', '480', '--h', '320',
+ '--settle', '20', '--timeout', '60000',
+ '--out', path.join(WORK, 'frame.png'),
+ ], { encoding: 'utf8', cwd: ROOT });
+ const text = `${r.stdout ?? ''}${r.stderr ?? ''}`;
+ const line = text.split('\n').find((l) => /^[✓✗] /.test(l.trim())) ?? '';
+ // No verdict line at all means the browser never ran — this machine cannot
+ // answer the question, which is neither a pass nor a failure of the claim.
+ if (!line) {
+ console.log('check-script-failure: the packaged game never started here — nothing to judge');
+ console.log((text.trim().split('\n').slice(-4).join('\n')));
+ process.exit(2);
+ }
+ return { text, ok: line.includes('✓'), errors: Number(/errors=(\d+)/.exec(line)?.[1] ?? -1) };
+}
+
+rmSync(WORK, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+mkdirSync(WORK, { recursive: true });
+
+// 1. Declared and sound.
+{
+ const out = pack(project('sound'), 'sound');
+ const cfg = JSON.parse(readFileSync(path.join(out, 'game.config.json'), 'utf8'));
+ check('a project with code declares it in the package', cfg.scripts === 'scripts.mjs',
+ `scripts ${JSON.stringify(cfg.scripts)}`);
+ const run = boot(out);
+ check('and boots clean', run.ok && run.errors === 0, `errors ${run.errors}`);
+}
+
+// 2. Not declared. The host must not go looking, and must not mind.
+{
+ const out = pack(project('none', (dir) => {
+ const file = path.join(dir, 'project.esproject');
+ const proj = JSON.parse(readFileSync(file, 'utf8'));
+ delete proj.scriptEntry;
+ delete proj.scripts;
+ writeFileSync(file, JSON.stringify(proj, null, 2));
+ rmSync(path.join(dir, 'src'), { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ }), 'none');
+ const cfg = JSON.parse(readFileSync(path.join(out, 'game.config.json'), 'utf8'));
+ check('a project with no code declares none', cfg.scripts === undefined,
+ `scripts ${JSON.stringify(cfg.scripts)}`);
+ const run = boot(out);
+ check('and boots clean without importing anything', run.ok && run.errors === 0,
+ `errors ${run.errors}`);
+}
+
+// 3. Declared and throwing. The whole point.
+{
+ const out = pack(project('throwing', (dir) => {
+ const entry = path.join(dir, 'src', 'main.ts');
+ writeFileSync(entry, `throw new Error(${JSON.stringify(MARKER)});\n${readFileSync(entry, 'utf8')}`);
+ }), 'throwing');
+ const run = boot(out);
+ check('a project whose code throws does not report a healthy boot', !run.ok && run.errors > 0,
+ `errors ${run.errors}`);
+ check('and the original message reaches the page', run.text.includes(MARKER),
+ run.text.includes(MARKER) ? MARKER : 'marker not observed');
+ check('named as a startup failure rather than a stray log',
+ /startup failed/.test(run.text), '');
+}
+
+const failed = results.filter((ok) => !ok).length;
+console.log(failed === 0
+ ? `check-script-failure: ${results.length} claim(s) — a package cannot hide a boot it did not do`
+ : `check-script-failure: ${failed} of ${results.length} claim(s) failed`);
+process.exit(failed === 0 ? 0 : 1);
diff --git a/tools/gates.mjs b/tools/gates.mjs
index aa2146364..04dabeb5e 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -249,6 +249,7 @@ export const GATES = [
// Windows deletes asynchronously: the rmdir races the unlink it just did, and
// the temp tree a test made comes back ENOTEMPTY at random. Node's retry loop
// is right there and defaults to OFF.
+ { id: 'script-failure', run: 'node tools/check-script-failure.mjs' },
{ id: 'rm-retries', run: 'node tools/check-rm-retries.mjs' },
{ id: 'examples', run: 'node build-tools/cli.js check-examples' },
{ id: 'documents', run: 'node build-tools/cli.js validate-documents' },