Skip to content

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

feat(sdk): the open data context is a capability, and an export bundles one

yhhed481a2109b1
diff --git a/desktop/electron/exportMiniGame.ts b/desktop/electron/exportMiniGame.ts
index eec96a793..ccff77f10 100644
--- a/desktop/electron/exportMiniGame.ts
+++ b/desktop/electron/exportMiniGame.ts
@@ -41,6 +41,7 @@ import {
sceneUsesPhysics, sceneUsesVideo, sceneUsesDragonBones, detectSpineVersion, detectSpineVersionJson,
spineModuleId, SIDE_MODULE_FILE,
} from './sideModuleScan';
+import { OPEN_DATA_DIR } from './miniGameExportProfile';
import type { MiniGameExportProfile, MiniGameVendor } from './miniGameExportProfile';
export interface ExportMiniGameResult {
@@ -334,6 +335,42 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
errors.push(...(e.errors?.map((x) => x.text) ?? [String(e.message ?? err)]));
}
+ // 4b. The open data context — a SECOND bundle, for a second JS runtime.
+ //
+ // It has no WebGL, no wasm and almost none of the host API; it draws on a
+ // 2D canvas the main domain samples as a texture, and it is the only place
+ // a player's friends can be read. So it cannot share the game bundle, and
+ // the `esengine` alias is deliberately WITHHELD here: a context that
+ // imports the engine fails to resolve at export instead of throwing on a
+ // device, which is the only place that mistake would otherwise surface.
+ const openDataEntry = ['index.ts', 'index.js']
+ .map((f) => path.join(opts.root, OPEN_DATA_DIR, f))
+ .find((f) => existsSync(f));
+ if (openDataEntry) {
+ progress({ phase: 'Bundling open data context' });
+ try {
+ const { build } = await loadEsbuild();
+ const res = await build({
+ entryPoints: [openDataEntry],
+ bundle: true,
+ format: 'cjs',
+ platform: 'browser',
+ // Same syntax floor as the game bundle: the host compiles EVERY .js in
+ // the package, this one included.
+ target: profile.esTarget,
+ minify: opts.minify ?? false,
+ sourcemap: false,
+ outfile: path.join(absOut, OPEN_DATA_DIR, 'index.js'),
+ logLevel: 'silent',
+ write: true,
+ });
+ errors.push(...res.errors.map((e) => e.text));
+ } catch (err) {
+ const e = err as { errors?: { text: string }[]; message?: string };
+ errors.push(...(e.errors?.map((x) => x.text) ?? [String(e.message ?? err)]));
+ }
+ }
+
// 5. Entry + config (vendor-specific emission).
await writeFile(path.join(absOut, 'game.js'), profile.emitEntry({ sideModules, engineGlueFile }));
const configFiles = profile.emitConfigFiles({
@@ -342,6 +379,10 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
orientation: opts.orientation ?? 'portrait',
subPackages: subPackagesOf(cookEntries, profile.subpackageDir),
includeSuffixes: packIncludeSuffixes(cookEntries, profile.nativeSuffixes),
+ // Only a bundle that was actually written counts: an entry that failed to
+ // build must not leave the config pointing at a directory with no index.js.
+ hasOpenData: !!openDataEntry && errors.length === 0,
+ openDataRoot: OPEN_DATA_DIR,
});
for (const { file, content } of configFiles) {
await writeFile(path.join(absOut, file), content);
diff --git a/desktop/electron/miniGameExportProfile.ts b/desktop/electron/miniGameExportProfile.ts
index d62e78271..364f78ae0 100644
--- a/desktop/electron/miniGameExportProfile.ts
+++ b/desktop/electron/miniGameExportProfile.ts
@@ -31,8 +31,26 @@ export interface MiniGameConfigContext {
subPackages: ReadonlyArray<{ name: string; root: string }>;
/** Custom suffixes the cook staged that need an explicit packer include rule. */
includeSuffixes: string[];
+ /** Whether this export actually bundled an open data context. Declaring one
+ * that is not there fails the host's compile, so the config names the
+ * directory only when the directory exists. */
+ hasOpenData: boolean;
+ /** Where it was bundled — {@link OPEN_DATA_DIR}, handed in rather than read
+ * from a constant so a project-authored profile emits the same name the
+ * pipeline actually wrote to. */
+ openDataRoot: string;
}
+/**
+ * The directory an open data context is authored in and bundled to.
+ *
+ * A family constant, not vendor data: the hosts that have this capability let
+ * the game pick the name, so the only thing a vendor could contribute is a
+ * different arbitrary string. It is the same on both sides — `<project>/open-data/`
+ * in, `<package>/open-data/` out — so there is one name to know.
+ */
+export const OPEN_DATA_DIR = 'open-data';
+
/** Vendor-neutral facts the pipeline computes, handed to the entry emitter. */
export interface MiniGameEntryContext {
/** Optional modules the shipped scenes need (physics/spine/basis/videodec). */
@@ -136,6 +154,12 @@ export const wechatExportProfile: MiniGameExportProfile = {
deviceOrientation: ctx.orientation,
showStatusBar: false,
};
+ // 开放数据域: named ONLY when this export bundled one. WeChat compiles
+ // the directory the key points at, so declaring an absent context is a
+ // build failure rather than a feature nobody uses.
+ if (ctx.hasOpenData) {
+ gameCfg.openDataContext = ctx.openDataRoot;
+ }
// WeChat 分包: each lazy group is a subpackage rooted at subpackages/<name>/.
// The game calls Assets.loadGroup(name) → wx.loadSubpackage at runtime.
if (ctx.subPackages.length > 0) {
diff --git a/desktop/tests/export-wechat.test.ts b/desktop/tests/export-wechat.test.ts
index 6b0390e93..8624e3efc 100644
--- a/desktop/tests/export-wechat.test.ts
+++ b/desktop/tests/export-wechat.test.ts
@@ -389,3 +389,87 @@ describe('exportGame (wechat)', () => {
expect(pcfg.packOptions?.include ?? []).not.toContainEqual({ type: 'suffix', value: '.esscene' });
}, 60_000);
});
+
+/**
+ * The open data context — a SECOND bundle for a second JS runtime, which is the
+ * only place a player's friends can be read. Its own project roots: the presence
+ * of an `open-data/` directory changes the emitted config, so a case that adds
+ * one must not be able to leak into a case that asserts its absence.
+ */
+describe('exportGame (wechat) — open data context', () => {
+ const roots: string[] = [];
+
+ /** A minimal exportable project: one scene, one texture, stub SDK + runtime. */
+ function scaffold(openDataSource?: string): { root: string; out: string } {
+ const dir = mkdtempSync(path.join(tmpdir(), 'estella-export-opendata-'));
+ roots.push(dir);
+ mkdirSync(path.join(dir, 'assets'), { recursive: true });
+ writeFileSync(path.join(dir, 'assets', 'hero.png'), 'PNGDATA');
+ writeFileSync(path.join(dir, 'assets', 'hero.png.meta'), meta(TEX, 'texture'));
+ mkdirSync(path.join(dir, 'scenes'), { recursive: true });
+ writeFileSync(
+ path.join(dir, 'scenes', 'main.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }),
+ );
+ writeFileSync(path.join(dir, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
+ mkdirSync(path.join(dir, '_sdk'), { recursive: true });
+ writeFileSync(path.join(dir, '_sdk', 'index.wechat.js'), 'export function initWeChatRuntime(){return Promise.resolve();}\n');
+ mkdirSync(path.join(dir, '_wxwasm'), { recursive: true });
+ writeFileSync(path.join(dir, '_wxwasm', 'esengine.js'), 'module.exports = () => Promise.resolve({});');
+ writeFileSync(path.join(dir, '_wxwasm', 'esengine.wasm'), 'wasmbytes');
+ if (openDataSource !== undefined) {
+ mkdirSync(path.join(dir, 'open-data'), { recursive: true });
+ writeFileSync(path.join(dir, 'open-data', 'index.ts'), openDataSource);
+ }
+ return { root: dir, out: path.join(dir, 'dist-wechat') };
+ }
+
+ const exportIt = (root: string, out: string) => exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wxwasm'),
+ outDir: out,
+ platform: 'wechat',
+ });
+
+ afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+
+ it('a project without one declares no context — an absent directory would fail the host compile', async () => {
+ const { root: r, out: o } = scaffold();
+ const res = await exportIt(r, o);
+ expect(res.ok).toBe(true);
+ expect(existsSync(path.join(o, 'open-data'))).toBe(false);
+ expect(JSON.parse(readFileSync(path.join(o, 'game.json'), 'utf8'))).not.toHaveProperty('openDataContext');
+ }, 60_000);
+
+ it('a project with one is bundled beside the game and named in game.json', async () => {
+ const { root: r, out: o } = scaffold(
+ 'const draw = (n?: { rows?: string[] }) => n?.rows?.length ?? 0;\n'
+ + 'wx.onMessage((m: { rows?: string[] }) => { draw(m); });\n'
+ + 'declare const wx: { onMessage(cb: (m: unknown) => void): void };\n',
+ );
+ const res = await exportIt(r, o);
+ expect(res.ok).toBe(true);
+
+ const bundled = path.join(o, 'open-data', 'index.js');
+ expect(existsSync(bundled)).toBe(true);
+ expect(JSON.parse(readFileSync(path.join(o, 'game.json'), 'utf8')).openDataContext).toBe('open-data');
+
+ // Down-levelled to the vendor's syntax floor like every other .js in the
+ // package: the host compiles this file too, and real-device WeChat rejects
+ // the optional chaining the source is written with.
+ const code = readFileSync(bundled, 'utf8');
+ expect(code).not.toContain('?.');
+ }, 60_000);
+
+ it('a context that imports the engine fails the export, not the device', async () => {
+ const { root: r, out: o } = scaffold("import { Assets } from 'esengine';\nAssets.toString();\n");
+ const res = await exportIt(r, o);
+ expect(res.ok).toBe(false);
+ expect(res.errors.join('\n')).toMatch(/esengine/);
+ // And a failed context leaves the config pointing at nothing.
+ expect(JSON.parse(readFileSync(path.join(o, 'game.json'), 'utf8'))).not.toHaveProperty('openDataContext');
+ }, 60_000);
+});
diff --git a/desktop/tests/platform-catalog.test.ts b/desktop/tests/platform-catalog.test.ts
index 3da69d76e..9c39d669b 100644
--- a/desktop/tests/platform-catalog.test.ts
+++ b/desktop/tests/platform-catalog.test.ts
@@ -189,7 +189,7 @@ describe('createProjectPlatform — scaffolding', () => {
const loaded = await loadProjectPlatform(root, 'acme-play', dirs());
expect(loaded!.profile.runtimeProfileModule).toBe(path.join(root, 'src', 'platforms', 'acme-play.runtime.ts'));
expect(loaded!.defaultOut).toBe('dist-acme-play');
- expect(loaded!.profile.emitConfigFiles({ title: 'T', appid: '', orientation: 'portrait', subPackages: [], includeSuffixes: [] })[0].file)
+ expect(loaded!.profile.emitConfigFiles({ title: 'T', appid: '', orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' })[0].file)
.toBe('game.json');
});
@@ -239,7 +239,7 @@ describe('loadProjectPlatform — the profile handed to exportMiniGame', () => {
expect(entry).toContain("require('./game-bundle.js')");
// And the project's own emitter is what runs for config.
- expect(p.emitConfigFiles({ title: 'T', appid: '', orientation: 'portrait', subPackages: [], includeSuffixes: [] }))
+ expect(p.emitConfigFiles({ title: 'T', appid: '', orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' }))
.toEqual([{ file: 'game.json', content: '{"t":"T"}' }]);
});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index cdccfcb6e..e7be3f087 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -4766,6 +4766,8 @@ onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
+openDataCanvas: (() => PlatformCanvas | null) | undefined
+openDataPostMessage: ((message: Record<string, unknown>) => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefined
readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined
@@ -4773,6 +4775,7 @@ readFile: (path: string) => Promise<ArrayBuffer>
readTextFile: (path: string) => Promise<string>
registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined
removeStorageItem: (key: string) => void
+setCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefined
setStorageItem: (key: string, value: string) => void
share: ((options: PlatformShareOptions) => void) | undefined
unbindInputEvents: (() => void) | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 130017f10..a7eeaf960 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -4922,6 +4922,8 @@ onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
+openDataCanvas: (() => PlatformCanvas | null) | undefined
+openDataPostMessage: ((message: Record<string, unknown>) => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefined
readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined
@@ -4929,6 +4931,7 @@ readFile: (path: string) => Promise<ArrayBuffer>
readTextFile: (path: string) => Promise<string>
registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined
removeStorageItem: (key: string) => void
+setCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefined
setStorageItem: (key: string, value: string) => void
share: ((options: PlatformShareOptions) => void) | undefined
unbindInputEvents: (() => void) | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 54c8997fa..8015a267e 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -4761,6 +4761,8 @@ onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
+openDataCanvas: (() => PlatformCanvas | null) | undefined
+openDataPostMessage: ((message: Record<string, unknown>) => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefined
readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined
@@ -4768,6 +4770,7 @@ readFile: (path: string) => Promise<ArrayBuffer>
readTextFile: (path: string) => Promise<string>
registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined
removeStorageItem: (key: string) => void
+setCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefined
setStorageItem: (key: string, value: string) => void
share: ((options: PlatformShareOptions) => void) | undefined
unbindInputEvents: (() => void) | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 547f984fd..e54121037 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -4135,6 +4135,7 @@ createInnerAudioContext: () => MiniGameInnerAudioContext
createInterstitialAd: ((opts: { adUnitId: string; }) => MiniGameInterstitialAd) | undefined
createRewardedVideoAd: ((opts: { adUnitId: string; }) => MiniGameRewardedVideoAd) | undefined
getFileSystemManager: () => MiniGameFileSystemManager
+getOpenDataContext: (() => MiniGameOpenDataContext) | undefined
getStorageInfoSync: () => MiniGameStorageInfo
getStorageSync: (key: string) => unknown
getSystemInfoSync: () => MiniGameSystemInfo
@@ -4159,6 +4160,7 @@ onTouchStart: (cb: (res: MiniGameTouchEvent) => void) => void
removeStorageSync: (key: string) => void
request: (opts: MiniGameRequestOptions) => void
setStorageSync: (key: string, value: string) => void
+setUserCloudStorage: ((opts: { KVDataList: MiniGameKVData[]; success?: () => void; fail?: (err: unknown) => void; complete?: () => void; }) => void) | undefined
shareAppMessage: ((opts: MiniGameShareOptions) => void) | undefined
```
@@ -4220,9 +4222,12 @@ name: PlatformName
now: () => number
onMemoryWarning: (callback: () => void) => () => void
onShareRequest: (provide: () => PlatformShareOptions) => void
+openDataCanvas: () => PlatformCanvas | null
+openDataPostMessage: (message: Record<string, unknown>) => void
readFile: (path: string) => Promise<ArrayBuffer>
readTextFile: (path: string) => Promise<string>
removeStorageItem: (key: string) => void
+setCloudKeyValues: (entries: Readonly<Record<string, string>>) => boolean
setStorageItem: (key: string, value: string) => void
share: (options: PlatformShareOptions) => void
unbindInputEvents: () => void
@@ -4984,6 +4989,8 @@ onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
+openDataCanvas: (() => PlatformCanvas | null) | undefined
+openDataPostMessage: ((message: Record<string, unknown>) => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefined
readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined
@@ -4991,6 +4998,7 @@ readFile: (path: string) => Promise<ArrayBuffer>
readTextFile: (path: string) => Promise<string>
registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined
removeStorageItem: (key: string) => void
+setCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefined
setStorageItem: (key: string, value: string) => void
share: ((options: PlatformShareOptions) => void) | undefined
unbindInputEvents: (() => void) | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 1270e86b3..7526fbe89 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -4768,6 +4768,8 @@ onAppHide: ((callback: () => void) => () => void) | undefined
onAppShow: ((callback: () => void) => () => void) | undefined
onMemoryWarning: ((callback: () => void) => () => void) | undefined
onShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined
+openDataCanvas: (() => PlatformCanvas | null) | undefined
+openDataPostMessage: ((message: Record<string, unknown>) => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefined
readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefined
@@ -4775,6 +4777,7 @@ readFile: (path: string) => Promise<ArrayBuffer>
readTextFile: (path: string) => Promise<string>
registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefined
removeStorageItem: (key: string) => void
+setCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefined
setStorageItem: (key: string, value: string) => void
share: ((options: PlatformShareOptions) => void) | undefined
unbindInputEvents: (() => void) | undefined
diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.ts
index ec7f14f3a..08f53afb3 100644
--- a/sdk/src/platform/base.ts
+++ b/sdk/src/platform/base.ts
@@ -299,6 +299,50 @@ export function platformOnShareRequest(provide: () => import('./types').Platform
return true;
}
+/**
+ * Whether this platform has a USABLE open data context — what a leaderboard
+ * reads to hide itself honestly (web, native and the editor have none).
+ *
+ * Method presence is not the answer here, the way it is for share: the
+ * mini-game family is ONE adapter, so every vendor defines these, and a game
+ * whose package declares no context directory has none even on a host that
+ * supports them. So the honest probe is the same one the ad path uses — ask
+ * for the thing and treat null as "not here".
+ */
+export function platformCanOpenData(): boolean {
+ if (!isPlatformInitialized()) return false;
+ const p = getPlatform();
+ return p.openDataPostMessage !== undefined && p.openDataCanvas?.() != null;
+}
+
+/**
+ * Send one message into the open data context; false where there is none.
+ * One way: the hosts offer no path back, so there is nothing to await.
+ *
+ * Gated on the same probe rather than on method presence — otherwise this
+ * reports a delivery it did not make, on every mini-game host without a
+ * context, which is the answer a caller is least able to check.
+ */
+export function platformOpenDataPostMessage(message: Record<string, unknown>): boolean {
+ if (!platformCanOpenData()) return false;
+ getPlatform().openDataPostMessage!(message);
+ return true;
+}
+
+/** The canvas the open data context draws on, for sampling as a texture. */
+export function platformOpenDataCanvas(): import('./types').PlatformCanvas | null {
+ if (!isPlatformInitialized()) return null;
+ return getPlatform().openDataCanvas?.() ?? null;
+}
+
+/** Write this player's own cloud rows; false where the host has no such store.
+ * Unlike a share, "there was nowhere to write this" is knowable at call time,
+ * so it is reported rather than swallowed. */
+export function platformSetCloudKeyValues(entries: Readonly<Record<string, string>>): boolean {
+ if (!isPlatformInitialized()) return false;
+ return getPlatform().setCloudKeyValues?.(entries) ?? false;
+}
+
export function platformDevicePixelRatio(): number {
if (currentPlatform) {
return currentPlatform.devicePixelRatio();
diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.ts
index a0f9b247c..96f5ca2eb 100644
--- a/sdk/src/platform/index.ts
+++ b/sdk/src/platform/index.ts
@@ -60,6 +60,10 @@ export {
platformCanShare,
platformShare,
platformOnShareRequest,
+ platformCanOpenData,
+ platformOpenDataPostMessage,
+ platformOpenDataCanvas,
+ platformSetCloudKeyValues,
} from './base';
// Note: webAdapter is exported here for initialization
diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.ts
index 283e842af..b4cb37df4 100644
--- a/sdk/src/platform/minigame/adapter.ts
+++ b/sdk/src/platform/minigame/adapter.ts
@@ -32,7 +32,10 @@ import type { PlatformAudioBackend } from '../../audio/PlatformAudioBackend';
import type { PlatformVideoBackend, VideoBackendContext } from '../../video/PlatformVideoBackend';
import { toBuildPath } from '../../assetTypes';
import { log } from '../../util/logger';
-import type { MiniGameGlobal, MiniGameProfile, MiniGameCanvas, MiniGameFileSystemManager, MiniGameTouchEvent } from './api';
+import type {
+ MiniGameGlobal, MiniGameProfile, MiniGameCanvas, MiniGameFileSystemManager, MiniGameTouchEvent,
+ MiniGameOpenDataContext,
+} from './api';
import { createPrimaryPointer } from '../primaryPointer';
import { mgReadFileSync, mgReadTextFileSync, mgFileExistsSync } from './fs';
import { mgLoadImagePixels } from './image';
@@ -50,6 +53,8 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {
private readonly g_: MiniGameGlobal;
private fs_: MiniGameFileSystemManager | null = null;
private inputCleanup_: (() => void) | null = null;
+ private openDataCtx_: MiniGameOpenDataContext | null = null;
+ private openDataResolved_ = false;
constructor(profile: MiniGameProfile) {
this.profile_ = profile;
@@ -181,6 +186,50 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {
this.g_.onShareAppMessage?.call(this.g_, provide);
}
+ /**
+ * The open data context, resolved once and kept.
+ *
+ * `getOpenDataContext()` is documented as returning the same object every
+ * time, but it is not free — and this is asked on the frame a leaderboard
+ * opens, not at boot, because a host whose package declares no context
+ * throws rather than answering null. Caching a THROW as "absent" is the
+ * point: the second ask would throw again to no one's benefit.
+ */
+ private openData_(): MiniGameOpenDataContext | null {
+ if (this.openDataResolved_) return this.openDataCtx_;
+ this.openDataResolved_ = true;
+ try {
+ this.openDataCtx_ = this.g_.getOpenDataContext?.call(this.g_) ?? null;
+ } catch {
+ this.openDataCtx_ = null;
+ }
+ return this.openDataCtx_;
+ }
+
+ /** Send one message into the open data context. Absent context = no-op:
+ * the caller already asked `available` if it cared. */
+ openDataPostMessage(message: Record<string, unknown>): void {
+ this.openData_()?.postMessage(message);
+ }
+
+ /** The shared canvas, for the main domain to sample as a texture. The same
+ * honest cast {@link createCanvas} makes, for the same reason. */
+ openDataCanvas(): PlatformCanvas | null {
+ return (this.openData_()?.canvas as unknown as PlatformCanvas | undefined) ?? null;
+ }
+
+ /** Write this player's own rows to the host's cloud store. Whether there
+ * was a store is reported; whether the write landed is not — that failure
+ * (offline) is the one no host distinguishes for us. */
+ setCloudKeyValues(entries: Readonly<Record<string, string>>): boolean {
+ const set = this.g_.setUserCloudStorage;
+ if (!set) return false;
+ set.call(this.g_, {
+ KVDataList: Object.entries(entries).map(([key, value]) => ({ key, value })),
+ });
+ return true;
+ }
+
onMemoryWarning(callback: () => void): () => void {
const on = this.g_.onMemoryWarning;
const off = this.g_.offMemoryWarning;
diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.ts
index 4b8f3ae33..9e2f6648d 100644
--- a/sdk/src/platform/minigame/api.ts
+++ b/sdk/src/platform/minigame/api.ts
@@ -156,6 +156,29 @@ export interface MiniGameShareOptions {
query?: string;
}
+/**
+ * The open data context, seen from the MAIN domain.
+ *
+ * It is a second JS runtime with no WebGL, no wasm and almost none of the host
+ * API — and the only place a player's FRIENDS can be read at all. It draws on
+ * `canvas`, which the main domain samples as a texture; `postMessage` is how it
+ * is told what to draw. There is no channel back: no host offers sub→main
+ * messaging, which is why nothing in this engine's leaderboard asks the context
+ * a question.
+ */
+export interface MiniGameOpenDataContext {
+ postMessage(message: Record<string, unknown>): void;
+ /** The shared canvas. The context draws here; the main domain samples it. */
+ readonly canvas: MiniGameCanvas;
+}
+
+/** One entry of the host's per-player cloud store — the rows a leaderboard is
+ * assembled from. Writable only for the player themselves. */
+export interface MiniGameKVData {
+ key: string;
+ value: string;
+}
+
/** The socket task `connectSocket()` returns. WeChat's `SocketTask` fits. */
export interface MiniGameSocketTask {
send(opts: { data: string | ArrayBuffer }): void;
@@ -222,6 +245,19 @@ export interface MiniGameGlobal {
* own menu. The host calls `cb` at share time, not at registration. */
onShareAppMessage?(cb: () => MiniGameShareOptions): void;
+ /** The open data context, if this host has one. Absent on a host without
+ * friend data, and on a game whose package declares no context directory. */
+ getOpenDataContext?(): MiniGameOpenDataContext;
+ /** Write THIS player's rows into the host's cloud store. Writing is the main
+ * domain's half of a leaderboard; reading — anyone's, including the
+ * player's own — belongs to the open data context alone. */
+ setUserCloudStorage?(opts: {
+ KVDataList: MiniGameKVData[];
+ success?: () => void;
+ fail?: (err: unknown) => void;
+ complete?: () => void;
+ }): void;
+
getStorageSync(key: string): unknown;
setStorageSync(key: string, value: string): void;
removeStorageSync(key: string): void;
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index ff70ac4ae..2a2a750af 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -507,6 +507,20 @@ export interface PlatformAdapter {
* host asks at share time, so the provider can answer with live state. */
onShareRequest?(provide: () => PlatformShareOptions): void;
+ /** Send a message into the open data context — the second JS runtime that
+ * is the only place friend data can be read. ONE WAY by nature: no host
+ * offers a channel back, so this returns nothing and nothing awaits it. */
+ openDataPostMessage?(message: Record<string, unknown>): void;
+ /** The canvas the open data context draws on, for the main domain to sample
+ * as a texture. Null when the host has the capability but this game's
+ * package declares no context to draw with. */
+ openDataCanvas?(): PlatformCanvas | null;
+ /** Write this player's own rows to the host's per-player cloud store — the
+ * writable half of a leaderboard. Reading is the open data context's
+ * alone, which is the whole reason that context exists. Returns whether
+ * there was a store to write to; the write itself is fire-and-forget. */
+ setCloudKeyValues?(entries: Readonly<Record<string, string>>): boolean;
+
devicePixelRatio(): number;
getStorageItem(key: string): string | null;
diff --git a/sdk/tests/minigame-opendata.test.ts b/sdk/tests/minigame-opendata.test.ts
new file mode 100644
index 000000000..37168a9eb
--- /dev/null
+++ b/sdk/tests/minigame-opendata.test.ts
@@ -0,0 +1,115 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The open data context surface over a fake host global: the one-way
+ * message channel, the shared canvas as a texture source, the cloud rows
+ * a player may write, and — the part that matters most — what "this host
+ * has no context" looks like from every angle a caller can ask.
+ */
+import { describe, it, expect } from 'vitest';
+import { MiniGamePlatformAdapter } from '../src/platform/minigame/adapter';
+import { setPlatform, platformCanOpenData, platformOpenDataPostMessage } from '../src/platform/base';
+import type {
+ MiniGameGlobal, MiniGameProfile, MiniGameCanvas, MiniGameOpenDataContext, MiniGameKVData,
+} from '../src/platform/minigame/api';
+
+const canvas = (): MiniGameCanvas => ({ width: 512, height: 512, getContext: () => ({}) });
+
+function adapterOver(globalPatch: Partial<MiniGameGlobal>): MiniGamePlatformAdapter {
+ const profile: MiniGameProfile = {
+ id: 'wechat',
+ hostLabel: 'Test',
+ global: {
+ getSystemInfoSync: () => ({ pixelRatio: 1, screenWidth: 1, screenHeight: 1, platform: 'devtools', language: 'zh_CN' }),
+ ...globalPatch,
+ } as unknown as MiniGameGlobal,
+ };
+ return new MiniGamePlatformAdapter(profile);
+}
+
+/** A host with a context, recording what the main domain sent it. */
+function hostWithContext(): { patch: Partial<MiniGameGlobal>; sent: Record<string, unknown>[]; asks: () => number } {
+ const sent: Record<string, unknown>[] = [];
+ const ctx: MiniGameOpenDataContext = {
+ postMessage: (m) => { sent.push(m); },
+ canvas: canvas(),
+ };
+ let asks = 0;
+ return {
+ sent,
+ asks: () => asks,
+ patch: { getOpenDataContext: () => { asks++; return ctx; } },
+ };
+}
+
+describe('mini-game open data context', () => {
+ it('sends the main domain\'s messages into the context', () => {
+ const host = hostWithContext();
+ adapterOver(host.patch).openDataPostMessage({ kind: 'show', rows: 10 });
+ expect(host.sent).toEqual([{ kind: 'show', rows: 10 }]);
+ });
+
+ it('hands out the shared canvas for the main domain to sample', () => {
+ const host = hostWithContext();
+ expect(adapterOver(host.patch).openDataCanvas()).toMatchObject({ width: 512, height: 512 });
+ });
+
+ it('resolves the context once, however many times it is used', () => {
+ const host = hostWithContext();
+ const adapter = adapterOver(host.patch);
+ adapter.openDataCanvas();
+ adapter.openDataPostMessage({ a: 1 });
+ adapter.openDataPostMessage({ b: 2 });
+ expect(host.asks()).toBe(1);
+ });
+
+ it('reads a host without the capability as absent, not as an error', () => {
+ const adapter = adapterOver({});
+ expect(adapter.openDataCanvas()).toBeNull();
+ expect(() => adapter.openDataPostMessage({ a: 1 })).not.toThrow();
+ });
+
+ it('reads a THROWN context as absent, and does not ask twice', () => {
+ // A package that declares no context directory does not answer null —
+ // the host throws. Asking again would throw again, to no one's benefit.
+ let asks = 0;
+ const adapter = adapterOver({
+ getOpenDataContext: () => { asks++; throw new Error('no such context'); },
+ });
+ expect(adapter.openDataCanvas()).toBeNull();
+ expect(adapter.openDataCanvas()).toBeNull();
+ expect(asks).toBe(1);
+ });
+
+ it('writes the player\'s own rows in the host\'s KV shape', () => {
+ const written: MiniGameKVData[][] = [];
+ const adapter = adapterOver({
+ setUserCloudStorage: (opts: { KVDataList: MiniGameKVData[] }) => { written.push(opts.KVDataList); },
+ });
+ expect(adapter.setCloudKeyValues({ score: '4200', level: '7' })).toBe(true);
+ expect(written).toEqual([[{ key: 'score', value: '4200' }, { key: 'level', value: '7' }]]);
+ });
+
+ it('says so when there was no store to write to', () => {
+ expect(adapterOver({}).setCloudKeyValues({ score: '1' })).toBe(false);
+ });
+});
+
+describe('platformCanOpenData', () => {
+ // The family is ONE adapter, so every vendor DEFINES these methods —
+ // presence cannot be the probe the way it is for share. The honest answer
+ // is whether a canvas actually comes back, the same null-answer contract
+ // the ad path uses.
+ it('is false on a family adapter whose host has no context', () => {
+ setPlatform(adapterOver({}));
+ expect(platformCanOpenData()).toBe(false);
+ // And a send reports that it went nowhere, rather than the `true` that
+ // method presence alone would have answered.
+ expect(platformOpenDataPostMessage({ a: 1 })).toBe(false);
+ });
+
+ it('is true only when the host hands back a canvas', () => {
+ setPlatform(adapterOver(hostWithContext().patch));
+ expect(platformCanOpenData()).toBe(true);
+ });
+});