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
feat(assets): content-addressed hot update for shipped games
yhh823417601404
diff --git a/.gitignore b/.gitignoreindex a0debc915..a34d3d9ef 100644--- a/.gitignore+++ b/.gitignore@@ -59,6 +59,8 @@ compile_commands.json# Cooked-build render-verify artifacts (regenerated by verify:render:cooked)desktop/.cooked-verify/desktop/.cooked-src/+# Hot-update render-verify artifacts (regenerated by verify:render:hotupdate)+desktop/.hotupdate-verify/# Emscripten output*.wasmdiff --git a/desktop/electron/addressableManifest.ts b/desktop/electron/addressableManifest.tsnew file mode 100644index 000000000..5ef643fcf--- /dev/null+++ b/desktop/electron/addressableManifest.ts@@ -0,0 +1,89 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Shared cook → AddressableManifest (v2.0) builder.+ *+ * Reads the flat `assets.manifest.json` a cook emits and produces the+ * AddressableManifest (groups + bundle modes + content-addressed paths ++ * a build `revision`) the runtime's `Assets.setManifest` / `loadGroup` /+ * hot-update consume. ONE builder for EVERY target — web, desktop, and+ * mini-game all get the same addressable model, so `loadGroup` and hot-+ * update are platform-uniform (historically only the mini-game export+ * emitted a v2.0 manifest; web/desktop shipped only the flat v1.0 one).+ *+ * Pure Node (fs). `deriveManifestRevision` is imported from the SDK source+ * — the SAME hash the runtime reads back — so build and runtime agree by+ * construction (mirrors how the cook imports `contentHashHex`).+ */+import { readFile, stat } from 'node:fs/promises';+import path from 'node:path';+import { deriveManifestRevision, type AddressableManifest } from '../../sdk/src/asset/AddressableManifest';++/** The flat v1.0 cook manifest this reads (see cookAssets `CookManifestEntry`). */+interface FlatManifest {+ entries: {+ uuid: string; path: string; sourcePath?: string; type: string;+ contentHash?: string; size?: number; group?: string; groupMode?: string;+ compressedFormats?: string[];+ atlas?: { page: number; frame: { x: number; y: number; width: number; height: number }; pageWidth: number; pageHeight: number };+ }[];+}++// Editor asset type → AddressableAssetType (sdk/src/assetTypes.ts). Feeds the+// runtime Catalog; an unmapped type degrading to 'binary' is harmless.+const ADDRESSABLE_TYPE: Record<string, string> = {+ texture: 'texture', material: 'material', audio: 'audio', 'bitmap-font': 'bitmap-font',+ prefab: 'prefab', spine: 'spine',+ scene: 'json', 'anim-clip': 'json', tilemap: 'json', timeline: 'json', json: 'json', shader: 'text',+};+export const addrType = (editorType: string): string => ADDRESSABLE_TYPE[editorType] ?? 'binary';++/** A group's bundleMode from its assets' cooked `groupMode`, with the legacy+ * fallback (an entry without groupMode): `main` → local, else lazy subpackage. */+export function bundleModeFor(groupName: string, groupMode: string | undefined): string {+ if (groupMode === 'local' || groupMode === 'lazy' || groupMode === 'remote') return groupMode;+ return groupName === 'main' ? 'local' : 'lazy';+}++/**+ * Build the AddressableManifest (as a pretty JSON string) from a cook output+ * dir's flat `assets.manifest.json`. Each asset carries its `contentHash` + `size`+ * so the runtime dedupes by content and treats `<hash>.<ext>` as a permanently-+ * cacheable url; a top-level `revision` (hash-of-hashes) is the fast hot-update+ * gate. `size` falls back to stat() only for a legacy cook that omitted it.+ */+export async function buildAddressableManifest(absOut: string): Promise<string> {+ const flat = JSON.parse(await readFile(path.join(absOut, 'assets.manifest.json'), 'utf8')) as FlatManifest;+ type Entry = {+ path: string; address?: string; type: string; size: number; labels: string[]; contentHash?: string;+ metadata?: { atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number }; atlasPageWidth?: number; atlasPageHeight?: number };+ };+ type Group = { bundleMode: string; labels: string[]; assets: Record<string, Entry> };+ const groups: Record<string, Group> = {};+ for (const e of flat.entries) {+ let size = e.size ?? 0;+ if (e.size == null) { try { size = (await stat(path.join(absOut, e.path))).size; } catch { /* missing → 0 */ } }+ const groupName = e.group ?? 'main';+ const group = (groups[groupName] ??= {+ bundleMode: bundleModeFor(groupName, e.groupMode), labels: [], assets: {},+ });+ const entry: Entry = { path: e.path, type: addrType(e.type), size, labels: [] };+ if (e.contentHash) entry.contentHash = e.contentHash;+ // The logical source path rides as the asset's address: path-style refs+ // resolve through it. Only meaningful when staging renamed the file.+ if (e.sourcePath && e.sourcePath !== e.path) entry.address = e.sourcePath;+ if (e.atlas) {+ entry.metadata = {+ atlasPage: e.atlas.page, atlasFrame: e.atlas.frame,+ atlasPageWidth: e.atlas.pageWidth, atlasPageHeight: e.atlas.pageHeight,+ };+ }+ group.assets[e.uuid.toLowerCase()] = entry;+ }+ // Always emit a main group so the runtime's main package exists even if every+ // asset landed in a subpackage / remote group.+ groups.main ??= { bundleMode: 'local', labels: [], assets: {} };+ const manifest = { version: '2.0', groups } as unknown as AddressableManifest;+ manifest.revision = deriveManifestRevision(manifest);+ return JSON.stringify(manifest, null, 2) + '\n';+}diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.tsindex 988dc066b..8312dc88d 100644--- a/desktop/electron/cookAssets.ts+++ b/desktop/electron/cookAssets.ts@@ -35,6 +35,11 @@ const MANIFEST = 'assets.manifest.json';* simply ignores these extra fields (it maps uuid→path); the AddressableManifest* and content-addressed naming are what read them.*/+/** How an addressable group is delivered — the typed mode the folder convention+ * ({@link groupOf}) assigns and the AddressableManifest carries. `local` ships in+ * the main package; `lazy` in an on-demand subpackage; `remote` on a CDN (hot-update). */+export type GroupDelivery = 'local' | 'lazy' | 'remote';+export interface CookManifestEntry extends AssetEntry {/** XXH64 (16 hex) of the exact bytes staged — the asset's physical identity. */contentHash: string;@@ -58,6 +63,10 @@ export interface CookManifestEntry extends AssetEntry {* layout read it.*/group: string;+ /** How `group` is delivered (folder convention). Absent ⇒ `local`. The+ * AddressableManifest maps it to bundleMode; the WeChat subpackage layout and+ * the CDN / hot-update path both read it. */+ groupMode?: GroupDelivery;/*** Present when this texture was packed into an atlas page: `path` then points* at the PAGE file (URL-level redirect for free) and this records where the@@ -96,6 +105,40 @@ export function subpackageOf(projectRelPath: string): string | null {return m ? m[1] : null;}+const REMOTE_RE = /^remote\/([^/]+)\//;+/**+ * Folder-convention remote-group detection: an asset under `remote/<name>/…`+ * belongs to CDN-delivered group `<name>` — shipped to a remote origin, NOT the+ * package, and fetched on demand / hot-updated. Null for package assets. Parallel+ * to {@link subpackageOf}; the two are mutually exclusive by folder.+ */+export function remoteGroupOf(projectRelPath: string): string | null {+ const m = REMOTE_RE.exec(projectRelPath.replace(/\\/g, '/'));+ return m ? m[1] : null;+}++/**+ * The addressable group + delivery an asset's folder assigns it — the single+ * source of truth cook staging, the export layout, and the manifest all derive+ * from. `subpackages/<name>/` → lazy `<name>`; `remote/<name>/` → remote `<name>`;+ * anything else → local `main`.+ */+export function groupOf(projectRelPath: string): { name: string; delivery: GroupDelivery } {+ const sub = subpackageOf(projectRelPath);+ if (sub) return { name: sub, delivery: 'lazy' };+ const rem = remoteGroupOf(projectRelPath);+ if (rem) return { name: rem, delivery: 'remote' };+ return { name: 'main', delivery: 'local' };+}++/** Content-addressed base dir for a group's delivery: main → `assets`,+ * lazy → `subpackages/<name>/assets`, remote → `remote/<name>/assets`. */+function caBaseFor(name: string, delivery: GroupDelivery): string {+ if (delivery === 'lazy') return `subpackages/${name}/assets`;+ if (delivery === 'remote') return `remote/${name}/assets`;+ return 'assets';+}+/** Targets the UASTC KTX2 the cook emits can transcode to at runtime. */const COMPRESSED_TARGETS = ['astc-4x4', 'etc2-rgba8', 's3tc-dxt5'];@@ -233,7 +276,9 @@ export async function cookAssets(// shared dep that lives outside subpackages/ resolves to group 'main' below, so// it lands in the always-present main package, not duplicated per subpackage.for (const e of index.entries) {- if (subpackageOf(e.path)) seed(e.uuid);+ // …and remote CDN / hot-update assets (remote/<name>/): never scene-+ // referenced, but must be cooked + staged for upload to the CDN root.+ if (subpackageOf(e.path) || remoteGroupOf(e.path)) seed(e.uuid);}// Force-include locale string tables: translations load by code / plugin// option (a scene never references them — Text carries KEYS, not paths), so@@ -322,8 +367,8 @@ export async function cookAssets(compressedFormats = COMPRESSED_TARGETS;}const pageHash = contentHashHex(pageBytes);- const group = subpackageOf(`${dir}/`) ?? 'main';- const caBase = group === 'main' ? 'assets' : `subpackages/${group}/assets`;+ const { name: group, delivery } = groupOf(`${dir}/`);+ const caBase = caBaseFor(group, delivery);const pageOutRel = contentAddressed? `${caBase}/${pageHash}${pageExt}`: `${dir}.page${n}${pageExt}`;@@ -354,6 +399,7 @@ export async function cookAssets(// page's (hash/size of the bytes actually served for this ref).const framePlan = atlasPlan.get(entry.path);if (framePlan) {+ const fg = groupOf(entry.path);manifestEntries.push({uuid: entry.uuid,path: framePlan.pageOutRel,@@ -362,7 +408,8 @@ export async function cookAssets(importer: entry.importer,contentHash: framePlan.pageHash,size: framePlan.pageSize,- group: subpackageOf(entry.path) ?? 'main',+ group: fg.name,+ groupMode: fg.delivery,...(framePlan.compressedFormats ? { compressedFormats: framePlan.compressedFormats } : {}),atlas: {page: framePlan.page,@@ -460,9 +507,9 @@ export async function cookAssets(// Group by folder convention. Lazy-subpackage assets must stay under their// subpackage root (subpackages/<name>/…) so the root maps to a WeChat// subPackage — including the content-addressed layout (root/assets/<hash>).- const group = subpackageOf(entry.path) ?? 'main';+ const { name: group, delivery } = groupOf(entry.path);const useCA = contentAddressed && entry.type !== 'scene';- const caBase = group === 'main' ? 'assets' : `subpackages/${group}/assets`;+ const caBase = caBaseFor(group, delivery);const outRel = useCA ? `${caBase}/${hash}${ext}` : swapExt(entry.path, ext);const dst = path.join(absOut, outRel);if (!staged.has(outRel)) {@@ -479,6 +526,7 @@ export async function cookAssets(contentHash: hash,size: data.byteLength,group,+ groupMode: delivery,...(compressedFormats ? { compressedFormats } : {}),});// The video's audio track ships as its own manifest entry addressed as@@ -504,6 +552,7 @@ export async function cookAssets(contentHash: audioHash,size: videoAudio.byteLength,group,+ groupMode: delivery,});}} catch (err) {diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsindex 5b290df51..d0201c59e 100644--- a/desktop/electron/exportGame.ts+++ b/desktop/electron/exportGame.ts@@ -25,6 +25,7 @@ import { writeFile, mkdir, cp, readdir } from 'node:fs/promises';import { existsSync } from 'node:fs';import path from 'node:path';import { cookAssets } from './cookAssets';+import { buildAddressableManifest } from './addressableManifest';import { IMPORT_MAP_JSON, IMPORT_MAP_CSP_HASH } from './buildPlayRealm';import { exportWeChat } from './exportWeChat';import { exportPlayable } from './exportPlayable';@@ -306,6 +307,10 @@ export async function exportGame(opts: {uiTheme?: 'light';/** Project theme color overrides (role → #rrggbbaa hex) — the host parses them. */uiThemeColors?: Record<string, string>;+ /** Hot-update delivery baked into game.config.json: the CDN root `remote`-group+ * assets resolve against + the storage key an applied update persists under.+ * The addressable `asset-manifest.json` this export always emits enables it. */+ hotUpdate?: { remoteRoot?: string; persistUpdateKey?: string };}): Promise<ExportGameResult> {const platform = opts.platform ?? 'web';const title = opts.title ?? 'Game';@@ -391,6 +396,12 @@ export async function exportGame(opts: {warnings.push(...cook.warnings);progress({ phase: 'Cooking assets', detail: `${cook.included.length} reachable` });+ // 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+ // still reads the flat manifest; this powers on-demand + hot-update delivery.+ await writeFile(path.join(payloadDir, 'asset-manifest.json'), await buildAddressableManifest(payloadDir));+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@@ -435,6 +446,7 @@ export async function exportGame(opts: {...(opts.screenFit && opts.screenFit.scaleMode >= 0 ? { screenFit: opts.screenFit } : {}),...(opts.uiTheme === 'light' ? { uiTheme: opts.uiTheme } : {}),...(opts.uiThemeColors && Object.keys(opts.uiThemeColors).length > 0 ? { uiThemeColors: opts.uiThemeColors } : {}),+ ...(opts.hotUpdate ? { hotUpdate: opts.hotUpdate } : {}),},null, 2,) + '\n',diff --git a/desktop/electron/exportMiniGame.ts b/desktop/electron/exportMiniGame.tsindex f12586b32..fd1d580a1 100644--- a/desktop/electron/exportMiniGame.ts+++ b/desktop/electron/exportMiniGame.ts@@ -29,10 +29,11 @@* own path. Pure Node (esbuild + fs) — IPC wiring is in main.ts.*/import { loadEsbuild } from './esbuildRuntime';-import { writeFile, mkdir, cp, readFile, rename, stat, rm } from 'node:fs/promises';+import { writeFile, mkdir, cp, readFile, rename, rm } from 'node:fs/promises';import { existsSync } from 'node:fs';import path from 'node:path';import { cookAssets } from './cookAssets';+import { buildAddressableManifest } from './addressableManifest';import type { ExportScene } from './exportGame';import type { OnExportProgress } from './exportProgress';import { esengineAlias } from './esengineResolve';@@ -54,21 +55,11 @@ export interface ExportMiniGameResult {interface CookManifest {entries: {uuid: string; path: string; sourcePath?: string; type: string;- contentHash?: string; size?: number; group?: string;+ contentHash?: string; size?: number; group?: string; groupMode?: string;atlas?: { page: number; frame: { x: number; y: number; width: number; height: number }; pageWidth: number; pageHeight: number };}[];}-// Editor asset type → AddressableAssetType (sdk/src/assetTypes.ts). The mini-game-// path resolver ignores type (keys by uuid → path); this only feeds the Catalog,-// so an unmapped type degrading to 'binary' is harmless.-const ADDRESSABLE_TYPE: Record<string, string> = {- texture: 'texture', material: 'material', audio: 'audio', 'bitmap-font': 'bitmap-font',- prefab: 'prefab', spine: 'spine',- scene: 'json', 'anim-clip': 'json', tilemap: 'json', timeline: 'json', json: 'json', shader: 'text',-};-const addrType = (editorType: string): string => ADDRESSABLE_TYPE[editorType] ?? 'binary';-const UUID_PREFIX = '@uuid:';/** Strip @uuid: asset refs to the bare (lowercased) uuid the resolver keys by.@@ -87,7 +78,9 @@ function stripUuidRefs(v: unknown): unknown {/** Distinct lazy subpackage groups present in the cook, as vendor subPackage roots. */function subPackagesOf(entries: CookManifest['entries'], subpackageDir: string): Array<{ name: string; root: string }> {const names = new Set<string>();- for (const e of entries) if (e.group && e.group !== 'main') names.add(e.group);+ // Remote (CDN / hot-update) groups are NOT WeChat 分包 — they're fetched from a+ // remote origin, not packed as a subPackage root.+ for (const e of entries) if (e.group && e.group !== 'main' && e.groupMode !== 'remote') names.add(e.group);return [...names].map((name) => ({ name, root: `${subpackageDir}/${name}` }));}@@ -151,53 +144,6 @@ async function scanSideModules(return present;}-/** Read the web cook's flat manifest → AddressableManifest the runtime reads.- * Carries the cook's `contentHash` (XXH64) + `size` through so the runtime can- * dedupe by content and treat `<hash>.<ext>` as a permanently-cacheable CDN URL;- * falls back to stat() for size only if a legacy cook omitted it. */-async function buildAddressableManifest(absOut: string): Promise<string> {- const cook = JSON.parse(await readFile(path.join(absOut, 'assets.manifest.json'), 'utf8')) as CookManifest;- type Entry = {- path: string; address?: string; type: string; size: number; labels: string[]; contentHash?: string;- metadata?: { atlasPage?: number; atlasFrame?: { x: number; y: number; width: number; height: number }; atlasPageWidth?: number; atlasPageHeight?: number };- };- type Group = { bundleMode: string; labels: string[]; assets: Record<string, Entry> };- // One group per cook group: 'main' is local (eager); every other is a lazy- // subpackage. bundleMode here is the typed wire value the SDK's normalizeBundleMode- // reads ('local' | 'lazy').- const groups: Record<string, Group> = {};- for (const e of cook.entries) {- let size = e.size ?? 0;- if (e.size == null) { try { size = (await stat(path.join(absOut, e.path))).size; } catch { /* missing file → 0 */ } }- const groupName = e.group ?? 'main';- const group = (groups[groupName] ??= {- bundleMode: groupName === 'main' ? 'local' : 'lazy', labels: [], assets: {},- });- const entry: Entry = { path: e.path, type: addrType(e.type), size, labels: [] };- if (e.contentHash) entry.contentHash = e.contentHash;- // The logical source path rides as the asset's address: path-style refs- // resolve through it (ManifestModel indexes addresses; the runtime builds- // its logical→staged catalog from them). Only meaningful when staging- // renamed the file (content addressing / texture encoding).- if (e.sourcePath && e.sourcePath !== e.path) entry.address = e.sourcePath;- // Atlas frame → manifest metadata; the runtime derives uv from it and- // registers the frame under its uuid/address catalog keys.- if (e.atlas) {- entry.metadata = {- atlasPage: e.atlas.page,- atlasFrame: e.atlas.frame,- atlasPageWidth: e.atlas.pageWidth,- atlasPageHeight: e.atlas.pageHeight,- };- }- group.assets[e.uuid.toLowerCase()] = entry;- }- // Always emit a main group so the runtime's main package exists even if every- // asset happened to land in a subpackage.- groups.main ??= { bundleMode: 'local', labels: [], assets: {} };- return JSON.stringify({ version: '2.0', groups }, null, 2) + '\n';-}-/*** Export the open project as a mini-game for `profile`'s vendor into `outDir`.* `sdkDir` is the SDK dist dir the bundle aliases `esengine` to (the vendordiff --git a/desktop/package.json b/desktop/package.jsonindex 6076c4d79..765b8612c 100644--- a/desktop/package.json+++ b/desktop/package.json@@ -42,6 +42,7 @@"verify:render:material": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-tint.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-tint.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0],\\\"tol\\\":40}]\" electron scripts/headless-verify.mjs","verify:render:ktx2": "vite build && ESTELLA_VERIFY_SCENE=/scenes/ktx2-sprite.esscene ESTELLA_VERIFY_MANIFEST=/scenes/ktx2-sprite.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,180,0],\\\"tol\\\":50}]\" electron scripts/headless-verify.mjs","verify:render:cooked": "vite build && ESTELLA_COOK_FIXTURE=1 vitest run tests/cooked-verify-fixture.test.ts && electron scripts/headless-cooked-verify.mjs",+ "verify:render:hotupdate": "ESTELLA_HOTUPDATE_FIXTURE=1 vitest run tests/hotupdate-verify-fixture.test.ts && electron scripts/headless-hotupdate-verify.mjs","verify:render:material:instance": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-instance.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-instance.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":40}]\" electron scripts/headless-verify.mjs","verify:render:material:texture": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-tex.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-tex.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":50}]\" electron scripts/headless-verify.mjs","verify:render:material:switch": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-sw.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-sw.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.25,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0],\\\"tol\\\":50},{\\\"x\\\":0.75,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":50}]\" electron scripts/headless-verify.mjs",diff --git a/desktop/scripts/headless-hotupdate-verify.mjs b/desktop/scripts/headless-hotupdate-verify.mjsnew file mode 100644index 000000000..83bf49fd6--- /dev/null+++ b/desktop/scripts/headless-hotupdate-verify.mjs@@ -0,0 +1,97 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Render-verifies a HOT UPDATE end-to-end against the shipped runtime.+ * One loopback origin serves the shipped `build/` at `/` and the `cdn/`+ * update under `/cdn/` (same origin, so the cooked build's CSP allows the+ * update fetch — a different port would be a different origin and blocked).+ * Boots the shipped game headless, asserts it renders GREEN (fetched from+ * the `remote` group), drives `__estellaCooked.applyRemoteUpdate(...)`, and+ * asserts the SAME running game now renders RED — proving a changed+ * `remote` asset reaches the client from the CDN with no re-ship.+ */+import { app, BrowserWindow } from 'electron';+import http from 'node:http';+import { readFile } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '.hotupdate-verify');+const BUILD = path.join(ROOT, 'build');+const CDN = path.join(ROOT, 'cdn');+const W = 256, H = 256;++app.commandLine.appendSwitch('enable-unsafe-swiftshader');+process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';++const MIME = {+ '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',+ '.css': 'text/css', '.json': 'application/json', '.esscene': 'application/json',+ '.wasm': 'application/wasm', '.ktx2': 'application/octet-stream', '.png': 'image/png',+};++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++/** One origin: `/cdn/...` serves the update build, everything else the ship build. */+function serve(buildDir, cdnDir) {+ const server = http.createServer(async (req, res) => {+ try {+ let rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '');+ let dir = buildDir;+ if (rel === 'cdn' || rel.startsWith('cdn/')) { dir = cdnDir; rel = rel.slice(4); }+ rel = rel || 'index.html';+ const abs = path.join(dir, rel);+ if (!abs.startsWith(dir)) { res.writeHead(403).end(); return; }+ const bytes = await readFile(abs);+ res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream' });+ res.end(bytes);+ } catch { res.writeHead(404).end('not found'); }+ });+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));+}++app.whenReady().then(async () => {+ let server;+ const diag = [];+ let before = null, after = null, changed = 0;+ try {+ server = await serve(BUILD, CDN);+ const base = `http://127.0.0.1:${server.address().port}`;++ const win = new BrowserWindow({ show: false, width: W, height: H, webPreferences: { offscreen: false } });+ win.webContents.on('console-message', (...a) => {+ const m = a.map((x) => (x && typeof x === 'object' ? x.message ?? '' : String(x))).join(' ');+ if (/error|fail|unwind|exception|webgl|update|group|manifest/i.test(m)) diag.push(m.slice(0, 200));+ });+ await win.loadURL(`${base}/index.html?headless=1`);++ const exec = (code) => win.webContents.executeJavaScript(code, true);+ let ready = false;+ for (let i = 0; i < 150 && !ready; i++) { ready = await exec('!!window.__estellaCooked').catch(() => false); if (!ready) await sleep(100); }+ if (!ready) throw new Error('gameHost capture hook never appeared (boot failed?)');+ await sleep(1800); // demo system fetches the cdn group + stamps the texture++ const center = `(() => { const c = window.__estellaCooked.capture(); const { width: w, height: h, rgba } = c; const i = (((h >> 1) * w) + (w >> 1)) * 4; return [rgba[i], rgba[i + 1], rgba[i + 2]]; })()`;+ before = await exec(center);++ const upd = await exec(`window.__estellaCooked.applyRemoteUpdate(${JSON.stringify(`${base}/cdn/asset-manifest.json`)}, ${JSON.stringify(`${base}/cdn`)})`);+ changed = upd && typeof upd.changed === 'number' ? upd.changed : 0;+ await sleep(1800);+ after = await exec(center);++ const isGreen = ([r, g, b]) => g >= 130 && r <= 110 && b <= 120;+ const isRed = ([r, g, b]) => r >= 150 && g <= 100 && b <= 100;+ const ok = isGreen(before) && isRed(after) && changed >= 1;++ console.log(`\n[verify:render:hotupdate] ${ok ? 'PASS' : 'FAIL'}`);+ console.log('DRIVE_RESULT ' + JSON.stringify({ before, after, changed, greenBefore: isGreen(before), redAfter: isRed(after), diag: diag.slice(0, 8) }));+ process.exitCode = ok ? 0 : 1;+ } catch (e) {+ console.log('\n[verify:render:hotupdate] FAIL — ' + (e?.message ?? e));+ console.log('DRIVE_RESULT ' + JSON.stringify({ error: String(e?.message ?? e), before, after, changed, diag: diag.slice(0, 8) }));+ process.exitCode = 1;+ } finally {+ try { server?.close(); } catch { /* ignore */ }+ app.quit();+ }+});diff --git a/desktop/scripts/solidPng.mjs b/desktop/scripts/solidPng.mjsnew file mode 100644index 000000000..87e1c752d--- /dev/null+++ b/desktop/scripts/solidPng.mjs@@ -0,0 +1,54 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Minimal dependency-free solid-color PNG encoder (Node). Used to mint the+ * hot-update demo's CDN textures deterministically — a green "shipped" art+ * and a red "update" art — without committing binaries or pulling a codec.+ */+import zlib from 'node:zlib';++const CRC_TABLE = (() => {+ const t = new Uint32Array(256);+ for (let n = 0; n < 256; n++) {+ let c = n;+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);+ t[n] = c >>> 0;+ }+ return t;+})();++function crc32(buf) {+ let c = 0xffffffff;+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+}++function chunk(type, data) {+ const typeBuf = Buffer.from(type, 'ascii');+ const len = Buffer.alloc(4); len.writeUInt32BE(data.length, 0);+ const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);+ return Buffer.concat([len, typeBuf, data, crc]);+}++/** Encode a `width`×`height` solid `[r,g,b,a]` (0–255) image as a PNG Buffer. */+export function solidPng(width, height, [r, g, b, a] = [0, 0, 0, 255]) {+ const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);+ const ihdr = Buffer.alloc(13);+ ihdr.writeUInt32BE(width, 0);+ ihdr.writeUInt32BE(height, 4);+ ihdr[8] = 8; // bit depth+ ihdr[9] = 6; // color type: RGBA+ // ihdr[10..12] = 0: default compression / filter / no interlace.+ const rowLen = width * 4;+ const raw = Buffer.alloc((rowLen + 1) * height);+ for (let y = 0; y < height; y++) {+ const off = y * (rowLen + 1);+ raw[off] = 0; // per-row filter: none+ for (let x = 0; x < width; x++) {+ const p = off + 1 + x * 4;+ raw[p] = r; raw[p + 1] = g; raw[p + 2] = b; raw[p + 3] = a;+ }+ }+ const idat = zlib.deflateSync(raw);+ return Buffer.concat([sig, chunk('IHDR', ihdr), chunk('IDAT', idat), chunk('IEND', Buffer.alloc(0))]);+}diff --git a/desktop/src/gameHost.ts b/desktop/src/gameHost.tsindex c7b22ac48..f937d88f6 100644--- a/desktop/src/gameHost.ts+++ b/desktop/src/gameHost.ts@@ -11,8 +11,8 @@* Builtin scenes run as-is; project custom-script bundles are a follow-up* (shared with the play realm's import-map work).*/-import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, atlasCatalogFields, parseThemeOverrides } from 'esengine';-import type { CatalogData, CookedAtlasInfo, ESEngineModule, SceneData } from 'esengine';+import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, atlasCatalogFields, parseThemeOverrides, Assets } from 'esengine';+import type { CatalogData, CookedAtlasInfo, ESEngineModule, SceneData, AddressableManifest } from 'esengine';interface GameConfig {entryScene: string;@@ -29,6 +29,9 @@ interface GameConfig {uiTheme?: 'light';/** Project theme color overrides (role → #rrggbbaa hex). */uiThemeColors?: Record<string, string>;+ /** 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 };}interface CookedManifest {entries: { uuid: string; path: string; sourcePath?: string; type: string; atlas?: CookedAtlasInfo }[];@@ -59,6 +62,11 @@ async function boot(): Promise<void> {const cfg = (await (await fetch('./game.config.json')).json()) as GameConfig;const manifest = (await (await fetch('./assets.manifest.json')).json()) as CookedManifest;+ // Addressable manifest (v2.0): powers Assets.loadGroup + hot-update. Optional —+ // a legacy build without it degrades to eager-only (the flat manifest above).+ const addressable = await fetch('./asset-manifest.json')+ .then((r) => (r.ok ? (r.json() as Promise<AddressableManifest>) : null))+ .catch(() => null);const sceneData = (await (await fetch(`./${cfg.entryScene}`)).json()) as SceneData;const assetManifest: Record<string, string> = {};// Logical → staged resolution for PATH-style refs, twice over: `pathMap` for@@ -127,6 +135,15 @@ async function boot(): Promise<void> {gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, rgba);return { width: w, height: h, rgba };},+ /** Drive a hot update against a served (CDN) manifest: fetch + diff + apply.+ * Rebinding the visuals is the game's job (via Assets.onInvalidate); a+ * driver settles frames after this before re-capturing. */+ async applyRemoteUpdate(manifestUrl: string, remoteRoot?: string): Promise<{ changed: number }> {+ const assets = app.getResource(Assets);+ const plan = await assets.checkForUpdate({ manifestUrl, remoteRoot });+ await assets.applyUpdate();+ return { changed: plan.changedAssets.length };+ },};}// physics.wasm sits next to esengine.wasm; the runtime loads it when the scene@@ -149,6 +166,9 @@ async function boot(): Promise<void> {assetManifest,assetPathMap: pathMap,catalogData: catalog,+ manifest: addressable,+ remoteRoot: cfg.hotUpdate?.remoteRoot,+ persistUpdateKey: cfg.hotUpdate?.persistUpdateKey,wasmBaseUrl: wasmBase.replace(/\/$/, ''),uiTheme: cfg.uiTheme,uiThemeOverrides: parseThemeOverrides(cfg.uiThemeColors),diff --git a/desktop/tests/hotupdate-verify-fixture.test.ts b/desktop/tests/hotupdate-verify-fixture.test.tsnew file mode 100644index 000000000..a0eea52eb--- /dev/null+++ b/desktop/tests/hotupdate-verify-fixture.test.ts@@ -0,0 +1,57 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Produces the two cooked builds headless-hotupdate-verify.mjs drives — a+ * shipped build of examples/hot-update-demo (green CDN art) and a "CDN+ * update" of the same project with the remote art swapped to red (a+ * different content hash → a new url + manifest revision). Guarded by+ * ESTELLA_HOTUPDATE_FIXTURE; the verify:render:hotupdate script sets it.+ * Proves a hot update end-to-end: change a `remote`-group asset, re-cook,+ * and the shipped runtime fetches the new content — no re-ship.+ */+import { describe, it, expect } from 'vitest';+import { writeFileSync, cpSync, rmSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { exportGame } from '../electron/exportGame';+import { solidPng } from '../scripts/solidPng.mjs';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const EXAMPLE = path.resolve(HERE, '..', '..', 'examples', 'hot-update-demo');+const ROOT = path.resolve(HERE, '..', '.hotupdate-verify');+const BUILD = path.join(ROOT, 'build');+const CDN = path.join(ROOT, 'cdn');+const REDSRC = path.join(ROOT, 'red-src');++const opts = (root: string, outDir: string) => ({+ root,+ entryScene: 'assets/scenes/main.esscene',+ gameHostEntry: path.resolve(HERE, '..', 'src', 'gameHost.ts'),+ scriptsEntry: 'src/main.ts',+ sdkDistDir: path.resolve(HERE, '..', '..', 'sdk', 'dist'),+ wasmDir: path.resolve(HERE, '..', '..', 'build', 'wasm', 'web'),+ outDir,+ title: 'Hot Update Demo',+ contentAddressed: true,+});++describe.skipIf(!process.env.ESTELLA_HOTUPDATE_FIXTURE)('hot-update verify fixture', () => {+ it('cooks a shipped build (green CDN art) + a CDN update (red CDN art)', async () => {+ rmSync(ROOT, { recursive: true, force: true });++ // 1. Ship build: the example exactly as committed — green art in remote/cdn/.+ const build = await exportGame(opts(EXAMPLE, BUILD));+ expect(build.ok, build.errors.join('; ')).toBe(true);++ // 2. CDN update: the SAME project but the remote art is now RED. A different+ // hash → a new content-addressed url + a new manifest revision, so the+ // runtime's diff sees exactly one changed asset.+ cpSync(EXAMPLE, REDSRC, {+ recursive: true,+ filter: (s) => !s.includes(`${path.sep}.esengine`) && !s.includes('node_modules'),+ });+ writeFileSync(path.join(REDSRC, 'remote', 'cdn', 'art.png'), solidPng(64, 64, [220, 40, 40, 255]));+ const cdn = await exportGame(opts(REDSRC, CDN));+ expect(cdn.ok, cdn.errors.join('; ')).toBe(true);+ }, 180_000);+});diff --git a/examples/hot-update-demo/.gitignore b/examples/hot-update-demo/.gitignorenew file mode 100644index 000000000..359472ac2--- /dev/null+++ b/examples/hot-update-demo/.gitignore@@ -0,0 +1,7 @@+node_modules/+dist/+.vscode/+.idea/+.DS_Store+Thumbs.db+.esengine/cache/diff --git a/examples/hot-update-demo/README.md b/examples/hot-update-demo/README.mdnew file mode 100644index 000000000..2a65736c1--- /dev/null+++ b/examples/hot-update-demo/README.md@@ -0,0 +1,51 @@+# Hot Update Demo++Ship a game, then change its art **on a CDN** and have running clients pick up the+new bytes — no re-download of the package, no store re-submission. This example+shows the whole loop on a single sprite.++## How it works++Estella assets are **content-addressed**: a cooked asset ships as+`<contentHash>.<ext>`, an immutable, permanently-cacheable URL. Change a byte →+new hash → new URL. A hot update is therefore just: *fetch the new manifest,+diff it, download the assets whose hash changed, swap the active manifest.*+Nothing is ever overwritten, so a cache can never go stale.++### The pieces++- **`remote/cdn/art.png`** — a texture in a **`remote` group**. The+ `remote/<name>/` folder convention tells the cook this asset is delivered from+ a CDN (bundle mode `remote`), not baked into the package.+- **`src/systems/hotUpdate.ts`** — on start, calls `Assets.loadGroup('cdn')` to+ fetch the remote texture and stamps its handle onto the display sprite. It also+ subscribes to `Assets.onInvalidate` so that when an update lands, it reloads the+ group and the sprite follows.+- **The update** — call `Assets.checkForUpdate({ manifestUrl, remoteRoot })` to+ diff the CDN's manifest against the running one, then `Assets.applyUpdate()` to+ download the changed assets and swap the manifest. Existing handles bound to a+ changed asset are told to rebind. `Assets.restorePersistedUpdate(key)` at boot+ makes a returning player start on the already-updated content, even offline.++```ts+const plan = await assets.checkForUpdate({+ manifestUrl: 'https://cdn.example.com/asset-manifest.json',+ remoteRoot: 'https://cdn.example.com',+});+if (plan.hasUpdate) await assets.applyUpdate();+```++The whole path is content-addressed and platform-uniform: the same+`asset-manifest.json` + `loadGroup` + hot-update work on web, desktop, and+mini-games.++## Verify it++The engine ships an automated render check that proves the loop end-to-end —+cooks the game (green art), cooks a CDN update (red art), boots the shipped+runtime, asserts it draws **green**, drives the update, and asserts it draws+**red**:++```+pnpm --filter @estella/editor verify:render:hotupdate+```diff --git a/examples/hot-update-demo/assets/scenes/main.esscene b/examples/hot-update-demo/assets/scenes/main.esscenenew file mode 100644index 000000000..dfa9356ac--- /dev/null+++ b/examples/hot-update-demo/assets/scenes/main.esscene@@ -0,0 +1,29 @@+{+ "version": "1.0",+ "name": "Main",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }+ ]+ },+ {+ "id": 1,+ "name": "Display",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 4000, "y": 4000 }, "color": { "r": 1, "g": 1, "b": 1, "a": 1 } } },+ { "type": "HotDisplay", "data": {} }+ ]+ }+ ]+}diff --git a/examples/hot-update-demo/assets/scenes/main.esscene.meta b/examples/hot-update-demo/assets/scenes/main.esscene.metanew file mode 100644index 000000000..7ee49ab88--- /dev/null+++ b/examples/hot-update-demo/assets/scenes/main.esscene.meta@@ -0,0 +1,8 @@+{+ "uuid": "a1b2c3d4-0001-4001-8001-000000000001",+ "version": "2.0",+ "type": "scene",+ "importer": {+ "autoMigrate": true+ }+}diff --git a/examples/hot-update-demo/project.esproject b/examples/hot-update-demo/project.esprojectnew file mode 100644index 000000000..511e929e7--- /dev/null+++ b/examples/hot-update-demo/project.esproject@@ -0,0 +1,10 @@+{+ "formatVersion": "1",+ "name": "Hot Update Demo",+ "description": "Loads a texture from a `remote` (CDN) group and hot-swaps it live — no re-ship.",+ "tag": "Advanced",+ "version": "0.1.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": { "width": 800, "height": 600 },+ "spineVersion": "none"+}diff --git a/examples/hot-update-demo/remote/cdn/art.png b/examples/hot-update-demo/remote/cdn/art.pngnew file mode 100644index 000000000..882038bf7Binary files /dev/null and b/examples/hot-update-demo/remote/cdn/art.png differdiff --git a/examples/hot-update-demo/remote/cdn/art.png.meta b/examples/hot-update-demo/remote/cdn/art.png.metanew file mode 100644index 000000000..70e180c90--- /dev/null+++ b/examples/hot-update-demo/remote/cdn/art.png.meta@@ -0,0 +1,12 @@+{+ "uuid": "a1b2c3d4-0002-4002-8002-000000000002",+ "version": "2.0",+ "type": "texture",+ "importer": {+ "maxSize": 2048,+ "filterMode": "linear",+ "wrapMode": "clamp",+ "premultiplyAlpha": false,+ "sliceBorder": { "left": 0, "right": 0, "top": 0, "bottom": 0 }+ }+}diff --git a/examples/hot-update-demo/src/components.ts b/examples/hot-update-demo/src/components.tsnew file mode 100644index 000000000..d62d29633--- /dev/null+++ b/examples/hot-update-demo/src/components.ts@@ -0,0 +1,7 @@+import { defineComponent } from 'esengine';++/** Tag for the entity whose Sprite shows the CDN-delivered texture. `updates`+ * counts how many hot updates have been applied (handy to read back in tests). */+export const HotDisplay = defineComponent('HotDisplay', {+ updates: 0,+});diff --git a/examples/hot-update-demo/src/main.ts b/examples/hot-update-demo/src/main.tsnew file mode 100644index 000000000..3bf3e6685--- /dev/null+++ b/examples/hot-update-demo/src/main.ts@@ -0,0 +1,6 @@+import { addSystemToSchedule, Schedule } from 'esengine';++import './components';+import { hotDisplaySystem } from './systems/hotUpdate';++addSystemToSchedule(Schedule.Update, hotDisplaySystem);diff --git a/examples/hot-update-demo/src/systems/hotUpdate.ts b/examples/hot-update-demo/src/systems/hotUpdate.tsnew file mode 100644index 000000000..4ee5e0bee--- /dev/null+++ b/examples/hot-update-demo/src/systems/hotUpdate.ts@@ -0,0 +1,33 @@+import { defineSystem, Query, Mut, Res, Assets, Sprite } from 'esengine';+import { HotDisplay } from '../components';++// The texture handle currently loaded from the `cdn` remote group. The system+// stamps it onto the display sprite every frame, so when a hot update reloads+// the group into a NEW handle, the sprite follows automatically.+let cdnHandle = 0;+let started = false;++export const hotDisplaySystem = defineSystem(+ [Query(Mut(Sprite), HotDisplay), Res(Assets)],+ (query, assets) => {+ if (!started) {+ started = true;+ // Load the single texture in the `cdn` remote group. Re-run on every+ // hot update: after applyUpdate the manifest points `cdn` at the new+ // content-addressed url, so this fetches the fresh bytes.+ const load = (): void => {+ void assets.loadGroup('cdn').then((bundle) => {+ const tex = [...bundle.textures.values()][0];+ if (tex) cdnHandle = tex.handle;+ });+ };+ load();+ // A hot update (checkForUpdate → applyUpdate) fires onInvalidate.+ assets.onInvalidate(load);+ }+ if (cdnHandle !== 0) {+ for (const [, sprite] of query) sprite.texture = cdnHandle;+ }+ },+ { name: 'HotDisplaySystem' },+);diff --git a/examples/hot-update-demo/tsconfig.json b/examples/hot-update-demo/tsconfig.jsonnew file mode 100644index 000000000..0a8528b29--- /dev/null+++ b/examples/hot-update-demo/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "esengine": ["./.esengine/sdk/index.d.ts"],+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]+ }+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules"]+}diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex a86677683..40363a7a8 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -66,6 +66,7 @@ _filterType: "added"## AddressableManifest — interface```groups: Record<string, AddressableManifestGroup>+revision: string | undefinedversion: "2.0"```@@ -3615,11 +3616,13 @@ assetPathsInGroup: (name: string) => string[]assetsByLabel: (label: string) => AddressableManifestAsset[]assetsInGroup: (name: string) => AddressableManifestAsset[]bundleMode: (name: string) => BundleMode+entries: () => Array<{ group: string; key: string; asset: AddressableManifestAsset; }>findAsset: (pathOrAddress: string) => AddressableManifestAsset | nullgroup: (name: string) => AddressableManifestGroup | nullgroupNames: () => string[]groupsByMode: (mode: BundleMode) => string[]resolvePath: (ref: string, normalize?: (ref: string) => string) => string+revision: () => string | nullstatic empty: () => ManifestModelstatic fromJson: (manifest: AddressableManifest) => ManifestModelstatic new (manifest: AddressableManifest): ManifestModeldiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex a422dca26..802230263 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -61,6 +61,7 @@ _filterType: "added"## AddressableManifest — interface```groups: Record<string, AddressableManifestGroup>+revision: string | undefinedversion: "2.0"```@@ -3610,11 +3611,13 @@ assetPathsInGroup: (name: string) => string[]assetsByLabel: (label: string) => AddressableManifestAsset[]assetsInGroup: (name: string) => AddressableManifestAsset[]bundleMode: (name: string) => BundleMode+entries: () => Array<{ group: string; key: string; asset: AddressableManifestAsset; }>findAsset: (pathOrAddress: string) => AddressableManifestAsset | nullgroup: (name: string) => AddressableManifestGroup | nullgroupNames: () => string[]groupsByMode: (mode: BundleMode) => string[]resolvePath: (ref: string, normalize?: (ref: string) => string) => string+revision: () => string | nullstatic empty: () => ManifestModelstatic fromJson: (manifest: AddressableManifest) => ManifestModelstatic new (manifest: AddressableManifest): ManifestModeldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 6247ba61a..33d74f54b 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -61,6 +61,7 @@ _filterType: "added"## AddressableManifest — interface```groups: Record<string, AddressableManifestGroup>+revision: string | undefinedversion: "2.0"```@@ -3617,11 +3618,13 @@ assetPathsInGroup: (name: string) => string[]assetsByLabel: (label: string) => AddressableManifestAsset[]assetsInGroup: (name: string) => AddressableManifestAsset[]bundleMode: (name: string) => BundleMode+entries: () => Array<{ group: string; key: string; asset: AddressableManifestAsset; }>findAsset: (pathOrAddress: string) => AddressableManifestAsset | nullgroup: (name: string) => AddressableManifestGroup | nullgroupNames: () => string[]groupsByMode: (mode: BundleMode) => string[]resolvePath: (ref: string, normalize?: (ref: string) => string) => string+revision: () => string | nullstatic empty: () => ManifestModelstatic fromJson: (manifest: AddressableManifest) => ManifestModelstatic new (manifest: AddressableManifest): ManifestModeldiff --git a/sdk/src/asset/AddressableManifest.ts b/sdk/src/asset/AddressableManifest.tsindex e49db8ad9..709b35c42 100644--- a/sdk/src/asset/AddressableManifest.ts+++ b/sdk/src/asset/AddressableManifest.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { AddressableAssetType } from '../assetTypes';+import { contentHashOf } from './contentHash';export type { AddressableAssetType };@@ -38,9 +39,38 @@ export interface AddressableManifestGroup {export interface AddressableManifest {version: '2.0';+ /**+ * Build content revision — a stable hash over every asset's `contentHash`+ * (see {@link deriveManifestRevision}). Two builds share a revision iff they+ * ship byte-identical content under the same addressable keys, so a+ * changed / added / removed asset flips it. It is the fast gate for "is there+ * an update?"; the per-asset `contentHash` diff stays authoritative on WHAT+ * changed. Optional — absent on legacy manifests, where the diff falls back+ * to comparing contentHashes (or build paths) directly.+ */+ revision?: string;groups: Record<string, AddressableManifestGroup>;}+/**+ * Stable content revision of a manifest: XXH64 over every asset's sorted+ * `<group>\t<key>\t<contentHash>` line. Deterministic and order-independent, so+ * two cooks of identical content produce the same string and any content / set+ * change flips it. A BUILD-TIME helper (rides {@link contentHashOf}'s+ * `TextEncoder`); the runtime reads the emitted `revision` field and never+ * recomputes it.+ */+export function deriveManifestRevision(manifest: AddressableManifest): string {+ const lines: string[] = [];+ for (const [groupName, group] of Object.entries(manifest.groups)) {+ for (const [key, asset] of Object.entries(group.assets)) {+ lines.push(`${groupName}\t${key}\t${asset.contentHash ?? ''}`);+ }+ }+ lines.sort();+ return contentHashOf(lines.join('\n'));+}+/*** Delivery mode for an addressable group — the single typed source of truth for* what was historically a bare `bundleMode: string` scattered across the cook /@@ -121,6 +151,24 @@ export class ManifestModel {return out;}+ /** Every asset carrying its owning group name and record key — the iteration+ * the hot-update diff walks (allAssets() drops both). */+ entries(): Array<{ group: string; key: string; asset: AddressableManifestAsset }> {+ const out: Array<{ group: string; key: string; asset: AddressableManifestAsset }> = [];+ for (const [group, g] of Object.entries(this.manifest.groups)) {+ for (const [key, asset] of Object.entries(g.assets)) {+ out.push({ group, key, asset });+ }+ }+ return out;+ }++ /** The manifest's build content revision (see {@link deriveManifestRevision}),+ * or null on a legacy manifest that predates the field. */+ revision(): string | null {+ return this.manifest.revision ?? null;+ }+/** Assets carrying `label` across all groups, deduped by path. */assetsByLabel(label: string): AddressableManifestAsset[] {const seen = new Set<string>();diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex af028a708..4301759d7 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -2,8 +2,9 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { Backend } from './Backend';import { Catalog, type AtlasFrameInfo } from './Catalog';-import { ManifestModel, type AddressableManifest } from './AddressableManifest';-import { platformLoadSubpackage } from '../platform';+import { ManifestModel, normalizeBundleMode, type AddressableManifest } from './AddressableManifest';+import { diffManifests, type UpdatePlan, type AssetChange } from './hotUpdate';+import { platformLoadSubpackage, platformGetStorageItem, platformSetStorageItem } from '../platform';import type {AssetLoader, LoadContext, TextureResult, SpineResult,MaterialResult, FontResult, AudioResult, AnimClipResult,@@ -43,6 +44,23 @@ import { log } from '../logger';/** Callback fired when `Assets.invalidate(ref)` actually dropped cache entries. */export type InvalidateListener = (ref: string) => void;+/** Input to {@link Assets.checkForUpdate}. */+export interface CheckForUpdateOptions {+ /** Url of the candidate (remote) manifest JSON — diffed against the active one. */+ manifestUrl: string;+ /** CDN root the candidate's `remote`-group assets are served from; remembered+ * and applied by {@link Assets.applyUpdate}. Defaults to the current root. */+ remoteRoot?: string;+}++/** The manifest + root staged by checkForUpdate, awaiting applyUpdate. */+interface PendingUpdate {+ plan: UpdatePlan;+ model: ManifestModel;+ manifestJson: AddressableManifest;+ remoteRoot: string | null;+}+/*** Default upper bound on concurrent loads inside preloadSceneAssets.* Picked to match typical browser per-origin connection limits; scenes@@ -158,6 +176,13 @@ export class Assets {private module_: ESEngineModule;private manifestModel_: ManifestModel | null = null;+ /** CDN root that `remote`-group assets resolve against; see {@link setRemoteRoot}. */+ private remoteRoot_?: string;+ /** The update staged by {@link checkForUpdate}, consumed by {@link applyUpdate}. */+ private pendingUpdate_: PendingUpdate | null = null;+ /** Storage key {@link applyUpdate} persists the active manifest under; set by+ * {@link restorePersistedUpdate}. Null → persistence off. */+ private persistKey_: string | null = null;private getAudio_: () => import('../audio/Audio').AudioAPI | null;private getSpriteAnimation_: () => import('../animation/SpriteAnimator').SpriteAnimationAPI | null;private getLocalization_: () => import('../i18n/Localization').LocalizationAPI | null;@@ -474,9 +499,10 @@ export class Assets {return bundle;}+ const mode = model.bundleMode(groupName);// A lazy group is an on-demand subpackage — download it before loading its// assets (no-op on platforms without a subpackage concept, e.g. web).- if (model.bundleMode(groupName) === 'lazy') {+ if (mode === 'lazy') {await platformLoadSubpackage(groupName);}@@ -487,7 +513,12 @@ export class Assets {.catch(() => { onProgress?.(++loadedCount, totalCount); });for (const asset of model.assetsInGroup(groupName)) {- const path = this.resolveLoadPath_(asset.path);+ // A remote group's assets live on the CDN, not in the package: resolve+ // to the absolute `<remoteRoot>/<contentHash>.<ext>` url (the backend+ // passes absolute urls through). Local / lazy assets resolve normally.+ const path = mode === 'remote'+ ? this.remoteUrlFor_(asset.path)+ : this.resolveLoadPath_(asset.path);const task = this.groupLoadTask_(path, asset.type, bundle);if (task) promises.push(track(task));}@@ -533,6 +564,136 @@ export class Assets {}}+ // =========================================================================+ // Hot Update (content-addressed remote delivery)+ // =========================================================================++ /** The CDN / remote root that `remote`-group assets resolve against. */+ get remoteRoot(): string | undefined { return this.remoteRoot_; }++ /** Point `remote`-group resolution at a CDN root: their content-addressed+ * paths then fetch from `<root>/<path>`. A trailing slash is trimmed;+ * `undefined` clears it (same-origin fallback). */+ setRemoteRoot(url: string | undefined): void {+ this.remoteRoot_ = url ? url.replace(/\/+$/, '') : undefined;+ }++ /** Absolute url of a `remote`-group asset. An already-absolute manifest path+ * (a fully-qualified CDN url) passes through; otherwise it joins the remote+ * root. With no root set the path returns as-is (same-origin fallback). */+ private remoteUrlFor_(path: string): string {+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path)) return path;+ if (!this.remoteRoot_) return path;+ return `${this.remoteRoot_}/${path.replace(/^\/+/, '')}`;+ }++ /**+ * Fetch a candidate manifest and diff it against the active one WITHOUT+ * applying anything — the "is there an update, and how big?" query. The+ * returned plan (changed assets + byte total) is what a UI shows before+ * asking the player to download; the candidate is staged for {@link applyUpdate}.+ *+ * Diffing is by content hash (see {@link diffManifests}); because assets are+ * content-addressed, a changed asset is a brand-new url, so applying can never+ * overwrite or corrupt a cached file.+ */+ async checkForUpdate(options: CheckForUpdateOptions): Promise<UpdatePlan> {+ const text = await this.backend.fetchText(this.backend.resolveUrl(options.manifestUrl));+ const json = JSON.parse(text) as AddressableManifest;+ const model = ManifestModel.fromJson(json);+ const plan = diffManifests(this.manifestModel_, model);+ const remoteRoot = options.remoteRoot ?? this.remoteRoot_ ?? null;+ this.pendingUpdate_ = { plan, model, manifestJson: json, remoteRoot };+ return plan;+ }++ /**+ * Apply the update staged by the last {@link checkForUpdate}: point remote+ * resolution at its root, make its manifest active, download the changed+ * (content-addressed) assets from the CDN with progress, notify live handles+ * bound to a changed asset to rebind (via the `onInvalidate` channel), and+ * persist the manifest so a returning player boots on it. No-op with nothing+ * staged.+ */+ async applyUpdate(onProgress?: (loaded: number, total: number) => void): Promise<void> {+ const pending = this.pendingUpdate_;+ if (!pending) {+ log.warn('asset', 'applyUpdate() called with no pending update — call checkForUpdate first');+ onProgress?.(0, 0);+ return;+ }+ // Swap FIRST so changed assets resolve to their new remote urls, then warm+ // them. Content addressing makes the download purely additive to the cache.+ if (pending.remoteRoot != null) this.setRemoteRoot(pending.remoteRoot);+ this.setManifest(pending.model);++ const changed = pending.plan.changedAssets;+ let done = 0;+ onProgress?.(0, changed.length);+ const tasks = changed.map((c) => async (): Promise<void> => {+ try {+ await this.downloadChangedAsset_(c);+ } catch (e) {+ log.warn('asset', `applyUpdate: failed to fetch ${c.path}`, e);+ }+ });+ await runWithConcurrency(tasks, DEFAULT_PRELOAD_CONCURRENCY, () => {+ onProgress?.(++done, changed.length);+ });++ // Rebind: tell renderers holding a stale handle for a changed asset to+ // re-resolve it against the now-active manifest → the freshly-warmed+ // content. Old, differently-keyed handles orphan and release by refcount.+ for (const c of changed) this.fireInvalidate_(c.key);++ this.persistActiveManifest_(pending.manifestJson);+ this.pendingUpdate_ = null;+ }++ /** Warm one changed asset from its group's delivery source (remote → CDN url,+ * else the normal resolved path) through its typed loader. */+ private downloadChangedAsset_(c: AssetChange): Promise<unknown> {+ const group = this.manifestModel_?.group(c.group);+ const remote = group != null && normalizeBundleMode(group.bundleMode) === 'remote';+ const path = remote ? this.remoteUrlFor_(c.path) : this.resolveLoadPath_(c.path);+ const load = this.typedLoadFor_(path, c.type);+ return load ? load() : Promise.resolve();+ }++ /**+ * Remember a storage key under which {@link applyUpdate} persists the active+ * manifest, and immediately restore any manifest a prior run persisted there —+ * so a returning player boots straight onto the updated content, even offline.+ * Returns true if a persisted manifest was found and made active. Call at+ * boot, before the first scene loads.+ */+ restorePersistedUpdate(key: string): boolean {+ this.persistKey_ = key;+ const raw = platformGetStorageItem(key);+ if (!raw) return false;+ try {+ const parsed = JSON.parse(raw) as { manifest: AddressableManifest; remoteRoot?: string | null };+ if (parsed.remoteRoot) this.setRemoteRoot(parsed.remoteRoot);+ this.setManifest(parsed.manifest);+ return true;+ } catch (e) {+ log.warn('asset', 'failed to restore persisted manifest', e);+ return false;+ }+ }++ private persistActiveManifest_(json: AddressableManifest): void {+ if (!this.persistKey_) return;+ try {+ platformSetStorageItem(+ this.persistKey_,+ JSON.stringify({ manifest: json, remoteRoot: this.remoteRoot_ ?? null }),+ );+ } catch (e) {+ log.warn('asset', 'failed to persist updated manifest', e);+ }+ }+/*** Load one asset into the displayable bundle maps. Returns the in-flight* promise for the four bundle-able types (texture / material / spine /@@ -1023,19 +1184,24 @@ export class Assets {if (p === path) this.handleToPath_.delete(key);}- if (hit) {- for (const listener of this.invalidateListeners_) {- try {- listener(ref);- } catch (e) {- log.warn('asset', 'onInvalidate listener threw', e);- }- }- }+ if (hit) this.fireInvalidate_(ref);return hit;}+ /** Fire every onInvalidate listener with `ref`, isolating throws. Shared by+ * {@link invalidate} (cache drop) and {@link applyUpdate} (rebind to updated+ * content), so both notify subscribers through one path. */+ private fireInvalidate_(ref: string): void {+ for (const listener of this.invalidateListeners_) {+ try {+ listener(ref);+ } catch (e) {+ log.warn('asset', 'onInvalidate listener threw', e);+ }+ }+ }+/*** Subscribe to cache invalidations. The listener fires once per* successful `invalidate(ref)` call with the original ref (not thediff --git a/sdk/src/asset/hotUpdate.ts b/sdk/src/asset/hotUpdate.tsnew file mode 100644index 000000000..886438a29--- /dev/null+++ b/sdk/src/asset/hotUpdate.ts@@ -0,0 +1,110 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file hotUpdate.ts+ * @brief Pure manifest-diff core for content-addressed hot updates.+ *+ * The runtime hot-update flow is: fetch the remote manifest → {@link diffManifests}+ * it against the active one → download the changed (content-addressed) assets →+ * swap the active manifest. Because every asset url is `<contentHash>.<ext>`+ * (immutable), a changed asset is a NEW url: the diff is a pure comparison of+ * per-asset `contentHash`, and applying it never overwrites or invalidates a+ * cached file — the old url simply stops being referenced.+ *+ * This module is pure — no fetch, no platform, no Assets — so it unit-tests in+ * isolation and the SAME diff drives every platform (web / mini-game / native).+ */+import type { ManifestModel } from './AddressableManifest';+import type { AddressableAssetType, AddressableManifestAsset } from './AddressableManifest';++/** One asset the update touches, resolved to what the downloader needs. */+export interface AssetChange {+ /** Group-record key (uuid in cooked manifests, else path) — the stable+ * cross-build identity the diff matches on. */+ key: string;+ /** Build path of the asset in the NEW manifest (content-addressed → the+ * immutable url tail the downloader appends to the remote root). */+ path: string;+ /** Owning group in the new manifest. */+ group: string;+ type: AddressableAssetType;+ size: number;+ contentHash?: string;+}++/** The result of comparing an active manifest to a candidate one. */+export interface UpdatePlan {+ /** True iff any asset is new / content-changed (or, absent contentHashes on+ * both sides, the top-level revision moved). */+ hasUpdate: boolean;+ fromRevision: string | null;+ toRevision: string | null;+ /** Distinct groups owning ≥1 changed / added asset — the set to re-load. */+ changedGroups: string[];+ /** New or content-changed assets to download. */+ changedAssets: AssetChange[];+ /** Assets present before but absent now — informational, for cache cleanup;+ * never downloaded. */+ removedAssets: AssetChange[];+ /** Sum of `changedAssets` sizes: the download-size estimate for UI/progress. */+ totalBytes: number;+}++function toChange(group: string, key: string, asset: AddressableManifestAsset): AssetChange {+ const change: AssetChange = {+ key, group, path: asset.path, type: asset.type, size: asset.size ?? 0,+ };+ if (asset.contentHash != null) change.contentHash = asset.contentHash;+ return change;+}++/**+ * Compare the active manifest to `next` and produce the download plan.+ *+ * Matching is by group-record key (stable per asset across builds). An asset is+ * "changed" when it is brand-new, or its content differs — authoritatively by+ * `contentHash` when both sides carry one, else by build path. `current === null`+ * (no manifest yet, e.g. first launch off a persisted-manifest miss) treats every+ * asset as new — a full fetch.+ */+export function diffManifests(current: ManifestModel | null, next: ManifestModel): UpdatePlan {+ const changedAssets: AssetChange[] = [];+ const changedGroups = new Set<string>();+ let totalBytes = 0;++ for (const { group, key, asset } of next.entries()) {+ const prev = current?.assetByKey(key) ?? null;+ const changed = !prev+ || (asset.contentHash != null && prev.contentHash != null+ ? asset.contentHash !== prev.contentHash+ : asset.path !== prev.path);+ if (changed) {+ changedAssets.push(toChange(group, key, asset));+ changedGroups.add(group);+ totalBytes += asset.size ?? 0;+ }+ }++ const removedAssets: AssetChange[] = [];+ if (current) {+ const nextKeys = new Set(next.entries().map((e) => e.key));+ for (const { group, key, asset } of current.entries()) {+ if (!nextKeys.has(key)) removedAssets.push(toChange(group, key, asset));+ }+ }++ const fromRevision = current?.revision() ?? null;+ const toRevision = next.revision() ?? null;+ const hasUpdate = changedAssets.length > 0+ || (fromRevision != null && toRevision != null && fromRevision !== toRevision);++ return {+ hasUpdate,+ fromRevision,+ toRevision,+ changedGroups: [...changedGroups],+ changedAssets,+ removedAssets,+ totalBytes,+ };+}diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.tsindex 244582407..9b4b8e3b4 100644--- a/sdk/src/asset/index.ts+++ b/sdk/src/asset/index.ts@@ -8,15 +8,17 @@ export {type BundleMode,BUNDLE_MODES,normalizeBundleMode,+ deriveManifestRevision,ManifestModel,} from './AddressableManifest';+export { diffManifests, type UpdatePlan, type AssetChange } from './hotUpdate';export { xxh64, contentHashHex, contentHashOf } from './contentHash';export { AsyncCache } from './AsyncCache';export { Assets, AssetPlugin, assetPlugin, type AssetsData } from './AssetPlugin';export { decodeImageBitmap, decodeImagePixels, imageBitmapOptions, type DecodedPixels } from './imageDecode';export { AssetRefCounter, type AssetRefInfo } from './AssetRefCounter';-export { Assets as AssetsImpl, type AssetsOptions, type AssetBundle, type SceneAssetResult, type MissingAsset } from './Assets';+export { Assets as AssetsImpl, type AssetsOptions, type AssetBundle, type SceneAssetResult, type MissingAsset, type CheckForUpdateOptions, type InvalidateListener } from './Assets';export { type Backend, HttpBackend, EmbeddedBackend, type HttpBackendOptions } from './Backend';export { Catalog, atlasCatalogFields, type CatalogData, type CatalogEntry, type AtlasFrameInfo, type CookedAtlasInfo } from './Catalog';export {diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex 5301431ac..df61e200d 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -140,6 +140,21 @@ export function platformOnMemoryWarning(callback: () => void): () => void {return p.onMemoryWarning ? p.onMemoryWarning(callback) : () => {};}+/** Read a persisted string by key (adapter storage: localStorage on web,+ * `wx.getStorageSync` on WeChat). Returns null when the key is absent OR the+ * platform is uninitialized (tests) — callers treat both as "nothing stored". */+export function platformGetStorageItem(key: string): string | null {+ if (!isPlatformInitialized()) return null;+ return getPlatform().getStorageItem(key);+}++/** Persist a string by key through the adapter's storage. No-op when the platform+ * is uninitialized (tests), so persistence is a safe best-effort everywhere. */+export function platformSetStorageItem(key: string, value: string): void {+ if (!isPlatformInitialized()) return;+ getPlatform().setStorageItem(key, value);+}+export function platformDevicePixelRatio(): number {if (currentPlatform) {return currentPlatform.devicePixelRatio();diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.tsindex 5bab9ab14..0986c0b6c 100644--- a/sdk/src/platform/index.ts+++ b/sdk/src/platform/index.ts@@ -36,6 +36,8 @@ export {platformCreateAudioBackend,platformLoadSubpackage,platformOnMemoryWarning,+ platformGetStorageItem,+ platformSetStorageItem,platformDevicePixelRatio,platformLanguage,} from './base';diff --git a/sdk/src/playRealmRuntime.ts b/sdk/src/playRealmRuntime.tsindex d4ce9f308..3303ef91d 100644--- a/sdk/src/playRealmRuntime.ts+++ b/sdk/src/playRealmRuntime.ts@@ -60,6 +60,10 @@ export interface PlayRealmRuntimeConfig {*/catalogData?: CatalogData | null;manifest?: AddressableManifest | null;+ /** CDN root `remote`-group assets resolve against — turns on hot-update delivery. */+ remoteRoot?: string;+ /** Storage key an applied hot-update persists under; boot restores it if present. */+ persistUpdateKey?: string;/** Base URL the engine side-modules (physics.wasm, …) are served from — same* dir as esengine.wasm. When set, the realm can load physics on demand. */wasmBaseUrl?: string;@@ -178,6 +182,9 @@ export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Promapp,module,source,+ manifest: config.manifest,+ remoteRoot: config.remoteRoot,+ persistUpdateKey: config.persistUpdateKey,catalog: config.catalogData ? Catalog.fromJson(config.catalogData) : undefined,scenes: [{ name: entryName, data: sceneData },diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex c7da5c104..58e95b0be 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -393,6 +393,13 @@ export interface RuntimeInitConfig {* existed before initRuntime, which the runtime instance replaces.*/manifest?: AddressableManifest | ManifestModel | null;+ /** CDN root that `remote`-group assets resolve against ({@link Assets.setRemoteRoot}) —+ * enables hot-update delivery from a remote origin. */+ remoteRoot?: string;+ /** Storage key an applied hot-update persists the manifest under. When set,+ * initRuntime restores any manifest a prior run persisted there — a returning+ * player boots on the updated content ({@link Assets.restorePersistedUpdate}). */+ persistUpdateKey?: string;/*** Logical-path → build-path catalog for cooked builds (content-addressed* staging renames physical files): loaders route their inner text refs (a@@ -434,6 +441,10 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {// return the existing instance).const assets = ensureRuntimeAssets(app, config.module, config.source, config.catalog);if (config.manifest) assets.setManifest(config.manifest);+ if (config.remoteRoot) assets.setRemoteRoot(config.remoteRoot);+ // A persisted update (from a prior applyUpdate) supersedes the shipped manifest+ // + root, so a returning player boots straight onto the already-updated content.+ if (config.persistUpdateKey) assets.restorePersistedUpdate(config.persistUpdateKey);if (config.audioConfig && app.hasResource(Audio)) {applyAudioProjectConfig(app.getResource(Audio), config.audioConfig);diff --git a/sdk/tests/hot-update-diff.test.ts b/sdk/tests/hot-update-diff.test.tsnew file mode 100644index 000000000..971c8d1f3--- /dev/null+++ b/sdk/tests/hot-update-diff.test.ts@@ -0,0 +1,140 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import {+ ManifestModel,+ deriveManifestRevision,+ type AddressableManifest,+ type AddressableManifestAsset,+} from '../src/asset/AddressableManifest';+import { diffManifests } from '../src/asset/hotUpdate';++/** A one-`remote`-group manifest keyed by uuid, as a cooked build emits. Each+ * call site overrides individual assets to model a re-cook. */+function manifest(+ assets: Record<string, Partial<AddressableManifestAsset>>,+ revision?: string,+): AddressableManifest {+ const full: Record<string, AddressableManifestAsset> = {};+ for (const [key, a] of Object.entries(assets)) {+ full[key] = {+ path: a.path ?? `assets/${key}.png`,+ type: a.type ?? 'texture',+ size: a.size ?? 1,+ labels: a.labels ?? [],+ ...(a.contentHash != null ? { contentHash: a.contentHash } : {}),+ };+ }+ const m: AddressableManifest = {+ version: '2.0',+ groups: { cdn: { bundleMode: 'remote', labels: [], assets: full } },+ };+ if (revision != null) m.revision = revision;+ return m;+}++const model = (m: AddressableManifest) => ManifestModel.fromJson(m);++describe('deriveManifestRevision', () => {+ it('is stable across group/asset ordering', () => {+ const a = deriveManifestRevision(manifest({+ 'uuid-1': { contentHash: 'aaaa' }, 'uuid-2': { contentHash: 'bbbb' },+ }));+ const b = deriveManifestRevision(manifest({+ 'uuid-2': { contentHash: 'bbbb' }, 'uuid-1': { contentHash: 'aaaa' },+ }));+ expect(a).toBe(b);+ });++ it('changes when any asset content changes', () => {+ const a = deriveManifestRevision(manifest({ 'uuid-1': { contentHash: 'aaaa' } }));+ const b = deriveManifestRevision(manifest({ 'uuid-1': { contentHash: 'cccc' } }));+ expect(a).not.toBe(b);+ });++ it('changes when the asset set changes', () => {+ const a = deriveManifestRevision(manifest({ 'uuid-1': { contentHash: 'aaaa' } }));+ const b = deriveManifestRevision(manifest({+ 'uuid-1': { contentHash: 'aaaa' }, 'uuid-2': { contentHash: 'bbbb' },+ }));+ expect(a).not.toBe(b);+ });+});++describe('diffManifests', () => {+ it('treats a null current manifest as a full update (first install)', () => {+ const next = model(manifest({+ 'uuid-1': { contentHash: 'aaaa', size: 10 },+ 'uuid-2': { contentHash: 'bbbb', size: 20 },+ }));+ const plan = diffManifests(null, next);+ expect(plan.hasUpdate).toBe(true);+ expect(plan.changedAssets).toHaveLength(2);+ expect(plan.changedGroups).toEqual(['cdn']);+ expect(plan.totalBytes).toBe(30);+ expect(plan.removedAssets).toEqual([]);+ });++ it('reports no update for identical manifests', () => {+ const m = () => model(manifest(+ { 'uuid-1': { contentHash: 'aaaa' } }, 'rev-1',+ ));+ const plan = diffManifests(m(), m());+ expect(plan.hasUpdate).toBe(false);+ expect(plan.changedAssets).toEqual([]);+ expect(plan.changedGroups).toEqual([]);+ expect(plan.totalBytes).toBe(0);+ });++ it('detects a single content-changed asset by contentHash (path unchanged)', () => {+ const current = model(manifest({+ 'uuid-1': { contentHash: 'aaaa', path: 'assets/logo.png', size: 5 },+ 'uuid-2': { contentHash: 'bbbb', size: 7 },+ }));+ // Re-cook: uuid-1's bytes changed. Content addressing would rename the+ // file, but even a fixed-path (non-CA) asset is caught via contentHash.+ const next = model(manifest({+ 'uuid-1': { contentHash: 'zzzz', path: 'assets/logo.png', size: 6 },+ 'uuid-2': { contentHash: 'bbbb', size: 7 },+ }));+ const plan = diffManifests(current, next);+ expect(plan.hasUpdate).toBe(true);+ expect(plan.changedAssets.map((c) => c.key)).toEqual(['uuid-1']);+ expect(plan.changedAssets[0].contentHash).toBe('zzzz');+ expect(plan.totalBytes).toBe(6);+ });++ it('reports an added asset as changed and a dropped asset as removed', () => {+ const current = model(manifest({ 'uuid-1': { contentHash: 'aaaa' } }));+ const next = model(manifest({+ 'uuid-1': { contentHash: 'aaaa' }, 'uuid-3': { contentHash: 'dddd', size: 4 },+ }));+ const added = diffManifests(current, next);+ expect(added.changedAssets.map((c) => c.key)).toEqual(['uuid-3']);+ expect(added.removedAssets).toEqual([]);++ const dropped = diffManifests(next, current);+ expect(dropped.changedAssets).toEqual([]);+ expect(dropped.removedAssets.map((c) => c.key)).toEqual(['uuid-3']);+ expect(dropped.hasUpdate).toBe(false); // nothing to download+ });++ it('falls back to build-path comparison when contentHashes are absent', () => {+ const current = model(manifest({ 'uuid-1': { path: 'assets/a-old.png' } }));+ const next = model(manifest({ 'uuid-1': { path: 'assets/a-new.png' } }));+ const plan = diffManifests(current, next);+ expect(plan.changedAssets.map((c) => c.path)).toEqual(['assets/a-new.png']);+ });++ it('signals hasUpdate on a revision move even if per-asset detection is blind', () => {+ // No contentHashes and identical paths → per-asset diff sees nothing, but+ // a moved top-level revision still flags that content shifted.+ const current = model(manifest({ 'uuid-1': { path: 'assets/a.png' } }, 'rev-1'));+ const next = model(manifest({ 'uuid-1': { path: 'assets/a.png' } }, 'rev-2'));+ const plan = diffManifests(current, next);+ expect(plan.changedAssets).toEqual([]);+ expect(plan.hasUpdate).toBe(true);+ expect(plan.fromRevision).toBe('rev-1');+ expect(plan.toRevision).toBe('rev-2');+ });+});diff --git a/sdk/tests/hot-update-runtime.test.ts b/sdk/tests/hot-update-runtime.test.tsnew file mode 100644index 000000000..7c2fca721--- /dev/null+++ b/sdk/tests/hot-update-runtime.test.ts@@ -0,0 +1,174 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, vi } from 'vitest';+import { Assets } from '../src/asset/Assets';+import { Catalog } from '../src/asset/Catalog';+import type { AddressableManifest } from '../src/asset/AddressableManifest';+import type { Backend } from '../src/asset/Backend';++const mockModule = {+ _malloc: vi.fn(() => 0),+ _free: vi.fn(),+ HEAPU8: new Uint8Array(1024),+ GL: null,+ FS: null,+} as any;++vi.mock('../src/resourceManager', () => ({+ requireResourceManager: () => ({+ createTexture: vi.fn(() => 42),+ releaseTexture: vi.fn(),+ invalidateTexturePath: vi.fn(() => false),+ }),+ getResourceManager: () => null,+ evictTextureDimensions: vi.fn(),+}));++// In-memory platform storage so persistence round-trips in the test.+vi.mock('../src/platform', () => {+ const store = new Map<string, string>();+ return {+ platformLoadSubpackage: vi.fn(() => Promise.resolve()),+ platformGetStorageItem: (k: string) => store.get(k) ?? null,+ platformSetStorageItem: (k: string, v: string) => { store.set(k, v); },+ __store: store,+ };+});++/** A cdn (`remote`) manifest keyed by uuid — the shape a cooked build emits.+ * `hash` overrides the single asset's contentHash + content-addressed path. */+function cdnManifest(hash: string, revision: string): AddressableManifest {+ return {+ version: '2.0',+ revision,+ groups: {+ cdn: {+ bundleMode: 'remote',+ labels: [],+ assets: {+ 'uuid-1': {+ path: `assets/${hash}.png`, address: 'assets/hero.png',+ type: 'texture', size: 10, labels: [], contentHash: hash,+ },+ },+ },+ },+ };+}++function createAssets(backend: Backend): Assets {+ return Assets.create({ backend, catalog: Catalog.empty(), module: mockModule });+}++function backendServing(manifestJson?: AddressableManifest): Backend {+ return {+ fetchBinary: vi.fn(async () => new ArrayBuffer(8)),+ fetchText: vi.fn(async () => (manifestJson ? JSON.stringify(manifestJson) : '{}')),+ resolveUrl: vi.fn((p: string) => p),+ } as any;+}++describe('Assets.loadGroup — remote group', () => {+ it('resolves remote assets against the CDN root (absolute url passthrough)', async () => {+ const assets = createAssets(backendServing());+ assets.setManifest(cdnManifest('aaaa', 'rev-1'));+ assets.setRemoteRoot('https://cdn.example.com/build/');+ const spy = vi.spyOn(assets, 'loadTexture')+ .mockResolvedValue({ handle: 1, width: 1, height: 1 } as any);++ await assets.loadGroup('cdn');++ expect(spy).toHaveBeenCalledWith('https://cdn.example.com/build/assets/aaaa.png');+ });++ it('trims a trailing slash on the root exactly once', async () => {+ const assets = createAssets(backendServing());+ assets.setManifest(cdnManifest('bbbb', 'rev-1'));+ assets.setRemoteRoot('https://cdn.example.com');+ const spy = vi.spyOn(assets, 'loadTexture')+ .mockResolvedValue({ handle: 1, width: 1, height: 1 } as any);++ await assets.loadGroup('cdn');++ expect(spy).toHaveBeenCalledWith('https://cdn.example.com/assets/bbbb.png');+ });+});++describe('Assets.checkForUpdate / applyUpdate', () => {+ it('checkForUpdate diffs the fetched manifest against the active one without applying', async () => {+ const assets = createAssets(backendServing(cdnManifest('zzzz', 'rev-2')));+ assets.setManifest(cdnManifest('aaaa', 'rev-1'));+ assets.setRemoteRoot('https://cdn/v1');++ const plan = await assets.checkForUpdate({ manifestUrl: 'asset-manifest.json', remoteRoot: 'https://cdn/v2' });++ expect(plan.hasUpdate).toBe(true);+ expect(plan.changedAssets.map((c) => c.key)).toEqual(['uuid-1']);+ expect(plan.totalBytes).toBe(10);+ expect(plan.fromRevision).toBe('rev-1');+ expect(plan.toRevision).toBe('rev-2');+ // Not applied yet: the active manifest and root are unchanged.+ expect(assets.getManifest()?.revision()).toBe('rev-1');+ expect(assets.remoteRoot).toBe('https://cdn/v1');+ });++ it('applyUpdate swaps the manifest+root, downloads changed assets, and notifies listeners', async () => {+ const assets = createAssets(backendServing(cdnManifest('zzzz', 'rev-2')));+ assets.setManifest(cdnManifest('aaaa', 'rev-1'));+ assets.setRemoteRoot('https://cdn/v1');+ const spy = vi.spyOn(assets, 'loadTexture')+ .mockResolvedValue({ handle: 2, width: 1, height: 1 } as any);+ const rebinds: string[] = [];+ assets.onInvalidate((ref) => rebinds.push(ref));++ await assets.checkForUpdate({ manifestUrl: 'asset-manifest.json', remoteRoot: 'https://cdn/v2' });+ const progress: [number, number][] = [];+ await assets.applyUpdate((loaded, total) => progress.push([loaded, total]));++ // Manifest + root are now the update's.+ expect(assets.getManifest()?.revision()).toBe('rev-2');+ expect(assets.remoteRoot).toBe('https://cdn/v2');+ // The changed asset was fetched from the NEW cdn root.+ expect(spy).toHaveBeenCalledWith('https://cdn/v2/assets/zzzz.png');+ // A renderer bound to the changed asset's stable key is told to rebind.+ expect(rebinds).toEqual(['uuid-1']);+ expect(progress[0]).toEqual([0, 1]);+ expect(progress[progress.length - 1]).toEqual([1, 1]);+ });++ it('applyUpdate is a no-op without a prior checkForUpdate', async () => {+ const assets = createAssets(backendServing());+ assets.setManifest(cdnManifest('aaaa', 'rev-1'));+ const progress: [number, number][] = [];+ await assets.applyUpdate((l, t) => progress.push([l, t]));+ expect(assets.getManifest()?.revision()).toBe('rev-1');+ expect(progress).toContainEqual([0, 0]);+ });+});++describe('Assets.restorePersistedUpdate', () => {+ it('persists an applied update and restores it into a fresh Assets', async () => {+ const backend = backendServing(cdnManifest('zzzz', 'rev-2'));+ const first = createAssets(backend);+ first.setManifest(cdnManifest('aaaa', 'rev-1'));+ first.setRemoteRoot('https://cdn/v1');+ vi.spyOn(first, 'loadTexture').mockResolvedValue({ handle: 1, width: 1, height: 1 } as any);++ // Arm persistence (nothing stored yet → false), then update.+ expect(first.restorePersistedUpdate('hotupdate:demo')).toBe(false);+ await first.checkForUpdate({ manifestUrl: 'asset-manifest.json', remoteRoot: 'https://cdn/v2' });+ await first.applyUpdate();++ // A returning player boots a fresh Assets straight onto the updated manifest.+ const second = createAssets(backendServing());+ const restored = second.restorePersistedUpdate('hotupdate:demo');+ expect(restored).toBe(true);+ expect(second.getManifest()?.revision()).toBe('rev-2');+ expect(second.remoteRoot).toBe('https://cdn/v2');+ });++ it('returns false when nothing is persisted under the key', () => {+ const assets = createAssets(backendServing());+ expect(assets.restorePersistedUpdate('hotupdate:absent')).toBe(false);+ });+});