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(hot-update): a mini-game fetches its update from the CDN, and shows it offline
esengined330b5400ab1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ea571dbed..fb0c3b203 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,8 @@ published separately; it ships inside the editor.### Fixed+- A WeChat development build connects to the editor from WeChat DevTools (the domain check is turned off for that build only), and frame replays come back from a mini-game.+- Hot update works on mini-games: the update is fetched from the CDN, verified, applied and cached, and after a restart without a network the game starts on it with its updated art.- A frame-rate cap now holds: `setTargetFrameRate(30)` on a 60 Hz display runs at 30, not 24.- A hot update reports how far it got — verified, applied, stored for the next launch, cached for offline — instead of one `ok`; two updates at once no longer both commit or lose the newer one; and an update stored by an older build no longer covers a newer one the player installed.- A hot update on a mini-game is stored for the next launch and its assets are cached on the device, so the updated game starts offline; before, a mini-game went back to what shipped.diff --git a/sdk/src/asset/Backend.ts b/sdk/src/asset/Backend.tsindex 032a3d358..2342f6c26 100644--- a/sdk/src/asset/Backend.ts+++ b/sdk/src/asset/Backend.ts@@ -2,6 +2,33 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { platformFetch, platformReadFile, platformReadTextFile, platformReadCacheFile } from '../platform';+function isRemoteUrl(url: string): boolean {+ return /^https?:\/\//i.test(url);+}++/**+ * Content cache first: hot update wrote its verified, content-addressed (immutable)+ * assets to the platform's disk store keyed by this url, so they load offline and+ * skip the CDN. Only remote urls are ever written, so anything else just fetches.+ */+async function fetchUrlBinary(url: string, path: string): Promise<ArrayBuffer> {+ if (isRemoteUrl(url)) {+ const cached = await platformReadCacheFile(url);+ if (cached) return cached;+ }+ // A mini-game's request answers text unless told otherwise, and bytes re-encoded+ // from text are not the image: every hot-updated asset failed its hash there.+ const response = await platformFetch(url, { responseType: 'arraybuffer' });+ if (!response.ok) throw new Error(`Failed to fetch '${path}': ${response.status} ${response.statusText}`);+ return response.arrayBuffer();+}++async function fetchUrlText(url: string, path: string): Promise<string> {+ const response = await platformFetch(url);+ if (!response.ok) throw new Error(`Failed to fetch '${path}': ${response.status} ${response.statusText}`);+ return response.text();+}+export interface Backend {fetchBinary(path: string): Promise<ArrayBuffer>;fetchText(path: string): Promise<string>;@@ -21,30 +48,11 @@ export class HttpBackend implements Backend {}async fetchBinary(path: string): Promise<ArrayBuffer> {- const url = this.resolveUrl(path);- // Content cache: hot-update wrote its verified, content-addressed (immutable)- // assets to the platform's disk store keyed by this url; serve them first so- // updated assets load offline and skip the CDN roundtrip. Only remote (http(s))- // urls are cache-eligible — local / same-origin paths are already local, and- // nothing else is ever written, so a miss just falls through to a normal fetch.- if (/^https?:\/\//i.test(url)) {- const cached = await platformReadCacheFile(url);- if (cached) return cached;- }- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch '${path}': ${response.status} ${response.statusText}`);- }- return response.arrayBuffer();+ return fetchUrlBinary(this.resolveUrl(path), path);}async fetchText(path: string): Promise<string> {- const url = this.resolveUrl(path);- const response = await platformFetch(url);- if (!response.ok) {- throw new Error(`Failed to fetch '${path}': ${response.status} ${response.statusText}`);- }- return response.text();+ return fetchUrlText(this.resolveUrl(path), path);}resolveUrl(path: string): string {@@ -66,12 +74,13 @@ export class HttpBackend implements Backend {* the path IS the file location.*/export class FileSystemBackend implements Backend {+ // Its own files are in the package; a hot update's manifest and assets are on a CDN.async fetchBinary(path: string): Promise<ArrayBuffer> {- return platformReadFile(path);+ return isRemoteUrl(path) ? fetchUrlBinary(path, path) : platformReadFile(path);}async fetchText(path: string): Promise<string> {- return platformReadTextFile(path);+ return isRemoteUrl(path) ? fetchUrlText(path, path) : platformReadTextFile(path);}resolveUrl(path: string): string {diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.tsindex e74442155..300afa106 100644--- a/sdk/src/platform/minigame/adapter.ts+++ b/sdk/src/platform/minigame/adapter.ts@@ -121,7 +121,16 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {}async loadImagePixels(path: string): Promise<ImageLoadResult> {- return mgLoadImagePixels(this.g_, path);+ return mgLoadImagePixels(this.g_, this.cachedFileOf_(path) ?? path);+ }++ /** Where hot update stored @p url's bytes, when it did: an image drawn from the+ * CDN url instead goes blank the first launch without a network. */+ private cachedFileOf_(url: string): string | null {+ const dir = this.g_.env?.USER_DATA_PATH;+ if (!dir || !/^https?:\/\//i.test(url)) return null;+ const file = `${dir}/${cacheEntryName(url)}`;+ return mgFileExistsSync(this.fs(), file) ? file : null;}async instantiateWasm(diff --git a/sdk/tests/content-cache.test.ts b/sdk/tests/content-cache.test.tsindex 4e23da738..f7aa5f37b 100644--- a/sdk/tests/content-cache.test.ts+++ b/sdk/tests/content-cache.test.ts@@ -9,7 +9,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { join } from 'node:path';import { tmpdir } from 'node:os';import { rm } from 'node:fs/promises';-import { HttpBackend } from '../src/asset/Backend';+import { HttpBackend, FileSystemBackend } from '../src/asset/Backend';import { setPlatform, platformReadCacheFile, platformWriteCacheFile } from '../src/platform/base';import type { PlatformAdapter, PlatformResponse } from '../src/platform/types';import { nodeAdapter } from '../src/platform/node';@@ -72,6 +72,41 @@ describe('HttpBackend content cache (offline hot-update store)', () => {});});+describe('a packaged realm (mini-game, native) reaches a CDN url over the network', () => {+ // Its own files are read from the package; a hot update's manifest and assets+ // live on a CDN, and reading those as package paths found nothing.+ it('fetches a manifest from the CDN as text', async () => {+ const fetch = vi.fn(async () => ({ ok: true, status: 200, text: async () => '{"version":"2.0"}' }));+ const readTextFile = vi.fn(async () => { throw new Error('not in the package'); });+ setPlatform(mockPlatform({ fetch: fetch as never, readTextFile }));+ expect(await new FileSystemBackend().fetchText('https://cdn/asset-manifest.json')).toBe('{"version":"2.0"}');+ expect(readTextFile).not.toHaveBeenCalled();+ });++ it('serves an updated asset from the cache first, as the web does', async () => {+ const cached = new Uint8Array([7, 7]).buffer;+ const fetch = vi.fn();+ setPlatform(mockPlatform({ fetch: fetch as never, readCacheFile: async () => cached }));+ expect(await new FileSystemBackend().fetchBinary('https://cdn/assets/abcd.png')).toBe(cached);+ expect(fetch).not.toHaveBeenCalled();+ });++ it('asks for bytes, so a host that answers text by default hands over the image itself', async () => {+ const fetch = vi.fn(async () => okResponse(new ArrayBuffer(4)));+ setPlatform(mockPlatform({ fetch: fetch as never, readCacheFile: async () => null }));+ await new FileSystemBackend().fetchBinary('https://cdn/assets/abcd.png');+ expect(fetch).toHaveBeenCalledWith('https://cdn/assets/abcd.png', expect.objectContaining({ responseType: 'arraybuffer' }));+ });++ it('still reads its own files from the package', async () => {+ const readFile = vi.fn(async () => new ArrayBuffer(3));+ const fetch = vi.fn();+ setPlatform(mockPlatform({ fetch: fetch as never, readFile }));+ expect((await new FileSystemBackend().fetchBinary('assets/hero.png')).byteLength).toBe(3);+ expect(fetch).not.toHaveBeenCalled();+ });+});+describe('node adapter disk cache (real filesystem)', () => {const dir = join(tmpdir(), `esengine-cache-test-${process.pid}`);beforeEach(() => { process.env.ESENGINE_CACHE_DIR = dir; });diff --git a/sdk/tests/minigame-content-cache.test.ts b/sdk/tests/minigame-content-cache.test.tsindex 98ab4c7ff..f22260f94 100644--- a/sdk/tests/minigame-content-cache.test.ts+++ b/sdk/tests/minigame-content-cache.test.ts@@ -63,4 +63,29 @@ describe('a mini-game content cache', () => {expect(await platformWriteCacheFile(URL, new ArrayBuffer(4))).toBe('failed');expect(await platformReadCacheFile(URL)).toBeNull();});++ it('draws a cached image from the disk, not the CDN, so an updated texture shows offline', async () => {+ const files = host({ dir: 'wxfile://usr' });+ await platformWriteCacheFile(URL, new Uint8Array([1]).buffer);+ const sources: string[] = [];+ const adapter = new MiniGamePlatformAdapter({+ id: 'wechat', hostLabel: 'Test',+ global: {+ getSystemInfoSync: () => ({ pixelRatio: 1, screenWidth: 1, screenHeight: 1, platform: 'devtools', language: 'zh_CN' }),+ getFileSystemManager: () => ({+ accessSync: (p: string) => { if (!files.has(p)) throw new Error('no such file'); },+ readFile: () => {}, writeFile: () => {},+ }),+ env: { USER_DATA_PATH: 'wxfile://usr' },+ createImage: () => {+ const img: Record<string, unknown> = {};+ Object.defineProperty(img, 'src', { set: (v: string) => { sources.push(v); (img.onerror as (e: unknown) => void)?.({}); } });+ return img;+ },+ } as unknown as MiniGameGlobal,+ } as MiniGameProfile);+ await adapter.loadImagePixels(URL).catch(() => {});+ await adapter.loadImagePixels('https://cdn.example/v2/never-cached.png').catch(() => {});+ expect(sources).toEqual([`wxfile://usr/${cacheEntryName(URL)}`, 'https://cdn.example/v2/never-cached.png']);+ });});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 36bc0024f..fad94527b 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -1076,4 +1076,8 @@ export const NOTED = {{ note: 'In the Outliner, a connected development build\'s world can be shown instead of this editor\'s (read-only, with live values in Details).' },'feat(debug): the debug channel reports what it costs the game it watches':{ internal: 'a number the channel reports for its own budget check; the profiler does not show it yet' },+ 'fix(minigame): a WeChat development build reaches the editor, and its replays come back':+ { note: 'A WeChat development build connects to the editor from WeChat DevTools (the domain check is turned off for that build only), and frame replays come back from a mini-game.' },+ 'fix(hot-update): a mini-game fetches its update from the CDN, and shows it offline':+ { note: 'Hot update works on mini-games: the update is fetched from the CDN, verified, applied and cached, and after a restart without a network the game starts on it with its updated art.' },};