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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(minigame): the engine subpackage notice shows only a real percentage, stops at load, and comes down when the boot fails
yhhd48cabae896c
diff --git a/pipeline/src/export/miniGameExportProfile.ts b/pipeline/src/export/miniGameExportProfile.tsindex 87123710b..8ae0a3131 100644--- a/pipeline/src/export/miniGameExportProfile.ts+++ b/pipeline/src/export/miniGameExportProfile.ts@@ -123,16 +123,17 @@ export function defaultMiniGameEntry(ctx: MiniGameEntryContext, load = 'require'const requires = ctx.sideModules.map((m) => ` ${JSON.stringify(m.id)}: asFactory(${load}('./${ctx.runtimeDir}/${m.file}.js')),`).join('\n');+ const hideNotice = ctx.hostGlobal+ ? ` try { ${ctx.hostGlobal}.hideLoading && ${ctx.hostGlobal}.hideLoading(); } catch (e) {}\n`+ : '';const boot = `const asFactory = (m) => (typeof m === 'function' ? m : (m && m.default) || m);const engineFactory = asFactory(${load}('./${ctx.runtimeDir}/${ctx.engineGlueFile}'));const sideModuleFactories = {${requires}};const bundle = ${load}('./game-bundle.js');-// A boot that fails rejects; a host without onUnhandledRejection drops that-// silently, which leaves a device on the loading screen with nothing in the log.Promise.resolve(bundle.boot(engineFactory, sideModuleFactories)).catch(function (e) {- console.error('[estella] the game did not start: ' + ((e && (e.stack || e.message)) || e));+${hideNotice} console.error('[estella] the game did not start: ' + ((e && (e.stack || e.message)) || e));});`;if (!ctx.engineSubpackage) {// Before the bundle is REQUIRED: the runtime's own indicator cannot@@ -146,32 +147,42 @@ Promise.resolve(bundle.boot(engineFactory, sideModuleFactories)).catch(function${notice}${boot}`;}- // The host fetches the engine binary before the bundle is parsed, so the- // runtime's own indicator cannot cover this wait — and it is the one stage- // with real byte progress. `showLoading` is OPTIONAL, hence `__say`.return `'use strict';// Generated by Estella exportGame (MiniGame entry, engine in a subpackage).var __g = ${ctx.hostGlobal};+var __done = false;var __say = function (t) { try { __g.showLoading && __g.showLoading({ title: t, mask: true }); } catch (e) {} };+var __hide = function () { try { __g.hideLoading && __g.hideLoading(); } catch (e) {} };+var __percent = function (p) {+ var v = p && p.progress;+ if (!(typeof v === 'number' && isFinite(v) && v >= 0 && v <= 100)) {+ var w = p && p.totalBytesWritten, t = p && p.totalBytesExpectedToWrite;+ v = typeof w === 'number' && typeof t === 'number' && t > 0 && w >= 0 ? Math.min(100, (w / t) * 100) : NaN;+ }+ return isFinite(v) ? ' ' + Math.round(v) + '%' : '';+};__say('Fetching the engine 0%');var __task = __g.loadSubpackage({name: ${JSON.stringify(ctx.engineSubpackage)},success() {-${boot.split('\n').map((l) => (l ? ` ${l}` : l)).join('\n')}+ __done = true;+ try {+${boot.split('\n').map((l) => (l ? ` ${l}` : l)).join('\n')}+ } catch (e) {+ __hide();+ console.error('[estella] the game did not start: ' + ((e && (e.stack || e.message)) || e));+ }},fail(err) {- try { __g.hideLoading && __g.hideLoading(); } catch (e) {}- // Stringified: a vendor hands back an object, and a console line reading- // "[object Object]" is the one place a device gives you to look.+ __done = true;+ __hide();var __why = ''; try { __why = JSON.stringify(err); } catch (e) { __why = String(err); }console.error('[estella] the engine subpackage ${ctx.engineSubpackage} did not load — the game cannot start: ' + __why);},});-// Optional on the host: a version without it leaves the 0% notice up, which is-// still a package that says it is doing something.if (__task && __task.onProgressUpdate) {__task.onProgressUpdate(function (p) {- __say('Fetching the engine ' + Math.round(p.progress || 0) + '%');+ if (!__done) __say('Fetching the engine' + __percent(p));});}diff --git a/pipeline/tests/export-wechat.test.ts b/pipeline/tests/export-wechat.test.tsindex 107f28902..49d689905 100644--- a/pipeline/tests/export-wechat.test.ts+++ b/pipeline/tests/export-wechat.test.ts@@ -831,9 +831,6 @@ describe('exportGame (wechat)', () => {// it is the one part of a cold start with real byte progress.expect(entry.indexOf('showLoading')).toBeLessThan(entry.indexOf('loadSubpackage'));expect(entry).toContain('onProgressUpdate');- // A failed fetch takes the notice down with it, rather than leaving the- // host spinning over a game that will never start.- expect(entry.slice(entry.indexOf('fail('))).toContain('hideLoading');// 6. …and the notice is never what kills the boot. MiniGameGlobal declares// showLoading OPTIONAL, and this is the entry's FIRST line: an unguardeddiff --git a/pipeline/tests/minigame-subpackage-entry.test.ts b/pipeline/tests/minigame-subpackage-entry.test.tsnew file mode 100644index 000000000..e64ee8641--- /dev/null+++ b/pipeline/tests/minigame-subpackage-entry.test.ts@@ -0,0 +1,92 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import vm from 'node:vm';+import { defaultMiniGameEntry } from '../src/export/miniGameExportProfile';++interface Task {+ progress?: (p: Record<string, number>) => void;+}++function runEntry(opts: { requireThrows?: boolean; bootRejects?: boolean } = {}) {+ const titles: string[] = [];+ const events: string[] = [];+ const errors: string[] = [];+ const task: Task = {};+ let succeed: (() => void) | undefined;+ let fail: ((e: unknown) => void) | undefined;+ const wx = {+ showLoading(o: { title: string }) { titles.push(o.title); events.push('show'); },+ hideLoading() { events.push('hide'); },+ loadSubpackage(o: { success(): void; fail(e: unknown): void }) {+ succeed = () => o.success();+ fail = (e) => o.fail(e);+ return { onProgressUpdate(cb: Task['progress']) { task.progress = cb; } };+ },+ };+ const bundle = {+ boot: () => {+ events.push('boot');+ return opts.bootRejects ? Promise.reject(new Error('ABI layout hash mismatch')) : new Promise(() => {});+ },+ };+ const require = (p: string) => {+ if (opts.requireThrows && p.includes('esengine')) throw new Error(`module '${p}' is not defined`);+ return p.endsWith('game-bundle.js') ? bundle : () => {};+ };+ const src = defaultMiniGameEntry({+ sideModules: [], engineGlueFile: 'esengine.wxgame.js', runtimeDir: 'wasm',+ hostGlobal: 'wx', engineSubpackage: 'engine',+ });+ vm.runInNewContext(src, { wx, require, console: { error: (m: string) => errors.push(m) }, Promise });+ return { titles, events, errors, task, succeed: () => succeed!(), fail: (e: unknown) => fail!(e) };+}++describe('mini-game entry with the engine in a subpackage, executed', () => {+ it('never shows a percentage outside 0–100, whatever the host reports', () => {+ const r = runEntry();+ r.task.progress!({ progress: -20608, totalBytesWritten: 206, totalBytesExpectedToWrite: -1 });+ r.task.progress!({ progress: 40, totalBytesWritten: 400, totalBytesExpectedToWrite: 1000 });+ r.task.progress!({ progress: NaN, totalBytesWritten: 500, totalBytesExpectedToWrite: 1000 });+ r.task.progress!({ progress: 250, totalBytesWritten: 0, totalBytesExpectedToWrite: 0 });+ for (const t of r.titles) {+ const m = /(-?\d+)%/.exec(t);+ if (m) expect(Number(m[1]), t).toBeGreaterThanOrEqual(0);+ if (m) expect(Number(m[1]), t).toBeLessThanOrEqual(100);+ }+ expect(r.titles).toContain('Fetching the engine 40%');+ expect(r.titles).toContain('Fetching the engine 50%');+ });++ it('a progress event after the subpackage loaded does not put the notice back over the game', () => {+ const r = runEntry();+ r.succeed();+ expect(r.events).toContain('boot');+ const shown = r.titles.length;+ r.task.progress!({ progress: 100, totalBytesWritten: 1000, totalBytesExpectedToWrite: 1000 });+ expect(r.titles.length).toBe(shown);+ });++ it('a boot that throws while the subpackage callback runs takes the notice down and says why', () => {+ const r = runEntry({ requireThrows: true });+ expect(() => r.succeed()).not.toThrow();+ expect(r.events.at(-1)).toBe('hide');+ expect(r.errors.join('\n')).toContain('is not defined');+ });++ it('a boot that rejects takes the notice down and says why', async () => {+ const r = runEntry({ bootRejects: true });+ r.succeed();+ await new Promise((res) => setTimeout(res, 0));+ expect(r.events.at(-1)).toBe('hide');+ expect(r.errors.join('\n')).toContain('ABI layout hash mismatch');+ });++ it('a failed fetch takes the notice down and later progress does not bring it back', () => {+ const r = runEntry();+ r.fail({ errMsg: 'loadSubpackage:fail' });+ r.task.progress!({ progress: 10, totalBytesWritten: 1, totalBytesExpectedToWrite: 10 });+ expect(r.events.at(-1)).toBe('hide');+ expect(r.errors.join('\n')).toContain('loadSubpackage:fail');+ });+});