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.

refactor(platform): unify WeChat into a mini-game platform family

yhh5e41a3103aa9
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 7162b4af8..c86101467 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -4199,7 +4199,7 @@ instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Impor
language: (() => string) | undefined
loadImagePixels: (path: string) => Promise<ImageLoadResult>
loadSubpackage: ((name: string) => Promise<void>) | undefined
-name: "web" | "wechat" | "node"
+name: "web" | "wechat" | "douyin" | "node"
now: () => number
onMemoryWarning: ((callback: () => void) => () => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
@@ -4271,7 +4271,7 @@ url: string
## PlatformType — type
```
-'web' | 'wechat'
+'web' | 'wechat' | 'douyin'
```
## PlatformVideoBackend — interface
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 6125834f8..fa8e0898c 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -4194,7 +4194,7 @@ instantiateWasm: (pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Impor
language: (() => string) | undefined
loadImagePixels: (path: string) => Promise<ImageLoadResult>
loadSubpackage: ((name: string) => Promise<void>) | undefined
-name: "web" | "wechat" | "node"
+name: "web" | "wechat" | "douyin" | "node"
now: () => number
onMemoryWarning: ((callback: () => void) => () => void) | undefined
pollGamepads: (() => GamepadSnapshot[]) | undefined
@@ -4266,7 +4266,7 @@ url: string
## PlatformType — type
```
-'web' | 'wechat'
+'web' | 'wechat' | 'douyin'
```
## PlatformVideoBackend — interface
diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.ts
index 62eff90d2..5301431ac 100644
--- a/sdk/src/platform/base.ts
+++ b/sdk/src/platform/base.ts
@@ -49,12 +49,23 @@ export function getPlatformType(): PlatformAdapter['name'] | null {
}
/**
- * Check if running on WeChat
+ * Check if running on WeChat specifically (true vendor identity).
+ * Prefer isMiniGame() for "no DOM / packaged fs / subpackages" checks that hold
+ * for every mini-game vendor, not just WeChat.
*/
export function isWeChat(): boolean {
return currentPlatform?.name === 'wechat';
}
+/**
+ * Check if running on any mini-game host (WeChat, Douyin, …) — the capability
+ * family that shares the packaged-filesystem / subpackage / no-DOM model.
+ */
+export function isMiniGame(): boolean {
+ const name = currentPlatform?.name;
+ return name === 'wechat' || name === 'douyin';
+}
+
/**
* Check if running on Web
*/
diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.ts
index 8e609b4ba..5bab9ab14 100644
--- a/sdk/src/platform/index.ts
+++ b/sdk/src/platform/index.ts
@@ -22,6 +22,7 @@ export {
getPlatformType,
isPlatformInitialized,
isWeChat,
+ isMiniGame,
isWeb,
platformFetch,
platformReadFile,
diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.ts
new file mode 100644
index 000000000..e3489a884
--- /dev/null
+++ b/sdk/src/platform/minigame/adapter.ts
@@ -0,0 +1,256 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file adapter.ts
+ * @brief The mini-game platform adapter family.
+ *
+ * ONE implementation of `PlatformAdapter` shared by every mini-game vendor. It
+ * reads `profile.global` for the shared capabilities (canvas, fs, fetch, image,
+ * input, storage, subpackage, memory-warning, DPR, language) and delegates the
+ * genuine per-vendor divergences (WASM, audio, video, sockets) to the profile.
+ *
+ * Adding a vendor = one `MiniGameProfile`, not a parallel adapter.
+ */
+
+import type {
+ PlatformAdapter,
+ PlatformRequestOptions,
+ PlatformResponse,
+ WasmInstantiateResult,
+ InputEventCallbacks,
+ ImageLoadResult,
+ PlatformSocket,
+ PlatformSocketOptions,
+} from '../types';
+import type { PlatformAudioBackend } from '../../audio/PlatformAudioBackend';
+import type { PlatformVideoBackend, VideoBackendContext } from '../../video/PlatformVideoBackend';
+import { toBuildPath } from '../../assetTypes';
+import { log } from '../../logger';
+import type { MiniGameGlobal, MiniGameProfile, MiniGameFileSystemManager } from './api';
+import { mgReadFileSync, mgReadTextFileSync, mgFileExistsSync } from './fs';
+import { mgLoadImagePixels } from './image';
+import { mgFetch } from './fetch';
+
+export class MiniGamePlatformAdapter implements PlatformAdapter {
+ readonly name: PlatformAdapter['name'];
+
+ private readonly profile_: MiniGameProfile;
+ private readonly g_: MiniGameGlobal;
+ private fs_: MiniGameFileSystemManager | null = null;
+ private inputCleanup_: (() => void) | null = null;
+
+ constructor(profile: MiniGameProfile) {
+ this.profile_ = profile;
+ this.g_ = profile.global;
+ this.name = profile.id;
+ }
+
+ private fs(): MiniGameFileSystemManager {
+ if (!this.fs_) this.fs_ = this.g_.getFileSystemManager();
+ return this.fs_;
+ }
+
+ async fetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse> {
+ return mgFetch(this.g_, url, options);
+ }
+
+ async readFile(path: string): Promise<ArrayBuffer> {
+ return mgReadFileSync(this.fs(), toBuildPath(path), this.profile_.hostLabel);
+ }
+
+ async readTextFile(path: string): Promise<string> {
+ return mgReadTextFileSync(this.fs(), toBuildPath(path), this.profile_.hostLabel);
+ }
+
+ async fileExists(path: string): Promise<boolean> {
+ return mgFileExistsSync(this.fs(), toBuildPath(path));
+ }
+
+ async loadImagePixels(path: string): Promise<ImageLoadResult> {
+ return mgLoadImagePixels(this.g_, path);
+ }
+
+ async instantiateWasm(
+ pathOrBuffer: string | ArrayBuffer,
+ imports: WebAssembly.Imports,
+ ): Promise<WasmInstantiateResult> {
+ return this.profile_.instantiateWasm(pathOrBuffer, imports);
+ }
+
+ createImage(): HTMLImageElement {
+ return this.g_.createImage() as unknown as HTMLImageElement;
+ }
+
+ /** Download an on-demand subpackage so its files become readable. */
+ loadSubpackage(name: string): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ const load = this.g_.loadSubpackage;
+ if (!load) {
+ resolve();
+ return;
+ }
+ load.call(this.g_, {
+ name,
+ success: () => resolve(),
+ fail: (err: unknown) =>
+ reject(new Error(`loadSubpackage("${name}") failed: ${JSON.stringify(err)}`)),
+ complete: () => {},
+ });
+ });
+ }
+
+ onMemoryWarning(callback: () => void): () => void {
+ const on = this.g_.onMemoryWarning;
+ const off = this.g_.offMemoryWarning;
+ if (!on) return () => {};
+ const listener = () => callback();
+ on.call(this.g_, listener);
+ return () => off?.call(this.g_, listener);
+ }
+
+ createCanvas(width: number, height: number): HTMLCanvasElement | OffscreenCanvas {
+ const canvas = this.g_.createCanvas() as unknown as HTMLCanvasElement;
+ canvas.width = width;
+ canvas.height = height;
+ return canvas;
+ }
+
+ now(): number {
+ return Date.now();
+ }
+
+ bindInputEvents(callbacks: InputEventCallbacks, _target?: unknown): void {
+ if (this.inputCleanup_) {
+ this.inputCleanup_();
+ this.inputCleanup_ = null;
+ }
+
+ const g = this.g_;
+
+ const onKeyDown = (res: { code: string }) => callbacks.onKeyDown(res.code);
+ const onKeyUp = (res: { code: string }) => callbacks.onKeyUp(res.code);
+
+ const hasKeyboard = typeof g.onKeyDown === 'function';
+ if (hasKeyboard) {
+ g.onKeyDown?.(onKeyDown);
+ g.onKeyUp?.(onKeyUp);
+ }
+
+ let primaryTouchId: number | null = null;
+
+ const onTouchStart = (res: { changedTouches: { identifier: number; clientX: number; clientY: number }[] }) => {
+ for (const touch of res.changedTouches) {
+ callbacks.onTouchStart?.(touch.identifier, touch.clientX, touch.clientY);
+ if (primaryTouchId === null) {
+ primaryTouchId = touch.identifier;
+ callbacks.onPointerDown(0, touch.clientX, touch.clientY);
+ }
+ }
+ };
+ const onTouchMove = (res: { changedTouches: { identifier: number; clientX: number; clientY: number }[] }) => {
+ for (const touch of res.changedTouches) {
+ callbacks.onTouchMove?.(touch.identifier, touch.clientX, touch.clientY);
+ if (touch.identifier === primaryTouchId) {
+ callbacks.onPointerMove(touch.clientX, touch.clientY);
+ }
+ }
+ };
+ const onTouchEnd = (res: { changedTouches: { identifier: number; clientX: number; clientY: number }[] }) => {
+ for (const touch of res.changedTouches) {
+ callbacks.onTouchEnd?.(touch.identifier);
+ if (touch.identifier === primaryTouchId) {
+ primaryTouchId = null;
+ callbacks.onPointerUp(0);
+ }
+ }
+ };
+
+ g.onTouchStart(onTouchStart);
+ g.onTouchMove(onTouchMove);
+ g.onTouchEnd(onTouchEnd);
+
+ this.inputCleanup_ = () => {
+ if (hasKeyboard) {
+ g.offKeyDown?.(onKeyDown);
+ g.offKeyUp?.(onKeyUp);
+ }
+ g.offTouchStart(onTouchStart);
+ g.offTouchMove(onTouchMove);
+ g.offTouchEnd(onTouchEnd);
+ };
+ }
+
+ unbindInputEvents(): void {
+ if (this.inputCleanup_) {
+ this.inputCleanup_();
+ this.inputCleanup_ = null;
+ }
+ }
+
+ createAudioBackend(): PlatformAudioBackend {
+ return this.profile_.createAudioBackend();
+ }
+
+ createVideoBackend(ctx: VideoBackendContext): PlatformVideoBackend {
+ return this.profile_.createVideoBackend(ctx);
+ }
+
+ createSocket(options: PlatformSocketOptions): PlatformSocket {
+ return this.profile_.createSocket(options);
+ }
+
+ getStorageItem(key: string): string | null {
+ try {
+ const value = this.g_.getStorageSync(key);
+ return typeof value === 'string' ? value : null;
+ } catch {
+ return null;
+ }
+ }
+
+ setStorageItem(key: string, value: string): void {
+ try {
+ this.g_.setStorageSync(key, value);
+ } catch (e) {
+ log.warn(this.profile_.id, 'setStorageSync failed', e);
+ }
+ }
+
+ removeStorageItem(key: string): void {
+ try {
+ this.g_.removeStorageSync(key);
+ } catch (e) {
+ log.warn(this.profile_.id, 'removeStorageSync failed', e);
+ }
+ }
+
+ devicePixelRatio(): number {
+ try {
+ return this.g_.getSystemInfoSync?.()?.pixelRatio ?? 1;
+ } catch {
+ return 1;
+ }
+ }
+
+ language(): string {
+ try {
+ // Hosts report 'zh_CN'-style tags; platformLanguage() normalizes underscores.
+ return this.g_.getSystemInfoSync?.()?.language ?? 'en';
+ } catch {
+ return 'en';
+ }
+ }
+
+ clearStorage(prefix: string): void {
+ try {
+ const { keys } = this.g_.getStorageInfoSync();
+ for (const k of keys) {
+ if (k.startsWith(prefix)) {
+ this.g_.removeStorageSync(k);
+ }
+ }
+ } catch (e) {
+ log.warn(this.profile_.id, 'clearStorage failed', e);
+ }
+ }
+}
diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.ts
new file mode 100644
index 000000000..4c75e6acd
--- /dev/null
+++ b/sdk/src/platform/minigame/api.ts
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file api.ts
+ * @brief Normalized mini-game host surface + per-vendor profile descriptor.
+ *
+ * WeChat (`wx`) and Douyin (`tt`) are two vendors of the same "mini-game
+ * platform" family: their global objects expose a near-identical API. This file
+ * models only the subset the engine actually uses; each vendor's global
+ * satisfies `MiniGameGlobal` structurally and is bound at the profile boundary
+ * (`sdk/src/platform/<vendor>/profile.ts`) with a single cast.
+ *
+ * The family logic (canvas / fs / fetch / image / input / storage) is written
+ * ONCE against `MiniGameGlobal` in `adapter.ts`. Genuinely divergent operations
+ * — WASM instantiation (WeChat's WXWebAssembly vs a standard loader), audio,
+ * video, sockets — are methods on `MiniGameProfile`, not derived from the global.
+ */
+
+import type { PlatformAudioBackend } from '../../audio/PlatformAudioBackend';
+import type { PlatformVideoBackend, VideoBackendContext } from '../../video/PlatformVideoBackend';
+import type { PlatformSocket, PlatformSocketOptions, WasmInstantiateResult } from '../types';
+
+// =============================================================================
+// Normalized host primitives
+// =============================================================================
+
+export interface MiniGameCanvas {
+ width: number;
+ height: number;
+ getContext(type: string, attributes?: unknown): unknown;
+}
+
+export interface MiniGameImage {
+ width: number;
+ height: number;
+ src: string;
+ onload: (() => void) | null;
+ onerror: ((err: unknown) => void) | null;
+}
+
+export interface MiniGameFileSystemManager {
+ readFileSync(path: string, encoding?: string): ArrayBuffer | string;
+ readFile(opts: {
+ filePath: string;
+ encoding?: string;
+ success?: (res: { data: ArrayBuffer | string }) => void;
+ fail?: (err: { errMsg: string }) => void;
+ }): void;
+ access(opts: { path: string; success?: () => void; fail?: (err: { errMsg: string }) => void }): void;
+ accessSync(path: string): void;
+ writeFile(opts: {
+ filePath: string;
+ data: string | ArrayBuffer;
+ encoding?: string;
+ success?: () => void;
+ fail?: (err: { errMsg: string }) => void;
+ }): void;
+}
+
+export interface MiniGameRequestOptions {
+ url: string;
+ method?: string;
+ data?: string | ArrayBuffer;
+ header?: Record<string, string>;
+ responseType?: 'text' | 'arraybuffer';
+ timeout?: number;
+ success?: (res: { statusCode: number; header?: Record<string, string>; data: string | ArrayBuffer }) => void;
+ fail?: (err: { errMsg: string }) => void;
+}
+
+export interface MiniGameSystemInfo {
+ pixelRatio?: number;
+ language?: string;
+ windowWidth?: number;
+ windowHeight?: number;
+}
+
+export interface MiniGameTouch {
+ identifier: number;
+ clientX: number;
+ clientY: number;
+}
+export interface MiniGameTouchEvent {
+ changedTouches: MiniGameTouch[];
+}
+export interface MiniGameKeyEvent {
+ code: string;
+}
+export interface MiniGameStorageInfo {
+ keys: string[];
+}
+
+// =============================================================================
+// The normalized mini-game global
+// =============================================================================
+
+/**
+ * The subset of the mini-game host global (`wx` / `tt`) the engine consumes.
+ * Optional members are capabilities a vendor may lack (keyboard, subpackages,
+ * memory-pressure signal, app show/hide). The adapter probes for them at use
+ * time, so a vendor missing one degrades gracefully rather than throwing.
+ */
+export interface MiniGameGlobal {
+ createCanvas(): MiniGameCanvas;
+ createImage(): MiniGameImage;
+ getFileSystemManager(): MiniGameFileSystemManager;
+ request(opts: MiniGameRequestOptions): void;
+ createInnerAudioContext(): unknown;
+ connectSocket(opts: { url: string; protocols?: string[] }): unknown;
+ getSystemInfoSync(): MiniGameSystemInfo;
+
+ onTouchStart(cb: (res: MiniGameTouchEvent) => void): void;
+ onTouchMove(cb: (res: MiniGameTouchEvent) => void): void;
+ onTouchEnd(cb: (res: MiniGameTouchEvent) => void): void;
+ offTouchStart(cb: (res: MiniGameTouchEvent) => void): void;
+ offTouchMove(cb: (res: MiniGameTouchEvent) => void): void;
+ offTouchEnd(cb: (res: MiniGameTouchEvent) => void): void;
+
+ onKeyDown?(cb: (res: MiniGameKeyEvent) => void): void;
+ onKeyUp?(cb: (res: MiniGameKeyEvent) => void): void;
+ offKeyDown?(cb: (res: MiniGameKeyEvent) => void): void;
+ offKeyUp?(cb: (res: MiniGameKeyEvent) => void): void;
+
+ loadSubpackage?(opts: {
+ name: string;
+ success?: () => void;
+ fail?: (err: unknown) => void;
+ complete?: () => void;
+ }): void;
+ onMemoryWarning?(cb: () => void): void;
+ offMemoryWarning?(cb: () => void): void;
+
+ onShow?(cb: () => void): void;
+ onHide?(cb: () => void): void;
+
+ getStorageSync(key: string): unknown;
+ setStorageSync(key: string, value: string): void;
+ removeStorageSync(key: string): void;
+ getStorageInfoSync(): MiniGameStorageInfo;
+}
+
+// =============================================================================
+// Per-vendor profile
+// =============================================================================
+
+export type MiniGameVendor = 'wechat' | 'douyin';
+
+/**
+ * A vendor described as DATA. The family adapter reads `global` for every shared
+ * capability; the methods below are the genuine per-vendor divergences.
+ */
+export interface MiniGameProfile {
+ /** Vendor identity — used for the adapter `name`, diagnostics, and logs. */
+ readonly id: MiniGameVendor;
+ /** Human label woven into filesystem error guidance ("WeChat" / "抖音"). */
+ readonly hostLabel: string;
+ /** The host global (`wx` / `tt`), bound with a cast at the profile boundary. */
+ readonly global: MiniGameGlobal;
+
+ /** WASM instantiation — the biggest divergence (WeChat's WXWebAssembly vs a
+ * standard loader). Kept off `global` because the WASM entry point is not a
+ * member of the host global on every vendor. */
+ instantiateWasm(pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports): Promise<WasmInstantiateResult>;
+
+ createAudioBackend(): PlatformAudioBackend;
+ createVideoBackend(ctx: VideoBackendContext): PlatformVideoBackend;
+ createSocket(options: PlatformSocketOptions): PlatformSocket;
+}
diff --git a/sdk/src/platform/wechat/fetch.ts b/sdk/src/platform/minigame/fetch.ts
similarity index 78%
rename from sdk/src/platform/wechat/fetch.ts
rename to sdk/src/platform/minigame/fetch.ts
index 29f133fad..84985bd55 100644
--- a/sdk/src/platform/wechat/fetch.ts
+++ b/sdk/src/platform/minigame/fetch.ts
@@ -2,24 +2,23 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file fetch.ts
- * @brief Fetch polyfill for WeChat MiniGame using wx.request
+ * @brief Fetch over a mini-game host's `request` (vendor-neutral).
*/
-/// <reference types="minigame-api-typings" />
-
import type { PlatformRequestOptions, PlatformResponse } from '../types';
+import type { MiniGameGlobal } from './api';
-// =============================================================================
-// WeChat Fetch Implementation
-// =============================================================================
-
-export function wxFetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse> {
+export function mgFetch(
+ g: MiniGameGlobal,
+ url: string,
+ options?: PlatformRequestOptions,
+): Promise<PlatformResponse> {
return new Promise((resolve, reject) => {
const responseType = options?.responseType ?? 'text';
- wx.request({
+ g.request({
url,
- method: (options?.method ?? 'GET') as WechatMinigame.RequestOption['method'],
+ method: options?.method ?? 'GET',
data: options?.body,
header: options?.headers,
responseType: responseType === 'arraybuffer' ? 'arraybuffer' : 'text',
@@ -55,7 +54,6 @@ export function wxFetch(url: string, options?: PlatformRequestOptions): Promise<
if (res.data instanceof ArrayBuffer) {
return Promise.resolve(res.data);
}
- // Convert string to ArrayBuffer
const encoder = new TextEncoder();
const data = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);
return Promise.resolve(encoder.encode(data).buffer);
@@ -63,7 +61,7 @@ export function wxFetch(url: string, options?: PlatformRequestOptions): Promise<
});
},
fail: (err) => {
- reject(new Error(`wx.request failed: ${err.errMsg}`));
+ reject(new Error(`mini-game request failed: ${err.errMsg}`));
},
});
});
@@ -73,11 +71,11 @@ export function wxFetch(url: string, options?: PlatformRequestOptions): Promise<
// Global Fetch Polyfill
// =============================================================================
-export function polyfillFetch(): void {
+export function polyfillFetch(g: MiniGameGlobal): void {
if (typeof globalThis.fetch === 'undefined') {
- (globalThis as any).fetch = async (
+ (globalThis as unknown as { fetch: unknown }).fetch = async (
input: string | URL,
- init?: RequestInit
+ init?: RequestInit,
): Promise<Response> => {
const url = typeof input === 'string' ? input : input.toString();
const options: PlatformRequestOptions = {
@@ -86,9 +84,8 @@ export function polyfillFetch(): void {
body: init?.body as string | ArrayBuffer,
};
- const response = await wxFetch(url, options);
+ const response = await mgFetch(g, url, options);
- // Return a Response-like object
return {
ok: response.ok,
status: response.status,
@@ -97,9 +94,11 @@ export function polyfillFetch(): void {
json: () => response.json(),
text: () => response.text(),
arrayBuffer: () => response.arrayBuffer(),
- blob: () => Promise.reject(new Error('Blob not supported in WeChat')),
- formData: () => Promise.reject(new Error('FormData not supported in WeChat')),
- clone: () => { throw new Error('clone not supported'); },
+ blob: () => Promise.reject(new Error('Blob not supported in mini-game runtime')),
+ formData: () => Promise.reject(new Error('FormData not supported in mini-game runtime')),
+ clone: () => {
+ throw new Error('clone not supported');
+ },
body: null,
bodyUsed: false,
redirected: false,
diff --git a/sdk/src/platform/minigame/fs.ts b/sdk/src/platform/minigame/fs.ts
new file mode 100644
index 000000000..1c16606bf
--- /dev/null
+++ b/sdk/src/platform/minigame/fs.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file fs.ts
+ * @brief Filesystem helpers over a mini-game FileSystemManager (vendor-neutral).
+ *
+ * Thin wrappers over `MiniGameGlobal.getFileSystemManager()`. Path conversion
+ * (toBuildPath) happens at the adapter level, not here — this layer is pure I/O.
+ * The `hostLabel` threads the vendor name ("WeChat" / "抖音") into permission
+ * guidance so the message names the right devtools.
+ */
+
+import { isCustomExtension } from '../../assetTypes';
+import type { MiniGameFileSystemManager } from './api';
+
+export function formatReadError(path: string, errMsg: string, hostLabel: string): string {
+ const msg = errMsg.toLowerCase();
+ if (msg.includes('permission denied')) {
+ if (isCustomExtension(path)) {
+ const ext = path.substring(path.lastIndexOf('.'));
+ return `[ESEngine] Cannot read "${path}": ${hostLabel} blocked access to "${ext}" files. `
+ + `Add { type: "suffix", value: "${ext}" } to packOptions.include in project.config.json. `
+ + `Some suffixes are denied regardless of packOptions — the exporter restages those `
+ + `as "${ext}.bin" (ktx2/esv already are); re-export if this file predates that.`;
+ }
+ return `[ESEngine] Cannot read "${path}": permission denied. Check file is included in ${hostLabel} package`;
+ }
+ if (msg.includes('no such file') || msg.includes('not found')) {
+ return `[ESEngine] File not found: "${path}". Ensure the asset is included in the build `
+ + `(referenced by a scene or added to an addressable group with export mode "always")`;
+ }
+ return `[ESEngine] Failed to read "${path}": ${errMsg}`;
+}
+
+export function mgReadFileSync(fs: MiniGameFileSystemManager, path: string, hostLabel: string): ArrayBuffer {
+ try {
+ return fs.readFileSync(path) as ArrayBuffer;
+ } catch (e) {
+ throw new Error(formatReadError(path, e instanceof Error ? e.message : String(e), hostLabel));
+ }
+}
+
+export function mgReadTextFileSync(
+ fs: MiniGameFileSystemManager,
+ path: string,
+ hostLabel: string,
+ encoding: 'utf8' | 'utf-8' = 'utf-8',
+): string {
+ try {
+ return fs.readFileSync(path, encoding) as string;
+ } catch (e) {
+ throw new Error(formatReadError(path, e instanceof Error ? e.message : String(e), hostLabel));
+ }
+}
+
+export function mgReadFile(fs: MiniGameFileSystemManager, path: string, hostLabel: string): Promise<ArrayBuffer> {
+ return new Promise((resolve, reject) => {
+ fs.readFile({
+ filePath: path,
+ success: (res) => resolve(res.data as ArrayBuffer),
+ fail: (err) => reject(new Error(formatReadError(path, err.errMsg, hostLabel))),
+ });
+ });
+}
+
+export function mgReadTextFile(
+ fs: MiniGameFileSystemManager,
+ path: string,
+ hostLabel: string,
+ encoding: 'utf8' | 'utf-8' = 'utf-8',
+): Promise<string> {
+ return new Promise((resolve, reject) => {
+ fs.readFile({
+ filePath: path,
+ encoding,
+ success: (res) => resolve(res.data as string),
+ fail: (err) => reject(new Error(formatReadError(path, err.errMsg, hostLabel))),
+ });
+ });
+}
+
+export function mgFileExists(fs: MiniGameFileSystemManager, path: string): Promise<boolean> {
+ return new Promise((resolve) => {
+ fs.access({
+ path,
+ success: () => resolve(true),
+ fail: () => resolve(false),
+ });
+ });
+}
+
+export function mgFileExistsSync(fs: MiniGameFileSystemManager, path: string): boolean {
+ try {
+ fs.accessSync(path);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function mgWriteFile(fs: MiniGameFileSystemManager, path: string, data: string | ArrayBuffer): Promise<void> {
+ return new Promise((resolve, reject) => {
+ fs.writeFile({
+ filePath: path,
+ data,
+ success: () => resolve(),
+ fail: (err) => reject(new Error(`Failed to write file "${path}": ${err.errMsg}`)),
+ });
+ });
+}
diff --git a/sdk/src/platform/minigame/image.ts b/sdk/src/platform/minigame/image.ts
new file mode 100644
index 000000000..e33f87320
--- /dev/null
+++ b/sdk/src/platform/minigame/image.ts
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file image.ts
+ * @brief Image decode over a mini-game host (vendor-neutral): load → draw to
+ * an offscreen 2D canvas → read back pixels.
+ */
+
+import type { ImageLoadResult } from '../types';
+import type { MiniGameGlobal, MiniGameImage } from './api';
+
+function getOffscreenCanvas(g: MiniGameGlobal, width: number, height: number): {
+ ctx: CanvasRenderingContext2D;
+} {
+ const canvas = g.createCanvas();
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
+ return { ctx };
+}
+
+/** Load an image from a package-relative file path. */
+export function mgLoadImage(g: MiniGameGlobal, path: string): Promise<MiniGameImage> {
+ return new Promise((resolve, reject) => {
+ const img = g.createImage();
+ img.onload = () => resolve(img);
+ img.onerror = (err) => reject(new Error(`Failed to load image: ${path}, ${err}`));
+ img.src = path;
+ });
+}
+
+/** Extract RGBA pixel data from a loaded image. */
+export function mgGetImagePixels(g: MiniGameGlobal, img: MiniGameImage): ImageLoadResult {
+ const { width, height } = img;
+ const { ctx } = getOffscreenCanvas(g, width, height);
+
+ ctx.clearRect(0, 0, width, height);
+ ctx.drawImage(img as unknown as CanvasImageSource, 0, 0);
+ const imageData = ctx.getImageData(0, 0, width, height);
+ const pixels = new Uint8Array(imageData.data.buffer);
+
+ return { width, height, pixels };
+}
+
+/** Load an image and read its pixels in one call. */
+export async function mgLoadImagePixels(g: MiniGameGlobal, path: string): Promise<ImageLoadResult> {
+ const img = await mgLoadImage(g, path);
+ return mgGetImagePixels(g, img);
+}
diff --git a/sdk/src/platform/minigame/index.ts b/sdk/src/platform/minigame/index.ts
new file mode 100644
index 000000000..8cec961a8
--- /dev/null
+++ b/sdk/src/platform/minigame/index.ts
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.ts
+ * @brief Mini-game platform family barrel. Vendors (wechat/, douyin/) import
+ * from here to build their profile + adapter.
+ */
+
+export type {
+ MiniGameGlobal,
+ MiniGameProfile,
+ MiniGameVendor,
+ MiniGameCanvas,
+ MiniGameImage,
+ MiniGameFileSystemManager,
+ MiniGameRequestOptions,
+ MiniGameSystemInfo,
+ MiniGameTouch,
+ MiniGameTouchEvent,
+ MiniGameKeyEvent,
+ MiniGameStorageInfo,
+} from './api';
+
+export { MiniGamePlatformAdapter } from './adapter';
+export { polyfillFetch, mgFetch } from './fetch';
+export { polyfillPerformance, polyfillTextEncoder } from './polyfills';
+export {
+ mgReadFile,
+ mgReadTextFile,
+ mgReadFileSync,
+ mgReadTextFileSync,
+ mgFileExists,
+ mgFileExistsSync,
+ mgWriteFile,
+ formatReadError,
+} from './fs';
+export { mgLoadImage, mgGetImagePixels, mgLoadImagePixels } from './image';
diff --git a/sdk/src/platform/minigame/polyfills.ts b/sdk/src/platform/minigame/polyfills.ts
new file mode 100644
index 000000000..ffc12f639
--- /dev/null
+++ b/sdk/src/platform/minigame/polyfills.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file polyfills.ts
+ * @brief Vendor-neutral global polyfills for mini-game runtimes (performance,
+ * TextEncoder/TextDecoder). Fetch and WebAssembly polyfills live with
+ * their implementations (fetch.ts / the vendor's wasm module) because
+ * they depend on the host global / vendor WASM entry point.
+ */
+
+export function polyfillPerformance(): void {
+ const g = globalThis as unknown as { performance?: { now(): number } };
+ if (typeof g.performance !== 'undefined') return;
+ const start = Date.now();
+ g.performance = { now: (): number => Date.now() - start };
+}
+
+export function polyfillTextEncoder(): void {
+ const g = globalThis as unknown as { TextEncoder?: unknown; TextDecoder?: unknown };
+ if (typeof g.TextEncoder === 'undefined') {
+ g.TextEncoder = class {
+ encode(str: string): Uint8Array {
+ const buf = new ArrayBuffer(str.length * 3);
+ const bytes = new Uint8Array(buf);
+ let pos = 0;
+ for (let i = 0; i < str.length; i++) {
+ let code = str.charCodeAt(i);
+ if (code < 0x80) {
+ bytes[pos++] = code;
+ } else if (code < 0x800) {
+ bytes[pos++] = 0xc0 | (code >> 6);
+ bytes[pos++] = 0x80 | (code & 0x3f);
+ } else if (code >= 0xd800 && code <= 0xdbff) {
+ const next = str.charCodeAt(++i);
+ code = ((code - 0xd800) << 10) + (next - 0xdc00) + 0x10000;
+ bytes[pos++] = 0xf0 | (code >> 18);
+ bytes[pos++] = 0x80 | ((code >> 12) & 0x3f);
+ bytes[pos++] = 0x80 | ((code >> 6) & 0x3f);
+ bytes[pos++] = 0x80 | (code & 0x3f);
+ } else {
+ bytes[pos++] = 0xe0 | (code >> 12);
+ bytes[pos++] = 0x80 | ((code >> 6) & 0x3f);
+ bytes[pos++] = 0x80 | (code & 0x3f);
+ }
+ }
+ return bytes.subarray(0, pos);
+ }
+ };
+ }
+ if (typeof g.TextDecoder === 'undefined') {
+ g.TextDecoder = class {
+ decode(buf: ArrayBuffer | Uint8Array): string {
+ const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
+ let str = '';
+ for (let i = 0; i < bytes.length;) {
+ const b = bytes[i];
+ if (b < 0x80) {
+ str += String.fromCharCode(b);
+ i++;
+ } else if ((b & 0xe0) === 0xc0) {
+ str += String.fromCharCode(((b & 0x1f) << 6) | (bytes[i + 1] & 0x3f));
+ i += 2;
+ } else if ((b & 0xf0) === 0xe0) {
+ str += String.fromCharCode(((b & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f));
+ i += 3;
+ } else {
+ const code = ((b & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f);
+ const offset = code - 0x10000;
+ str += String.fromCharCode(0xd800 + (offset >> 10), 0xdc00 + (offset & 0x3ff));
+ i += 4;
+ }
+ }
+ return str;
+ }
+ };
+ }
+}
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index 54cbef4cb..57425a2bd 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -114,7 +114,7 @@ export interface PlatformSocket {
// =============================================================================
export interface PlatformAdapter {
- readonly name: 'web' | 'wechat' | 'node';
+ readonly name: 'web' | 'wechat' | 'douyin' | 'node';
fetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse>;
@@ -187,12 +187,16 @@ export interface PlatformAdapter {
// Platform Detection
// =============================================================================
-export type PlatformType = 'web' | 'wechat';
+export type PlatformType = 'web' | 'wechat' | 'douyin';
export function detectPlatform(): PlatformType {
- // Check for WeChat MiniGame environment
+ // Mini-game hosts expose their API under a vendor global (`tt` = Douyin,
+ // `wx` = WeChat). Probe Douyin first — WeChat never defines `tt`.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const g = globalThis as any;
+ if (typeof g.tt !== 'undefined' && typeof g.tt.getSystemInfoSync === 'function') {
+ return 'douyin';
+ }
if (typeof g.wx !== 'undefined' && typeof g.wx.getSystemInfoSync === 'function') {
return 'wechat';
}
diff --git a/sdk/src/platform/wechat/fs.ts b/sdk/src/platform/wechat/fs.ts
index 6ba532a86..4f9177150 100644
--- a/sdk/src/platform/wechat/fs.ts
+++ b/sdk/src/platform/wechat/fs.ts
@@ -2,135 +2,60 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file fs.ts
- * @brief File system adapter for WeChat MiniGame
- *
- * These are thin wrappers over wx.getFileSystemManager().
- * Path conversion (toBuildPath) is handled at the platform adapter level,
- * not here — this layer is pure I/O.
+ * @brief Public `wx*` filesystem helpers — thin back-compat wrappers that bind
+ * the WeChat filesystem manager to the vendor-neutral family fs (see
+ * ../minigame/fs.ts). Retained because they are part of the public
+ * `esengine/wechat` surface.
*/
/// <reference types="minigame-api-typings" />
-import { isCustomExtension } from '../../assetTypes';
+import type { MiniGameFileSystemManager } from '../minigame';
+import {
+ mgReadFileSync,
+ mgReadTextFileSync,
+ mgReadFile,
+ mgReadTextFile,
+ mgFileExists,
+ mgFileExistsSync,
+ mgWriteFile,
+} from '../minigame';
-// =============================================================================
-// Types
-// =============================================================================
+const HOST_LABEL = 'WeChat';
-type WxFileSystemManager = WechatMinigame.FileSystemManager;
+let fsManager: MiniGameFileSystemManager | null = null;
-// =============================================================================
-// WeChat File System
-// =============================================================================
-
-let fsManager: WxFileSystemManager | null = null;
-
-function getFileSystemManager(): WxFileSystemManager {
+function fs(): MiniGameFileSystemManager {
if (!fsManager) {
- fsManager = wx.getFileSystemManager();
+ fsManager = wx.getFileSystemManager() as unknown as MiniGameFileSystemManager;
}
return fsManager;
}
-function formatReadError(path: string, errMsg: string): string {
- const msg = errMsg.toLowerCase();
- if (msg.includes('permission denied')) {
- if (isCustomExtension(path)) {
- const ext = path.substring(path.lastIndexOf('.'));
- return `[ESEngine] Cannot read "${path}": WeChat blocked access to "${ext}" files. `
- + `Add { type: "suffix", value: "${ext}" } to packOptions.include in project.config.json. `
- + `Some suffixes are denied regardless of packOptions — the exporter restages those `
- + `as "${ext}.bin" (ktx2/esv already are); re-export if this file predates that.`;
- }
- return `[ESEngine] Cannot read "${path}": permission denied. Check file is included in WeChat package`;
- }
- if (msg.includes('no such file') || msg.includes('not found')) {
- return `[ESEngine] File not found: "${path}". Ensure the asset is included in the build `
- + `(referenced by a scene or added to an addressable group with export mode "always")`;
- }
- return `[ESEngine] Failed to read "${path}": ${errMsg}`;
-}
-
export function wxReadFileSync(path: string): ArrayBuffer {
- const fs = getFileSystemManager();
- try {
- return fs.readFileSync(path) as ArrayBuffer;
- } catch (e) {
- throw new Error(formatReadError(path, e instanceof Error ? e.message : String(e)));
- }
+ return mgReadFileSync(fs(), path, HOST_LABEL);
}
export function wxReadTextFileSync(path: string, encoding: 'utf8' | 'utf-8' = 'utf-8'): string {
- const fs = getFileSystemManager();
- try {
- return fs.readFileSync(path, encoding) as string;
- } catch (e) {
- throw new Error(formatReadError(path, e instanceof Error ? e.message : String(e)));
- }
+ return mgReadTextFileSync(fs(), path, HOST_LABEL, encoding);
}
export function wxReadFile(path: string): Promise<ArrayBuffer> {
- return new Promise((resolve, reject) => {
- const fs = getFileSystemManager();
- fs.readFile({
- filePath: path,
- success: (res) => {
- resolve(res.data as ArrayBuffer);
- },
- fail: (err) => {
- reject(new Error(formatReadError(path, err.errMsg)));
- },
- });
- });
+ return mgReadFile(fs(), path, HOST_LABEL);
}
export function wxReadTextFile(path: string, encoding: 'utf8' | 'utf-8' = 'utf-8'): Promise<string> {
- return new Promise((resolve, reject) => {
- const fs = getFileSystemManager();
- fs.readFile({
- filePath: path,
- encoding,
- success: (res) => {
- resolve(res.data as string);
- },
- fail: (err) => {
- reject(new Error(formatReadError(path, err.errMsg)));
- },
- });
- });
+ return mgReadTextFile(fs(), path, HOST_LABEL, encoding);
}
export function wxFileExists(path: string): Promise<boolean> {
- return new Promise((resolve) => {
- const fs = getFileSystemManager();
- fs.access({
- path,
- success: () => resolve(true),
- fail: () => resolve(false),
- });
- });
+ return mgFileExists(fs(), path);
}
export function wxFileExistsSync(path: string): boolean {
- const fs = getFileSystemManager();
- try {
- fs.accessSync(path);
- return true;
- } catch {
- return false;
- }
+ return mgFileExistsSync(fs(), path);
}
export function wxWriteFile(path: string, data: string | ArrayBuffer): Promise<void> {
- return new Promise((resolve, reject) => {
- const fs = getFileSystemManager();
- fs.writeFile({
- filePath: path,
- data,
- success: () => resolve(),
- fail: (err) => {
- reject(new Error(`Failed to write file "${path}": ${err.errMsg}`));
- },
- });
- });
+ return mgWriteFile(fs(), path, data);
}
diff --git a/sdk/src/platform/wechat/image.ts b/sdk/src/platform/wechat/image.ts
index c2a6cbe88..4bcd81616 100644
--- a/sdk/src/platform/wechat/image.ts
+++ b/sdk/src/platform/wechat/image.ts
@@ -2,75 +2,31 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file image.ts
- * @brief WeChat MiniGame image loading utilities
+ * @brief Public `wx*` image helpers — thin back-compat wrappers binding the
+ * WeChat global to the vendor-neutral family image decode
+ * (../minigame/image.ts). Retained as part of `esengine/wechat`.
*/
/// <reference types="minigame-api-typings" />
-// =============================================================================
-// Types
-// =============================================================================
+import type { MiniGameGlobal, MiniGameImage } from '../minigame';
+import { mgLoadImage, mgGetImagePixels, mgLoadImagePixels } from '../minigame';
+import type { ImageLoadResult } from '../types';
-export interface ImageLoadResult {
- width: number;
- height: number;
- pixels: Uint8Array;
-}
-
-// =============================================================================
-// Canvas Management
-// =============================================================================
+export type { ImageLoadResult };
-function getOffscreenCanvas(width: number, height: number): {
- canvas: WechatMinigame.Canvas;
- ctx: CanvasRenderingContext2D;
-} {
- const canvas = wx.createCanvas();
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
- return { canvas, ctx };
+function g(): MiniGameGlobal {
+ return wx as unknown as MiniGameGlobal;
}
-// =============================================================================
-// Image Loading
-// =============================================================================
-
-/**
- * Load an image from a file path
- * @param path - File path relative to game root
- */
-export function wxLoadImage(path: string): Promise<WechatMinigame.Image> {
- return new Promise((resolve, reject) => {
- const img = wx.createImage();
- img.onload = () => resolve(img);
- img.onerror = (err) => reject(new Error(`Failed to load image: ${path}, ${err}`));
- img.src = path;
- });
+export function wxLoadImage(path: string): Promise<MiniGameImage> {
+ return mgLoadImage(g(), path);
}
-/**
- * Extract pixel data from an image
- * @param img - Loaded image object
- */
-export function wxGetImagePixels(img: WechatMinigame.Image): ImageLoadResult {
- const { width, height } = img;
- const { ctx } = getOffscreenCanvas(width, height);
-
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(img as unknown as CanvasImageSource, 0, 0);
- const imageData = ctx.getImageData(0, 0, width, height);
- const pixels = new Uint8Array(imageData.data.buffer);
-
- return { width, height, pixels };
+export function wxGetImagePixels(img: MiniGameImage): ImageLoadResult {
+ return mgGetImagePixels(g(), img);
}
-/**
- * Load image and get pixel data in one call
- * @param path - File path relative to game root
- */
-export async function wxLoadImagePixels(path: string): Promise<ImageLoadResult> {
- const img = await wxLoadImage(path);
- return wxGetImagePixels(img);
+export function wxLoadImagePixels(path: string): Promise<ImageLoadResult> {
+ return mgLoadImagePixels(g(), path);
}
-
diff --git a/sdk/src/platform/wechat/index.ts b/sdk/src/platform/wechat/index.ts
index 8cd90c6cc..9a93f54fd 100644
--- a/sdk/src/platform/wechat/index.ts
+++ b/sdk/src/platform/wechat/index.ts
@@ -2,246 +2,26 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file index.ts
- * @brief WeChat MiniGame platform adapter
+ * @brief WeChat MiniGame platform adapter (a profile of the mini-game family).
+ *
+ * The adapter is the shared family implementation (../minigame/adapter.ts) bound
+ * to the WeChat profile (./profile.ts). This file only wires it up + installs
+ * the WeChat boot polyfills, and preserves the public `wx*` helper surface.
*/
/// <reference types="minigame-api-typings" />
-import type {
- PlatformAdapter,
- PlatformRequestOptions,
- PlatformResponse,
- WasmInstantiateResult,
- InputEventCallbacks,
- ImageLoadResult,
- PlatformSocket,
- PlatformSocketOptions,
-} from '../types';
-import { WeChatSocket } from '../../net/WeChatSocket';
-import { WeChatAudioBackend } from '../../audio/WeChatAudioBackend';
-import type { PlatformAudioBackend } from '../../audio/PlatformAudioBackend';
-import { WasmVideoBackend } from '../../video/WasmVideoBackend';
-import type { PlatformVideoBackend, VideoBackendContext } from '../../video/PlatformVideoBackend';
-import { wxFetch, polyfillFetch } from './fetch';
-import { wxInstantiateWasm, polyfillWebAssembly } from './wasm';
-import { wxReadFileSync, wxReadTextFileSync, wxFileExistsSync } from './fs';
-import { wxLoadImagePixels } from './image';
-import { toBuildPath } from '../../assetTypes';
+import type { MiniGameGlobal } from '../minigame';
+import { MiniGamePlatformAdapter, polyfillFetch, polyfillPerformance, polyfillTextEncoder } from '../minigame';
+import { polyfillWebAssembly } from './wasm';
+import { wechatProfile } from './profile';
import { log } from '../../logger';
// =============================================================================
-// WeChat Platform Adapter
+// Adapter
// =============================================================================
-class WeChatPlatformAdapter implements PlatformAdapter {
- readonly name = 'wechat' as const;
- private inputCleanup_: (() => void) | null = null;
-
- async fetch(url: string, options?: PlatformRequestOptions): Promise<PlatformResponse> {
- return wxFetch(url, options);
- }
-
- async readFile(path: string): Promise<ArrayBuffer> {
- return wxReadFileSync(toBuildPath(path));
- }
-
- async readTextFile(path: string): Promise<string> {
- return wxReadTextFileSync(toBuildPath(path));
- }
-
- async fileExists(path: string): Promise<boolean> {
- return wxFileExistsSync(toBuildPath(path));
- }
-
- async loadImagePixels(path: string): Promise<ImageLoadResult> {
- return wxLoadImagePixels(path);
- }
-
- async instantiateWasm(
- pathOrBuffer: string | ArrayBuffer,
- imports: WebAssembly.Imports
- ): Promise<WasmInstantiateResult> {
- if (typeof pathOrBuffer !== 'string') {
- throw new Error(
- 'WeChat WXWebAssembly requires a file path string, not ArrayBuffer'
- );
- }
- return wxInstantiateWasm(pathOrBuffer, imports);
- }
-
- createImage(): HTMLImageElement {
- return wx.createImage() as unknown as HTMLImageElement;
- }
-
- /** WeChat 分包: download a subpackage so its files become readable. */
- loadSubpackage(name: string): Promise<void> {
- return new Promise<void>((resolve, reject) => {
- wx.loadSubpackage({
- name,
- success: () => resolve(),
- fail: (err: unknown) => reject(new Error(`loadSubpackage("${name}") failed: ${JSON.stringify(err)}`)),
- complete: () => {},
- });
- });
- }
-
- onMemoryWarning(callback: () => void): () => void {
- const listener = () => callback();
- wx.onMemoryWarning(listener);
- return () => wx.offMemoryWarning(listener);
- }
-
- createCanvas(width: number, height: number): HTMLCanvasElement | OffscreenCanvas {
- const canvas = wx.createCanvas() as unknown as HTMLCanvasElement;
- canvas.width = width;
- canvas.height = height;
- return canvas;
- }
-
- now(): number {
- return Date.now();
- }
-
- bindInputEvents(callbacks: InputEventCallbacks, _target?: unknown): void {
- if (this.inputCleanup_) {
- this.inputCleanup_();
- this.inputCleanup_ = null;
- }
-
- type KeyResult = WechatMinigame.OnKeyDownListenerResult;
- type TouchResult = WechatMinigame.OnTouchStartListenerResult;
-
- const onKeyDown = (res: KeyResult) => callbacks.onKeyDown(res.code);
- const onKeyUp = (res: KeyResult) => callbacks.onKeyUp(res.code);
-
- const hasKeyboard = typeof wx.onKeyDown === 'function';
- if (hasKeyboard) {
- wx.onKeyDown(onKeyDown);
- wx.onKeyUp(onKeyUp);
- }
-
- let primaryTouchId: number | null = null;
-
- const onTouchStart = (res: TouchResult) => {
- for (const touch of res.changedTouches) {
- callbacks.onTouchStart?.(touch.identifier, touch.clientX, touch.clientY);
- if (primaryTouchId === null) {
- primaryTouchId = touch.identifier;
- callbacks.onPointerDown(0, touch.clientX, touch.clientY);
- }
- }
- };
- const onTouchMove = (res: TouchResult) => {
- for (const touch of res.changedTouches) {
- callbacks.onTouchMove?.(touch.identifier, touch.clientX, touch.clientY);
- if (touch.identifier === primaryTouchId) {
- callbacks.onPointerMove(touch.clientX, touch.clientY);
- }
- }
- };
- const onTouchEnd = (res: TouchResult) => {
- for (const touch of res.changedTouches) {
- callbacks.onTouchEnd?.(touch.identifier);
- if (touch.identifier === primaryTouchId) {
- primaryTouchId = null;
- callbacks.onPointerUp(0);
- }
- }
- };
-
- wx.onTouchStart(onTouchStart);
- wx.onTouchMove(onTouchMove);
- wx.onTouchEnd(onTouchEnd);
-
- this.inputCleanup_ = () => {
- if (hasKeyboard) {
- wx.offKeyDown(onKeyDown);
- wx.offKeyUp(onKeyUp);
- }
- wx.offTouchStart(onTouchStart);
- wx.offTouchMove(onTouchMove);
- wx.offTouchEnd(onTouchEnd);
- };
- }
-
- unbindInputEvents(): void {
- if (this.inputCleanup_) {
- this.inputCleanup_();
- this.inputCleanup_ = null;
- }
- }
-
- createAudioBackend(): PlatformAudioBackend {
- return new WeChatAudioBackend();
- }
-
- // WeChat gets the engine-owned wasm decoder on every device class. The
- // native wx.createVideoDecoder is deliberately not used: it is absent on the
- // PC client and unreliable on phones (per-device staging, null frames, no
- // playhead), so the deterministic single path is the software decode.
- createVideoBackend(ctx: VideoBackendContext): PlatformVideoBackend {
- return new WasmVideoBackend(ctx);
- }
-
- createSocket(options: PlatformSocketOptions): PlatformSocket {
- return new WeChatSocket(options);
- }
-
- getStorageItem(key: string): string | null {
- try {
- const value = wx.getStorageSync(key);
- return typeof value === 'string' ? value : null;
- } catch {
- return null;
- }
- }
-
- setStorageItem(key: string, value: string): void {
- try {
- wx.setStorageSync(key, value);
- } catch (e) {
- log.warn('wechat', 'setStorageSync failed', e);
- }
- }
-
- removeStorageItem(key: string): void {
- try {
- wx.removeStorageSync(key);
- } catch (e) {
- log.warn('wechat', 'removeStorageSync failed', e);
- }
- }
-
- devicePixelRatio(): number {
- try {
- return wx.getSystemInfoSync?.()?.pixelRatio ?? 1;
- } catch {
- return 1;
- }
- }
-
- language(): string {
- try {
- // WeChat reports 'zh_CN'-style tags; platformLanguage() normalizes.
- return wx.getSystemInfoSync?.()?.language ?? 'en';
- } catch {
- return 'en';
- }
- }
-
- clearStorage(prefix: string): void {
- try {
- const { keys } = wx.getStorageInfoSync();
- for (const k of keys) {
- if (k.startsWith(prefix)) {
- wx.removeStorageSync(k);
- }
- }
- } catch (e) {
- log.warn('wechat', 'clearStorage failed', e);
- }
- }
-}
+export const wechatAdapter = new MiniGamePlatformAdapter(wechatProfile);
// =============================================================================
// Initialization
@@ -250,95 +30,33 @@ class WeChatPlatformAdapter implements PlatformAdapter {
let initialized = false;
/**
- * Initialize WeChat platform polyfills
- * Call this at the entry point of your game
+ * Initialize WeChat platform polyfills.
+ * Call this at the entry point of your game (see index.wechat.ts).
*/
export function initWeChatPlatform(): void {
if (initialized) return;
initialized = true;
polyfillPerformance();
- polyfillFetch();
+ polyfillFetch(wx as unknown as MiniGameGlobal);
polyfillWebAssembly();
polyfillTextEncoder();
log.info('wechat', 'WeChat platform initialized');
}
-function polyfillPerformance(): void {
- const g = globalThis as any;
- if (typeof g.performance !== 'undefined') return;
- const start = Date.now();
- g.performance = { now: (): number => Date.now() - start };
-}
-
-function polyfillTextEncoder(): void {
- const g = globalThis as any;
- if (typeof g.TextEncoder === 'undefined') {
- g.TextEncoder = class {
- encode(str: string): Uint8Array {
- const buf = new ArrayBuffer(str.length * 3);
- const bytes = new Uint8Array(buf);
- let pos = 0;
- for (let i = 0; i < str.length; i++) {
- let code = str.charCodeAt(i);
- if (code < 0x80) {
- bytes[pos++] = code;
- } else if (code < 0x800) {
- bytes[pos++] = 0xc0 | (code >> 6);
- bytes[pos++] = 0x80 | (code & 0x3f);
- } else if (code >= 0xd800 && code <= 0xdbff) {
- const next = str.charCodeAt(++i);
- code = ((code - 0xd800) << 10) + (next - 0xdc00) + 0x10000;
- bytes[pos++] = 0xf0 | (code >> 18);
- bytes[pos++] = 0x80 | ((code >> 12) & 0x3f);
- bytes[pos++] = 0x80 | ((code >> 6) & 0x3f);
- bytes[pos++] = 0x80 | (code & 0x3f);
- } else {
- bytes[pos++] = 0xe0 | (code >> 12);
- bytes[pos++] = 0x80 | ((code >> 6) & 0x3f);
- bytes[pos++] = 0x80 | (code & 0x3f);
- }
- }
- return bytes.subarray(0, pos);
- }
- };
- }
- if (typeof g.TextDecoder === 'undefined') {
- g.TextDecoder = class {
- decode(buf: ArrayBuffer | Uint8Array): string {
- const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
- let str = '';
- for (let i = 0; i < bytes.length;) {
- const b = bytes[i];
- if (b < 0x80) {
- str += String.fromCharCode(b);
- i++;
- } else if ((b & 0xe0) === 0xc0) {
- str += String.fromCharCode(((b & 0x1f) << 6) | (bytes[i + 1] & 0x3f));
- i += 2;
- } else if ((b & 0xf0) === 0xe0) {
- str += String.fromCharCode(((b & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f));
- i += 3;
- } else {
- const code = ((b & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f);
- const offset = code - 0x10000;
- str += String.fromCharCode(0xd800 + (offset >> 10), 0xdc00 + (offset & 0x3ff));
- i += 4;
- }
- }
- return str;
- }
- };
- }
-}
-
// =============================================================================
// Export
// =============================================================================
-export const wechatAdapter = new WeChatPlatformAdapter();
-
-export { polyfillFetch, polyfillWebAssembly };
-export { wxReadFile, wxReadTextFile, wxReadFileSync, wxReadTextFileSync, wxFileExists, wxFileExistsSync, wxWriteFile } from './fs';
+export { polyfillWebAssembly };
+export {
+ wxReadFile,
+ wxReadTextFile,
+ wxReadFileSync,
+ wxReadTextFileSync,
+ wxFileExists,
+ wxFileExistsSync,
+ wxWriteFile,
+} from './fs';
export { wxLoadImage, wxGetImagePixels, wxLoadImagePixels, type ImageLoadResult } from './image';
diff --git a/sdk/src/platform/wechat/profile.ts b/sdk/src/platform/wechat/profile.ts
new file mode 100644
index 000000000..132545271
--- /dev/null
+++ b/sdk/src/platform/wechat/profile.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file profile.ts
+ * @brief WeChat as a profile of the mini-game platform family.
+ *
+ * Everything WeChat shares with other vendors lives in the family adapter
+ * (../minigame/adapter.ts); this file is only the DATA + the genuine WeChat
+ * divergences: the WXWebAssembly loader and the WeChat audio/video/socket
+ * backends.
+ */
+
+/// <reference types="minigame-api-typings" />
+
+import type { MiniGameGlobal, MiniGameProfile } from '../minigame';
+import type { PlatformAudioBackend } from '../../audio/PlatformAudioBackend';
+import type { PlatformVideoBackend, VideoBackendContext } from '../../video/PlatformVideoBackend';
+import type { PlatformSocket, PlatformSocketOptions, WasmInstantiateResult } from '../types';
+import { WeChatAudioBackend } from '../../audio/WeChatAudioBackend';
+import { WeChatSocket } from '../../net/WeChatSocket';
+import { WasmVideoBackend } from '../../video/WasmVideoBackend';
+import { wxInstantiateWasm } from './wasm';
+
+export const wechatProfile: MiniGameProfile = {
+ id: 'wechat',
+ hostLabel: 'WeChat',
+
+ // `wx` is an ambient runtime global; read it lazily so importing this module
+ // outside a WeChat runtime (bundling/tests) never touches an undefined `wx`.
+ get global(): MiniGameGlobal {
+ return wx as unknown as MiniGameGlobal;
+ },
+
+ instantiateWasm(pathOrBuffer: string | ArrayBuffer, imports: WebAssembly.Imports): Promise<WasmInstantiateResult> {
+ if (typeof pathOrBuffer !== 'string') {
+ throw new Error('WeChat WXWebAssembly requires a file path string, not ArrayBuffer');
+ }
+ return wxInstantiateWasm(pathOrBuffer, imports);
+ },
+
+ createAudioBackend(): PlatformAudioBackend {
+ return new WeChatAudioBackend();
+ },
+
+ // WeChat gets the engine-owned wasm decoder on every device class. The
+ // native wx.createVideoDecoder is deliberately not used: it is absent on the
+ // PC client and unreliable on phones (per-device staging, null frames, no
+ // playhead), so the deterministic single path is the software decode.
+ createVideoBackend(ctx: VideoBackendContext): PlatformVideoBackend {
+ return new WasmVideoBackend(ctx);
+ },
+
+ createSocket(options: PlatformSocketOptions): PlatformSocket {
+ return new WeChatSocket(options);
+ },
+};