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(editor): play rehearses the open data context, not a leaderboard
yhhafab1cb41c58
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d6bd2abfa..7d791d12e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,13 +31,21 @@ published separately; it ships inside the editor.`open-data/` directory was getting the engine's board by default; it needs thatfile to keep one.+- **Play mode rehearses the open data CONTEXT, not a leaderboard.** It runs the+ project's own `open-data/index.ts` against an offscreen canvas and invented+ friends, and answers through the platform capabilities a device would — so any+ board is rehearsed, `submit()` reaches it, and a context that does not compile+ refuses Play the way it refuses an export. The stand-in that used to live in+ the service (`setProvider`, `createLocalLeaderboard`) is gone with it.+### Added- **Host capabilities a package can reach**: `platformCanOpenData`,`platformOpenDataPostMessage`, `platformOpenDataCanvas`,`platformSetCloudKeyValues`, `platformCreateCanvas`, `platformDevicePixelRatio`,and `createCanvasTexture` — a texture whose content is a canvas something else- draws on. Exported because a shipped plugin holds each one up.+ draws on. Exported because a shipped plugin holds each one up. Plus+ `extendPlatform`, for a host that can answer what its adapter cannot.- **A plugin can put a button on the editor's activity bar** —`ctx.activityBar.register({ id, title, icon, run })`, with the glyph as thediff --git a/desktop/electron/buildOpenData.ts b/desktop/electron/buildOpenData.tsnew file mode 100644index 000000000..525c45475--- /dev/null+++ b/desktop/electron/buildOpenData.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The project's open data context, bundled for the play realm.+ *+ * The same file a mini-game export bundles (`<root>/open-data/index.ts`), built+ * the same way: as one self-contained script with NO `esengine` — that runtime+ * has no engine, and a context that imports one must fail here rather than on a+ * device. The realm evaluates the output against a stand-in host, so what the+ * editor rehearses is the file that ships.+ *+ * Pure Node (esbuild + fs/path), no Electron imports.+ */+import { existsSync } from 'node:fs';+import path from 'node:path';+import { loadEsbuild } from './esbuildRuntime';+import { explainBundleErrors, type BundleMessage } from './bundleDiagnostics';++/** Same directory name the exporter reads, and the same entry candidates. */+const OPEN_DATA_DIR = 'open-data';+const ENTRIES = ['index.ts', 'index.js'];+const CACHE_DIR = '.esengine/cache';+const OUTPUT = 'open-data.js';++export interface BuildOpenDataResult {+ ok: boolean;+ /** Absolute path to the bundle, or null when the project declares no context. */+ outputPath: string | null;+ errors: string[];+ warnings: string[];+}++/**+ * Bundle `<root>/open-data/index.ts` → `<root>/.esengine/cache/open-data.js`.+ *+ * A project with no context directory is `ok` with a null path — most games have+ * none, and that is not a failure. Never throws.+ */+export async function buildOpenDataContext(root: string): Promise<BuildOpenDataResult> {+ const entry = ENTRIES+ .map((f) => path.join(root, OPEN_DATA_DIR, f))+ .find((f) => existsSync(f));+ if (!entry) return { ok: true, outputPath: null, errors: [], warnings: [] };++ const outputPath = path.join(root, CACHE_DIR, OUTPUT);+ try {+ const { build } = await loadEsbuild();+ const result = await build({+ entryPoints: [entry],+ bundle: true,+ // One script that runs on eval, because the realm hands it a host rather+ // than importing it: a module would need an import map the context has no+ // business in.+ format: 'iife',+ platform: 'browser',+ target: 'es2020',+ outfile: outputPath,+ sourcemap: false,+ write: true,+ logLevel: 'silent',+ });+ return {+ ok: true,+ outputPath,+ errors: explainBundleErrors(result.errors),+ warnings: result.warnings.map((w) => w.text),+ };+ } catch (err) {+ const e = err as { errors?: BundleMessage[]; warnings?: { text: string }[]; message?: string };+ return {+ ok: false,+ outputPath: null,+ errors: e.errors ? explainBundleErrors(e.errors) : [String(e.message ?? err)],+ warnings: e.warnings?.map((x) => x.text) ?? [],+ };+ }+}diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 39de28f7e..0bf050653 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -29,6 +29,7 @@ import * as journal from './fileJournal';import { syncAutosave, listAutosave, restoreAutosave, clearAutosave, type AutosaveEntry } from './autosave';import { listRecents, addRecent, removeRecent, listTemplates, createFromTemplate } from './launcher';import { buildProjectScripts } from './buildScripts';+import { buildOpenDataContext } from './buildOpenData';import { extractProjectSchemas } from './extractSchemas';import { scaffoldScript, type ScriptKind } from './scriptScaffold';import { scanAssetDatabase, readCachedAssetIndex, updateAssetIndex } from './assetDb';@@ -1378,6 +1379,21 @@ ipcMain.handle('project:preparePlayRealm', async () => {sideModules: [],};}+ // The open data context, so the realm can rehearse it. Refused the same way:+ // a context that does not compile is one the export would refuse too, and+ // finding that out here beats finding it out on a device.+ const openData = await buildOpenDataContext(root).catch((e: Error) => (+ { ok: false, outputPath: null, errors: [String(e?.message ?? e)], warnings: [] }+ ));+ if (!openData.ok) {+ return {+ ok: false,+ hostPath: '',+ errors: ['"open-data" did not compile, so the game would play without its context:', ...openData.errors],+ warnings: openData.warnings,+ sideModules: [],+ };+ }return buildPlayRealm({root,playHostArtifact: path.join(HOSTS_DIR, 'playHost.js'),diff --git a/desktop/src/engine/openDataRehearsal.ts b/desktop/src/engine/openDataRehearsal.tsnew file mode 100644index 000000000..efcef68c3--- /dev/null+++ b/desktop/src/engine/openDataRehearsal.ts@@ -0,0 +1,105 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The open data context, rehearsed in the play realm.+ *+ * On a mini-game host the context is a second JS runtime holding the player's+ * friends: the game posts a message in, it draws on a shared canvas, and there+ * is no channel back. The editor is not that host — so it stands in for one,+ * running the project's OWN context file against invented friends.+ *+ * What that buys is that nothing here knows what a leaderboard is. Whatever the+ * project points `open-data/index.ts` at — this engine's package, a third+ * party's, its own — is what plays here, through the capability seam a device+ * would use.+ */++/** One invented friend, in the shape every vendor reports. */+interface RehearsalPlayer {+ nickname: string;+ openid: string;+ KVDataList: Array<{ key: string; value: string }>;+}++/** Names that cannot be mistaken for a real friends list. The player's own row+ * is not here — it is built from what the game actually submitted. */+const INVENTED: ReadonlyArray<{ nickname: string; openid: string; score: number }> = [+ { nickname: 'Sample Friend', openid: 'rehearsal-2', score: 15250 },+ { nickname: 'Another Tester', openid: 'rehearsal-3', score: 9870 },+ { nickname: 'Someone Else', openid: 'rehearsal-4', score: 6120 },+ { nickname: 'Never Played', openid: 'rehearsal-5', score: Number.NaN },+];++const SELF_ID = 'rehearsal-self';+/** The host's word for "whoever is playing" in an openIdList. */+const SELF = 'selfOpenId';++/** What a rehearsed context answers with, and what the platform then reports. */+export interface OpenDataRehearsal {+ /** The shared canvas, for `openDataCanvas()`. */+ canvas: HTMLCanvasElement;+ /** Deliver one message, as `openDataPostMessage()` does. */+ post(message: Record<string, unknown>): void;+ /** Record this player's own cloud rows, as `setCloudKeyValues()` does — the+ * context reads them back, so a submitted score reaches the board. */+ write(entries: Readonly<Record<string, string>>): void;+}++/**+ * Run `source` (a bundled context) against a stand-in host.+ *+ * The host arrives as `globalThis.wx` for the length of the evaluation, because+ * that is how a context written for a device reads it — and is removed straight+ * after, since a `wx` left behind is a platform everything else would sniff.+ */+export function rehearseOpenData(source: string, width = 360, height = 260): OpenDataRehearsal {+ const canvas = document.createElement('canvas');+ canvas.width = width;+ canvas.height = height;++ let handler: ((message: unknown) => void) | null = null;+ const selfKV: Record<string, string> = {};++ const host = {+ getSharedCanvas: () => canvas,+ getFriendCloudStorage: (opts: {+ keyList: string[];+ success?: (res: { data: RehearsalPlayer[] }) => void;+ }) => {+ const key = opts.keyList[0] ?? '';+ // The invented rows are re-keyed to whatever the game asked for: a game+ // with its own key would otherwise rehearse against an empty board and+ // reasonably read that as "this is broken".+ const friends: RehearsalPlayer[] = INVENTED.map((f) => ({+ nickname: f.nickname,+ openid: f.openid,+ KVDataList: Number.isNaN(f.score) ? [] : [{ key, value: String(f.score) }],+ }));+ const own = Object.entries(selfKV).map(([k, value]) => ({ key: k, value }));+ opts.success?.({ data: [{ nickname: 'You', openid: SELF_ID, KVDataList: own }, ...friends] });+ },+ getUserInfo: (opts: { openIdList: string[]; success?: (res: { data: Array<{ openid?: string }> }) => void }) => {+ opts.success?.({ data: opts.openIdList.map((id) => ({ openid: id === SELF ? SELF_ID : id })) });+ },+ createImage: () => new Image(),+ onMessage: (cb: (message: unknown) => void) => { handler = cb; },+ selfOpenId: SELF_ID,+ };++ const scope = globalThis as unknown as Record<string, unknown>;+ const had = Object.prototype.hasOwnProperty.call(scope, 'wx');+ const previous = scope.wx;+ scope.wx = host;+ try {+ new Function(source)();+ } finally {+ if (had) scope.wx = previous;+ else delete scope.wx;+ }++ return {+ canvas,+ post: (message) => { handler?.(message); },+ write: (entries) => { Object.assign(selfKV, entries); },+ };+}diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.tsindex 8f09a7860..5e457f2c5 100644--- a/desktop/src/playHost.ts+++ b/desktop/src/playHost.ts@@ -17,6 +17,8 @@import { uiPickWorld, uiWorldToScreen, screenToUiWorld, uiNodeWorldBox, createWebApp, setEditorMode, setPlayMode, enableSceneOrigins, sceneOriginOf, entityWorldBox, entityBoxCorners, CameraView, layerOrderOf, quaternionToAngle2D, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport, Assets, Ads, createMockAdProvider, registerPackagedSideModules, Input, inputEventCallbacks, isEntityVisible, setEntityVisible, hasVisibility, takeCensus } from 'esengine';import type { App, SceneData, InputState, UICameraData } from 'esengine';import type { ESEngineModule } from 'esengine/wasm';+import { extendPlatform } from 'esengine';+import { rehearseOpenData, type OpenDataRehearsal } from './engine/openDataRehearsal';import { PLAY_PROTOCOL_VERSION } from './engine/playProtocol';import type { PlayOutbound, PlayInbound, LiveVisibility, CanvasPoint, PlayOverlayBox } from './engine/playProtocol';import { translateAssetHandles, projectRelative } from './engine/liveAssetRefs';@@ -439,6 +441,7 @@ type InitMessage = Extract<PlayOutbound, { type: 'estella:play:init' }>;const canvas = document.getElementById('canvas') as HTMLCanvasElement;const wasmBase = new URL('./wasm/', import.meta.url).href; // sibling of host.jsconst bundleUrl = new URL('../cache/scripts.mjs', import.meta.url).href; // project bundle+const openDataUrl = new URL('../cache/open-data.js', import.meta.url).href; // the project's context, if it has oneconst projectBase = new URL('../../', import.meta.url).href.replace(/\/$/, ''); // project root — assets live herefunction resize(): void {@@ -450,6 +453,7 @@ window.addEventListener('resize', resize);resize();let app: App | null = null;+let openData: OpenDataRehearsal | null = null;let engineModule: ESEngineModule | null = null;let glHandle = 0;/** The init snapshot of the current play session, replayed on hot-reload: a code@@ -558,8 +562,34 @@ function startFrameHeartbeat(): void {const HEARTBEAT_MS = 500;let heartbeat: number | null = null;+/**+ * Stand in for the host's open data context, where the project has one.+ *+ * Installed as PLATFORM capabilities rather than handed to a service, so any+ * leaderboard sees the seam it would see on a device. Once per session, as a+ * host's context outlives a hot reload.+ */+async function ensureOpenDataContext(): Promise<void> {+ if (openData !== null) return;+ const res = await fetch(openDataUrl).catch(() => null);+ if (!res?.ok) return; // no context in this project — and none on a device either+ try {+ openData = rehearseOpenData(await res.text());+ } catch (e) {+ console.warn('[play] the open data context threw while starting:', e);+ return;+ }+ const rehearsal = openData;+ extendPlatform({+ openDataCanvas: () => rehearsal.canvas as never,+ openDataPostMessage: (message: Record<string, unknown>) => { rehearsal.post(message); },+ setCloudKeyValues: (entries: Readonly<Record<string, string>>) => { rehearsal.write(entries); return true; },+ });+}+async function buildAppAndRun(msg: InitMessage): Promise<void> {const module = engineModule!;+ await ensureOpenDataContext();app = createWebApp(module, {renderSurface: { kind: 'gl-context', handle: glHandle },ySortLayers: msg.ySortLayers,@@ -614,11 +644,6 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {enableStats: true, // editor profiler: per-phase / per-system frame timing});- // A friends board, rehearsed as the ad above is. AFTER the runtime init, which- // is where the game's own plugins install — and by NAME, because a board is a- // package the editor does not depend on.- (app.getResourceByName('Leaderboard') as { rehearse?(): void } | undefined)?.rehearse?.();-// Realm-local debug handle for automation/diagnostics (mirrors the headless// host's __estellaHeadless): the editor can't reach into this OOPIF except by// main-process frame eval, and the eval needs SOMETHING to query. getComponentdiff --git a/desktop/tests/open-data-rehearsal.test.ts b/desktop/tests/open-data-rehearsal.test.tsnew file mode 100644index 000000000..6b947204f--- /dev/null+++ b/desktop/tests/open-data-rehearsal.test.ts@@ -0,0 +1,121 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The open data context, built for the play realm and rehearsed in it.+ *+ * The point of both halves is that what the editor plays is the file that+ * SHIPS: bundled by the same rules the exporter uses (no engine in there), and+ * run against a host shaped like the one on a device.+ */+import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { buildOpenDataContext } from '../electron/buildOpenData';+import { rehearseOpenData } from '@/engine/openDataRehearsal';++let root: string;++beforeAll(() => {+ root = mkdtempSync(path.join(tmpdir(), 'estella-opendata-'));+});+afterAll(() => {+ if (root) rmSync(root, { recursive: true, force: true });+});++function context(source: string): void {+ mkdirSync(path.join(root, 'open-data'), { recursive: true });+ writeFileSync(path.join(root, 'open-data', 'index.ts'), source);+}++describe('buildOpenDataContext', () => {+ it('has nothing to build, and says so, when the project declares no context', async () => {+ const empty = mkdtempSync(path.join(tmpdir(), 'estella-nocontext-'));+ const res = await buildOpenDataContext(empty);+ expect(res.ok).toBe(true);+ expect(res.outputPath).toBeNull();+ rmSync(empty, { recursive: true, force: true });+ });++ it('bundles the context and its own modules into one script', async () => {+ writeFileSync(path.join(root, 'draw.ts'), 'export const mark = () => { (globalThis as never as Record<string, unknown>).__DREW__ = 1; };\n');+ context("import { mark } from '../draw';\ndeclare const wx: { onMessage(cb: (m: unknown) => void): void };\nwx.onMessage(() => mark());\n");++ const res = await buildOpenDataContext(root);+ expect(res.ok).toBe(true);+ expect(res.errors).toEqual([]);+ const code = readFileSync(res.outputPath!, 'utf8');+ expect(code).toContain('__DREW__'); // the local module came in+ expect(code).not.toContain('import '); // one self-contained script+ }, 30_000);++ it('refuses a context that imports the engine — here, not on a device', async () => {+ context("import { Assets } from 'esengine';\nAssets.toString();\n");+ const res = await buildOpenDataContext(root);+ expect(res.ok).toBe(false);+ expect(res.errors.join('\n')).toMatch(/esengine/);+ }, 30_000);+});++describe('rehearseOpenData', () => {+ const globals = globalThis as unknown as Record<string, unknown>;+ let removed: string[] = [];++ beforeEach(() => {+ removed = [];+ for (const [key, value] of Object.entries({+ document: { createElement: () => ({ width: 0, height: 0, getContext: () => null }) },+ Image: class {},+ })) {+ if (!(key in globals)) { globals[key] = value; removed.push(key); }+ }+ });+ afterEach(() => {+ for (const key of removed) delete globals[key];+ delete globals.wx;+ });++ /** A context written the way one for a device is: reads the host global, keeps+ * the messages it is sent. */+ const SOURCE = `+ var seen = [];+ globalThis.__SEEN__ = seen;+ var host = globalThis.wx;+ globalThis.__CANVAS__ = host.getSharedCanvas();+ host.onMessage(function (m) {+ seen.push(m);+ host.getFriendCloudStorage({ keyList: [m.key], success: function (res) { seen.push(res.data); } });+ });+ `;++ it('runs a context and delivers what the game posted', () => {+ const rehearsal = rehearseOpenData(SOURCE);+ expect(globals.__CANVAS__).toBe(rehearsal.canvas);++ rehearsal.post({ kind: 'show', key: 'es.score' });+ const seen = globals.__SEEN__ as unknown[];+ expect(seen[0]).toEqual({ kind: 'show', key: 'es.score' });++ // The friends it invents are re-keyed to what the game asked for, and the+ // one who never played carries no row at all.+ const friends = seen[1] as Array<{ nickname: string; KVDataList: Array<{ key: string }> }>;+ expect(friends.map((f) => f.nickname)).toContain('Sample Friend');+ expect(friends.every((f) => f.KVDataList.every((kv) => kv.key === 'es.score'))).toBe(true);+ expect(friends.find((f) => f.nickname === 'Never Played')!.KVDataList).toEqual([]);+ });++ it('gives the player back the score the game submitted', () => {+ const rehearsal = rehearseOpenData(SOURCE);+ rehearsal.write({ 'es.score': '777' });+ rehearsal.post({ kind: 'show', key: 'es.score' });++ const friends = (globals.__SEEN__ as unknown[])[1] as Array<{ nickname: string; KVDataList: Array<{ value: string }> }>;+ expect(friends[0].nickname).toBe('You');+ expect(friends[0].KVDataList[0].value).toBe('777');+ });++ it('leaves no `wx` behind — the platform is the seam, not a global', () => {+ rehearseOpenData(SOURCE);+ expect('wx' in globals).toBe(false);+ });+});diff --git a/docs/astro/src/content/docs/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/publishing/ads-sharing.mdxindex 995e135f4..4c276fadb 100644--- a/docs/astro/src/content/docs/publishing/ads-sharing.mdx+++ b/docs/astro/src/content/docs/publishing/ads-sharing.mdx@@ -174,16 +174,21 @@ runtime, so `limit` is how many rows fit, not a page.### Your own boardWrite the file yourself instead of importing the package's. It runs in the-context, so it may **not import `esengine`** — the export fails if it does,-which is better than finding out on a device. Inside, you have a 2D canvas from-`wx.getSharedCanvas()`, `wx.getFriendCloudStorage()`, and `wx.onMessage()`-carrying whatever `show()` sent.+context, so it may **not import `esengine`** — the export fails if it does, and+so does entering Play, which is better than finding out on a device. Inside, you+have a 2D canvas from `wx.getSharedCanvas()`, `wx.getFriendCloudStorage()`, and+`wx.onMessage()` carrying whatever `show()` sent.### At your desk-Play mode has no context at all, so the board rehearses: the same renderer that-ships inside the context, drawn on an offscreen canvas with obviously-invented-friends. The panel can be laid out and styled without packaging anything.+Play mode has no host, so the editor stands in for one: it runs **your**+`open-data/index.ts` against an offscreen canvas and obviously-invented friends,+and answers `Leaderboard` through the same capabilities a device would. The+board you lay the panel out against is the one that ships — whoever wrote it —+and `submit()` reaches it, so your own row moves.++What it cannot rehearse is the part that is genuinely the host's: real friends+and the sandbox they live in. Check that on a device before you ship.What it cannot rehearse is the part that is genuinely the host's — real friendsand the sandbox they live in. Check that on a device before you ship.diff --git a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdxindex e98a17879..cea4764a9 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx@@ -161,18 +161,19 @@ import 'estella-plugin-minigame-services/open-data';### 自己写一份不 import 包的那份,自己写这个文件就行。它运行在开放数据域里,所以**不允许-import `esengine`**——真这么写会导出失败,这比到设备上才发现要好。在里面你有-`wx.getSharedCanvas()` 给的 2D 画布、`wx.getFriendCloudStorage()`,以及-`wx.onMessage()` 收到的 `show()` 发过去的内容。+import `esengine`**——真这么写导出会失败,进 Play 也会失败,这比到设备上才发现要+好。在里面你有 `wx.getSharedCanvas()` 给的 2D 画布、`wx.getFriendCloudStorage()`,+以及 `wx.onMessage()` 收到的 `show()` 发过去的内容。### 在你自己的桌面上-Play 模式里根本没有开放数据域,所以榜会**排演**:跑的是和开放数据域里那份同一段-渲染代码,画在离屏画布上,用一眼就看得出是假的好友数据。所以面板的排版和配色不-打包就能调。+Play 模式里没有宿主,所以**编辑器来当这个宿主**:它跑的是**你自己那份**+`open-data/index.ts`,画在离屏画布上,配一份一眼就看得出是假的好友数据,并按设备+上同样的那几个能力回答 `Leaderboard`。所以你对着排版的那块榜就是会发出去的那块+——不管它是谁写的——而且 `submit()` 真的能进去,自己那一行会动。-它替代不了的是真正属于宿主的那部分——真实好友,以及它们所在的沙箱。发版前请在-真机上过一眼。+它替代不了的是真正属于宿主的那部分——真实好友,以及它们所在的沙箱。发版前请在真+机上过一眼。## 登录diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex bf7d5d309..e5b010302 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 112,"beta": 60,- "experimental": 1500,+ "experimental": 1501,"deprecated": 3},- "total": 1672,+ "total": 1673,"subsystems": [{"id": "ecs",diff --git a/plugins/minigame-services/README.md b/plugins/minigame-services/README.mdindex c83dde9ce..1da6ac693 100644--- a/plugins/minigame-services/README.md+++ b/plugins/minigame-services/README.md@@ -79,9 +79,10 @@ That directory is what the exporter bundles separately and names in `game.json`.Without it the host has no context, and `available` says so rather than a boardfailing on a device.-In the editor's play mode there is no context at all, so the board draws against-invented friends — the same renderer that ships, on an offscreen canvas. It is-`rehearse()`, the editor calls it for you, and a real host always wins.+In the editor's play mode there is no host, so the editor stands in for one: it+runs **that same file** against an offscreen canvas and invented friends. So the+board you look at while building the panel is the one that ships, and nothing+here needs a rehearsal mode of its own.## Built on the public APIdiff --git a/plugins/minigame-services/src/index.ts b/plugins/minigame-services/src/index.tsindex 6de451083..e32e17062 100644--- a/plugins/minigame-services/src/index.ts+++ b/plugins/minigame-services/src/index.ts@@ -16,9 +16,8 @@ import { Leaderboard, LeaderboardAPI } from './leaderboard';export { Share, ShareAPI, type ShareCard } from './share';export { Payment, PaymentAPI, type PaymentRequest, type PaymentFailure } from './payment';export {- Leaderboard, LeaderboardAPI, createLocalLeaderboard,- type LeaderboardOptions, type LeaderboardProvider, type LeaderboardScope,- type LeaderboardStyle, type LocalLeaderboardOptions, type CloudPlayer,+ Leaderboard, LeaderboardAPI,+ type LeaderboardOptions, type LeaderboardScope, type LeaderboardStyle,} from './leaderboard';export class MiniGameServicesPlugin implements Plugin {diff --git a/plugins/minigame-services/src/leaderboard.ts b/plugins/minigame-services/src/leaderboard.tsindex a82982a26..a1e76bdee 100644--- a/plugins/minigame-services/src/leaderboard.ts+++ b/plugins/minigame-services/src/leaderboard.ts@@ -27,14 +27,13 @@import {defineResource, log,platformCanOpenData, platformOpenDataCanvas, platformOpenDataPostMessage,- platformSetCloudKeyValues, platformDevicePixelRatio, platformCreateCanvas,+ platformSetCloudKeyValues, platformDevicePixelRatio,createCanvasTexture,- type App, type CanvasTexture, type PlatformCanvas,+ type App, type CanvasTexture,} from 'esengine';-import { createBoard, type CloudPlayer, type HostCanvas } from './opendata/board';import type { LeaderboardScope, LeaderboardStyle, ShowMessage } from './opendata/protocol';-export type { LeaderboardScope, LeaderboardStyle, CloudPlayer };+export type { LeaderboardScope, LeaderboardStyle };/** What to draw, and how. Everything has a default a game can ignore. */export interface LeaderboardOptions {@@ -53,56 +52,17 @@ export interface LeaderboardOptions {* read each other's rows by accident. */const DEFAULT_KEY = 'es.score';-/**- * A stand-in for the open data context, for hosts that have none: the editor's- * play mode, a web build, a test. Mirrors the two things the platform supplies- * — somewhere to send a message, and a canvas to sample — so one seam serves- * both. {@link createLocalLeaderboard} is the standard implementation.- */-export interface LeaderboardProvider {- /** The surface the board is drawn on. */- canvas(): PlatformCanvas | null;- /** Receive what the main domain would have posted into the context. */- post(message: Record<string, unknown>): void;-}-export class LeaderboardAPI {private texture_: CanvasTexture | null = null;private shown_ = false;private key_ = DEFAULT_KEY;- private provider_: LeaderboardProvider | null = null;constructor(private readonly app_: () => App | null) {}- /** Whether SOME board exists here — the host's context, or an installed- * provider. What a menu reads to hide its leaderboard button honestly. */+ /** Whether this host has a context to draw in — what a menu reads to hide+ * its leaderboard button honestly (web and native have none). */get available(): boolean {- return this.provider_ !== null || platformCanOpenData();- }-- /**- * Draw against invented friends where this host has no open data context.- *- * The editor's play realm calls it, so a board can be looked at before the- * game is on a phone; a game may call it too (a web demo). A no-op where a- * real context exists — the real thing always wins.- */- rehearse(options?: LocalLeaderboardOptions): void {- if (this.available) return;- this.setProvider(createLocalLeaderboard(options));- }-- /**- * Install (or clear with null) a {@link LeaderboardProvider} that answers- * INSTEAD of the platform — a board to look at where the host has none.- * Clearing drops the texture: the canvas behind it is going away.- */- setProvider(provider: LeaderboardProvider | null): void {- if (provider === this.provider_) return;- this.provider_ = provider;- this.texture_?.destroy();- this.texture_ = null;- this.shown_ = false;+ return platformCanOpenData();}/**@@ -148,7 +108,7 @@ export class LeaderboardAPI {style: options.style ?? {},dpr: platformDevicePixelRatio(),};- if (!this.post_(message as unknown as Record<string, unknown>)) return false;+ if (!platformOpenDataPostMessage(message as unknown as Record<string, unknown>)) return false;this.shown_ = true;this.ensureTexture_();return true;@@ -159,7 +119,7 @@ export class LeaderboardAPI {hide(): void {if (!this.shown_) return;this.shown_ = false;- this.post_({ kind: 'hide' });+ platformOpenDataPostMessage({ kind: 'hide' });// One last take, so what stays on the handle is the CLEARED canvas// rather than the board that was on it when we stopped looking.this.texture_?.update();@@ -180,15 +140,9 @@ export class LeaderboardAPI {this.shown_ = false;}- /** An installed provider answers instead of the platform, both ways. */- private post_(message: Record<string, unknown>): boolean {- if (this.provider_) { this.provider_.post(message); return true; }- return platformOpenDataPostMessage(message);- }-private ensureTexture_(): void {if (this.texture_) return;- const canvas = this.provider_ ? this.provider_.canvas() : platformOpenDataCanvas();+ const canvas = platformOpenDataCanvas();if (!canvas) return;this.texture_ = createCanvasTexture(this.app_(), canvas);if (!this.texture_) {@@ -200,55 +154,3 @@ export class LeaderboardAPI {}export const Leaderboard = defineResource<LeaderboardAPI>(null!, 'Leaderboard');--/** How a rehearsal board is populated. */-export interface LocalLeaderboardOptions {- /** The friends to invent. Defaults to a small, obviously-fake set — real- * names would read as real data and hide that this is a rehearsal. */- friends?: readonly CloudPlayer[];- /** Canvas size in CSS px. */- width?: number;- height?: number;-}--/** Names that cannot be mistaken for a real friends list. */-const REHEARSAL_FRIENDS: readonly CloudPlayer[] = [- { nickname: 'Player One', openid: 'local-self', KVDataList: [{ key: 'es.score', value: '18400' }] },- { nickname: 'Sample Friend', openid: 'local-2', KVDataList: [{ key: 'es.score', value: '15250' }] },- { nickname: 'Another Tester', openid: 'local-3', KVDataList: [{ key: 'es.score', value: '9870' }] },- { nickname: 'Someone Else', openid: 'local-4', KVDataList: [{ key: 'es.score', value: '6120' }] },- { nickname: 'Never Played', openid: 'local-5', KVDataList: [] },-];--/**- * A board you can look at without a device.- *- * It runs the SAME board this package ships into the context, against an- * offscreen canvas and invented friends — a rehearsal that drew its own- * approximation would rehearse nothing. What it cannot stand in for is the part- * that is genuinely the host's: real friends, and the sandbox they live in.- */-export function createLocalLeaderboard(options: LocalLeaderboardOptions = {}): LeaderboardProvider {- const friends = options.friends ?? REHEARSAL_FRIENDS;- const canvas = platformCreateCanvas(options.width ?? 360, options.height ?? 260);- const board = createBoard({- getSharedCanvas: () => canvas as unknown as HostCanvas,- getFriendCloudStorage: ({ keyList, success }) => {- const key = keyList[0];- success?.({- data: friends.map((f) => ({- ...f,- // Re-keyed to whatever the game asked for, so a game with its- // own key still sees the rehearsal rows rather than an empty- // board it would reasonably read as "this is broken".- KVDataList: (f.KVDataList ?? []).map((kv) => ({ ...kv, key })),- })),- });- },- selfOpenId: 'local-self',- });- return {- canvas: () => canvas,- post: (message) => { board.handle(message); },- };-}diff --git a/plugins/minigame-services/tests/leaderboard.test.ts b/plugins/minigame-services/tests/leaderboard.test.tsindex 2c5237af7..c38cd04d7 100644--- a/plugins/minigame-services/tests/leaderboard.test.ts+++ b/plugins/minigame-services/tests/leaderboard.test.ts@@ -20,7 +20,6 @@ const host = {sent: [] as Record<string, unknown>[],cloud: [] as Array<Readonly<Record<string, string>>>,canvas: null as unknown,- makeCanvas: (w: number, h: number) => ({ width: w, height: h, getContext: () => null }) as unknown,};vi.mock('esengine', () => ({@@ -39,13 +38,12 @@ vi.mock('esengine', () => ({return true;},platformDevicePixelRatio: () => host.dpr,- platformCreateCanvas: (w: number, h: number) => host.makeCanvas(w, h),// No WebGL in a unit test — which is itself worth exercising: the service must// stay usable and just report texture 0.createCanvasTexture: () => null,}));-const { LeaderboardAPI, createLocalLeaderboard } = await import('../src/leaderboard');+const { LeaderboardAPI } = await import('../src/leaderboard');beforeEach(() => {host.context = true;@@ -54,7 +52,6 @@ beforeEach(() => {host.sent = [];host.cloud = [];host.canvas = { width: 512, height: 512, getContext: () => null };- host.makeCanvas = (w: number, h: number) => ({ width: w, height: h, getContext: () => null });});const api = () => new LeaderboardAPI(() => null);@@ -141,100 +138,6 @@ describe('show / hide', () => {});});-/**- * The rehearsal board. Its value is entirely in being the SAME renderer that- * ships inside the open data context — an approximation drawn here would tell- * you nothing about what appears on a phone — so what these pin is that it- * really does draw, and that it stands in for the platform everywhere.- */-describe('the local board', () => {- /** A 2D context that records what was drawn on it. */- function recordingCanvas() {- const calls: Array<{ op: string; args: unknown[] }> = [];- const ctx = new Proxy({} as Record<string, unknown>, {- get: (_t, prop: string) => {- if (prop === 'measureText') return (s: string) => ({ width: s.length * 7 });- if (prop === 'canvas') return undefined;- return (...args: unknown[]) => { calls.push({ op: prop, args }); };- },- set: () => true,- });- return { calls, ctx };- }-- /** 1:1 and wide enough that nothing is clipped: the clipping rule has its own- * test, and letting it fire here would only make this one assert the wrong thing. */- function drawnOn() {- const rec = recordingCanvas();- host.dpr = 1;- host.makeCanvas = (w: number, h: number) => ({ width: w, height: h, getContext: () => rec.ctx });- return rec;- }-- it('draws the rows through the same renderer that ships', () => {- const rec = drawnOn();- host.context = false; // no open data context at all — the provider is the whole board- const l = api();- l.setProvider(createLocalLeaderboard({ width: 640 }));- expect(l.available).toBe(true);- expect(l.show()).toBe(true);-- const texts = rec.calls.filter((c) => c.op === 'fillText').map((c) => String(c.args[0]));- // The invented friends, ranked — and the one who never played is absent,- // the same rule the shipped board follows because it IS that board.- expect(texts).toContain('Player One');- expect(texts).toContain('18400');- expect(texts).not.toContain('Never Played');- });-- it('re-keys the invented rows to whatever key the game asked for', () => {- // A game with its own key would otherwise rehearse against an empty board- // and reasonably read that as "this is broken".- const rec = drawnOn();- const l = api();- l.setProvider(createLocalLeaderboard({ width: 640 }));- l.show({ key: 'my.own.key' });- expect(rec.calls.some((c) => c.op === 'fillText' && c.args[0] === '18400')).toBe(true);- });-- it('answers `available` where the platform cannot', () => {- host.context = false;- const l = api();- expect(l.available).toBe(false);- l.setProvider(createLocalLeaderboard());- expect(l.available).toBe(true);- l.setProvider(null);- expect(l.available).toBe(false);- });-- it('rehearses only where the host has nothing, and only once', () => {- const l = api();- l.rehearse();- // A real context wins: nothing was installed, so `show` still goes to it.- l.show();- expect(host.sent).toHaveLength(1);-- host.context = false;- const off = api();- off.rehearse();- expect(off.available).toBe(true);- const board = off;- off.rehearse(); // second call keeps the first board- expect(board.available).toBe(true);- });-- it('clears the board when the provider is swapped out', () => {- const l = api();- l.setProvider(createLocalLeaderboard());- l.show();- expect(l.visible).toBe(true);- // The canvas behind the texture is going away with the provider.- l.setProvider(null);- expect(l.visible).toBe(false);- expect(l.texture).toBe(0);- });-});-describe('the texture', () => {it('is 0 until there is one, and the service still works', () => {const l = api();diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 6f7221f5e..28646dd4a 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 53 beta · 1385 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1386 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -9500,6 +9500,11 @@ EventBindingPlugin(prefab: PrefabData, delta: PrefabInstanceDelta, allocateId: () => number, loadPrefab?: SyncPrefabResolver): { entities: ProcessedEntity[]; rootId: number; }```+## extendPlatform — function @experimental+```+(extra: Partial<PlatformAdapter>): void+```+## extractAnimClipTexturePaths — function @experimental```(data: AnimClipAssetData): string[]diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 616805c4d..bdb5a3f95 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 58 beta · 1404 experimental · 3 deprecated+Symbols: 112 public · 58 beta · 1405 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -9733,6 +9733,11 @@ EventBindingPlugin(prefab: PrefabData, delta: PrefabInstanceDelta, allocateId: () => number, loadPrefab?: SyncPrefabResolver): { entities: ProcessedEntity[]; rootId: number; }```+## extendPlatform — function @experimental+```+(extra: Partial<PlatformAdapter>): void+```+## extractAnimClipTexturePaths — function @experimental```(data: AnimClipAssetData): string[]diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 59fd2d4c0..959f5c43d 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 55 beta · 1384 experimental · 3 deprecated+Symbols: 112 public · 55 beta · 1385 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -9495,6 +9495,11 @@ EventBindingPlugin(prefab: PrefabData, delta: PrefabInstanceDelta, allocateId: () => number, loadPrefab?: SyncPrefabResolver): { entities: ProcessedEntity[]; rootId: number; }```+## extendPlatform — function @experimental+```+(extra: Partial<PlatformAdapter>): void+```+## extractAnimClipTexturePaths — function @experimental```(data: AnimClipAssetData): string[]diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 3d01fd08f..ed42f542e 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 53 beta · 1405 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1406 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -9745,6 +9745,11 @@ EventBindingPlugin(prefab: PrefabData, delta: PrefabInstanceDelta, allocateId: () => number, loadPrefab?: SyncPrefabResolver): { entities: ProcessedEntity[]; rootId: number; }```+## extendPlatform — function @experimental+```+(extra: Partial<PlatformAdapter>): void+```+## extractAnimClipTexturePaths — function @experimental```(data: AnimClipAssetData): string[]diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 43560aa5a..4f195b938 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 53 beta · 1395 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1396 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -9522,6 +9522,11 @@ EventBindingPlugin(prefab: PrefabData, delta: PrefabInstanceDelta, allocateId: () => number, loadPrefab?: SyncPrefabResolver): { entities: ProcessedEntity[]; rootId: number; }```+## extendPlatform — function @experimental+```+(extra: Partial<PlatformAdapter>): void+```+## extractAnimClipTexturePaths — function @experimental```(data: AnimClipAssetData): string[]diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.tsindex 3a0a72790..1b68a4c89 100644--- a/sdk/src/core-sys.ts+++ b/sdk/src/core-sys.ts@@ -130,6 +130,9 @@ export type { PlatformShareOptions, PlatformPaymentRequest } from './platform/tyexport {getPlatform,+ // A host may add what its platform cannot answer — the editor's play realm+ // stands in for an open data context this way.+ extendPlatform,getPlatformType,isPlatformInitialized,isWeChat,diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex 7c1bdbac1..ffd664a87 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -22,6 +22,18 @@ export function setPlatform(adapter: PlatformAdapter): void {currentPlatform = adapter;}+/**+ * Add capabilities to the platform this app is already on — a host answering+ * what its adapter cannot (the editor's play realm stands in for an open data+ * context this way). Its own door because `setPlatform({ ...getPlatform() })`+ * drops every method an adapter holds on its PROTOTYPE.+ *+ * @throws Error if no platform is set — there is nothing to extend yet.+ */+export function extendPlatform(extra: Partial<PlatformAdapter>): void {+ Object.assign(getPlatform(), extra);+}+/*** Get the current platform adapter* @throws Error if platform not initializeddiff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.tsindex 2a4160d6a..1044bd029 100644--- a/sdk/src/platform/index.ts+++ b/sdk/src/platform/index.ts@@ -23,6 +23,7 @@ export type {// Re-export base functionsexport {setPlatform,+ extendPlatform,getPlatform,getPlatformType,isPlatformInitialized,